Skip to main content

rtmp_runtime/
client.rs

1//! RTMP client session engine — `connect` → `createStream` → `publish`
2//! (Adobe RTMP 1.0 §7.2, `NetConnection`/`NetStream` commands).
3//!
4//! [`ClientSession`] mirrors [`crate::server::ServerSession`]: a sans-IO
5//! state machine for the **client publish** role. Feed inbound bytes via
6//! [`ClientSession::handle_data`], get back outbound bytes + typed
7//! [`ClientEvent`]s. Auto-advances: a successful `connect` `_result`
8//! automatically emits `createStream`, and a successful `createStream`
9//! `_result` emits `publish`.
10
11use broadcast_common::error::BufferTooShort;
12use broadcast_common::len::need_in;
13use broadcast_common::{Parse, Serialize};
14
15use crate::RtmpError;
16use crate::amf0::{Amf0Value, Command};
17use crate::chunk::{ChunkAssembler, ChunkWriter, DEFAULT_MAX_IN_PROGRESS_BYTES, Message};
18use crate::flv::{FlvTagWriter, unpack_aggregate};
19use crate::handshake::{
20    EchoPacket, HANDSHAKE_PACKET_LEN, HandshakePacket, RTMP_VERSION, Version, default_random_fill,
21};
22use crate::message::{ProtocolControl, UserControl, msg_type};
23use alloc::format;
24use alloc::string::{String, ToString};
25use alloc::vec;
26use alloc::vec::Vec;
27
28type Result<T> = core::result::Result<T, RtmpError>;
29
30const COMMAND_CHUNK_STREAM_ID: u32 = 3;
31const VERSION_LEN: usize = 1;
32/// `flashVer` announced in `connect`: the Flash Media Live Encoder
33/// identity that ingest services key their publisher-compatibility
34/// handling on (what ffmpeg/OBS announce; #1108/RTMP-W9).
35const FLASH_VER: &str = "FMLE/3.0 (compatible; rtmp-runtime)";
36/// FMLE-style publish preamble commands sent before `createStream`
37/// (Adobe FMLE publish sequence, as ffmpeg's `rtmpproto` emits it).
38const CMD_RELEASE_STREAM: &str = "releaseStream";
39const CMD_FC_PUBLISH: &str = "FCPublish";
40/// `play` Start argument (§7.2.2.1): `-2` plays the live stream of that name, else a recorded
41/// one, else waits for a live one.
42const PLAY_START_LIVE_OR_RECORDED: f64 = -2.0;
43/// Default playback buffer length announced with SetBufferLength before `play` (§6.7), ms.
44pub const DEFAULT_PLAY_BUFFER_MS: u32 = 3_000;
45const STATUS_PLAY_START: &str = "NetStream.Play.Start";
46const STATUS_PLAY_STOP: &str = "NetStream.Play.Stop";
47const STATUS_PLAY_COMPLETE: &str = "NetStream.Play.Complete";
48const STATUS_PLAY_STREAM_NOT_FOUND: &str = "NetStream.Play.StreamNotFound";
49const STATUS_PLAY_FAILED: &str = "NetStream.Play.Failed";
50const STATUS_LEVEL_ERROR: &str = "error";
51
52/// What a [`ClientSession`] does after `connect` and `createStream`.
53#[non_exhaustive]
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
55pub enum ClientMode {
56    /// `publish` a stream (§7.2.2.6): the session sends audio, video and metadata.
57    #[default]
58    Publish,
59    /// `play` a stream (§7.2.2.1): the session receives audio, video and data.
60    Play,
61}
62
63impl ClientMode {
64    /// The NetStream command this mode ends in.
65    #[must_use]
66    pub fn name(&self) -> &'static str {
67        match self {
68            Self::Publish => "publish",
69            Self::Play => "play",
70        }
71    }
72}
73
74broadcast_common::impl_spec_display!(ClientMode);
75
76/// Configuration for a [`ClientSession`].
77#[non_exhaustive]
78#[derive(Clone)]
79pub struct ClientConfig {
80    /// Publish (default) or play.
81    pub mode: ClientMode,
82    /// Playback buffer length announced to the server before `play` (§6.7 SetBufferLength),
83    /// milliseconds. Play mode only.
84    pub play_buffer_ms: u32,
85    /// Outbound chunk size (§5.4.1).
86    pub chunk_size: u32,
87    /// Window Acknowledgement Size (§5.4.4).
88    pub window_ack_size: u32,
89    /// RTMP `app` name for the `connect` command.
90    pub app: String,
91    /// Publishing name (stream key) for the `publish` command, or the stream name `play` asks
92    /// for in play mode.
93    pub stream_key: String,
94    /// `tcUrl` for the `connect` command (e.g. `rtmp://host/app`).
95    pub tc_url: Option<String>,
96    /// Ceiling on the total payload bytes this session's
97    /// [`ChunkAssembler`] may buffer across **all** in-progress messages
98    /// at once (#1108/RTMP-W1); see
99    /// [`crate::chunk::DEFAULT_MAX_IN_PROGRESS_BYTES`] for the default.
100    pub max_in_progress_bytes: usize,
101}
102
103/// Manual `Debug`: the stream key is a publish secret and never renders
104/// (issue #1142).
105impl core::fmt::Debug for ClientConfig {
106    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
107        f.debug_struct("ClientConfig")
108            .field("mode", &self.mode)
109            .field("play_buffer_ms", &self.play_buffer_ms)
110            .field("chunk_size", &self.chunk_size)
111            .field("window_ack_size", &self.window_ack_size)
112            .field("app", &self.app)
113            .field("stream_key", &"<redacted>")
114            .field("tc_url", &self.tc_url)
115            .field("max_in_progress_bytes", &self.max_in_progress_bytes)
116            .finish()
117    }
118}
119
120impl Default for ClientConfig {
121    fn default() -> Self {
122        Self {
123            mode: ClientMode::Publish,
124            play_buffer_ms: DEFAULT_PLAY_BUFFER_MS,
125            chunk_size: 4096,
126            window_ack_size: 2_500_000,
127            app: String::new(),
128            stream_key: String::new(),
129            tc_url: None,
130            max_in_progress_bytes: DEFAULT_MAX_IN_PROGRESS_BYTES,
131        }
132    }
133}
134
135/// Typed events [`ClientSession::handle_data`] surfaces.
136#[non_exhaustive]
137#[derive(Debug, Clone, PartialEq)]
138pub enum ClientEvent {
139    /// Server accepted `connect`.
140    Connected {
141        /// Properties from `_result`.
142        properties: Vec<(String, Amf0Value)>,
143    },
144    /// Server allocated a stream id.
145    StreamCreated {
146        /// The allocated message stream id.
147        stream_id: u32,
148    },
149    /// Server accepted `publish` — session is now publishing.
150    Publishing,
151    /// Server accepted `play` (`NetStream.Play.Start`): media follows. Play mode only.
152    Playing {
153        /// The server announced the stream as recorded (User Control StreamIsRecorded, §6.7)
154        /// before starting it, so its end is final; a live stream's end is not.
155        recorded: bool,
156    },
157    /// One FLV chunk of played media: the payload of a single Audio(8)/Video(9)/Data-AMF0(18)
158    /// message as an FLV tag (+ `PreviousTagSize`), the very first chunk prefixed with the FLV
159    /// file header. Concatenating every chunk in order yields a valid FLV stream. Play mode only.
160    Media {
161        /// FLV bytes for this tag.
162        flv: Vec<u8>,
163    },
164    /// The played stream ended: User Control Stream EOF (§6.7) or `NetStream.Play.Stop` /
165    /// `NetStream.Play.Complete`. Play mode only.
166    StreamEnded,
167    /// Server returned an error.
168    Error {
169        /// Status code.
170        code: String,
171        /// Description.
172        description: String,
173    },
174    /// Session closed.
175    Closed,
176}
177
178#[derive(Debug, Clone, Copy, PartialEq)]
179enum ClientState {
180    Init,
181    HandshakeDone,
182    ConnectSent { txn_id: f64 },
183    Connected,
184    CreateStreamSent { txn_id: f64 },
185    StreamCreated,
186    PublishSent,
187    Publishing,
188    PlaySent,
189    Playing,
190}
191
192/// Client-side handshake: generate C0+C1, consume S0+S1+S2, produce C2.
193#[derive(Debug)]
194struct ClientHandshake {
195    state: ClientHandshakeState,
196    local_time: u32,
197    local_random: [u8; 1528],
198}
199
200#[derive(Debug)]
201enum ClientHandshakeState {
202    SendC0C1,
203    WaitS0S1S2,
204    Done,
205}
206
207impl ClientHandshake {
208    fn new() -> Self {
209        Self {
210            state: ClientHandshakeState::SendC0C1,
211            local_time: 0,
212            local_random: default_random_fill(),
213        }
214    }
215
216    fn start(&mut self) -> Vec<u8> {
217        let c0 = Version(RTMP_VERSION);
218        let c1 = HandshakePacket {
219            time: self.local_time,
220            zero: 0,
221            random: self.local_random,
222        };
223        let mut out = vec![0u8; VERSION_LEN + HANDSHAKE_PACKET_LEN];
224        c0.serialize_into(&mut out[..VERSION_LEN]).unwrap();
225        c1.serialize_into(&mut out[VERSION_LEN..]).unwrap();
226        self.state = ClientHandshakeState::WaitS0S1S2;
227        out
228    }
229
230    fn read(&mut self, input: &[u8]) -> Result<(Vec<u8>, usize, bool)> {
231        match &self.state {
232            ClientHandshakeState::SendC0C1 => Ok((Vec::new(), 0, false)),
233            ClientHandshakeState::WaitS0S1S2 => {
234                let need = VERSION_LEN + HANDSHAKE_PACKET_LEN + HANDSHAKE_PACKET_LEN;
235                need_in(input, need, "S0+S1+S2")?;
236                let s0 = Version::parse(&input[..VERSION_LEN])?;
237                // #1108/RTMP-W11: see handshake.rs's identical C0 check.
238                if s0.0 != RTMP_VERSION {
239                    return Err(RtmpError::Malformed { what: "S0 version" });
240                }
241                let s1 = HandshakePacket::parse(
242                    &input[VERSION_LEN..VERSION_LEN + HANDSHAKE_PACKET_LEN],
243                )?;
244                let _s2 = EchoPacket::parse(&input[VERSION_LEN + HANDSHAKE_PACKET_LEN..need])?;
245
246                let c2 = EchoPacket {
247                    time: s1.time,
248                    time2: 0,
249                    random_echo: s1.random,
250                };
251                let mut reply = vec![0u8; HANDSHAKE_PACKET_LEN];
252                c2.serialize_into(&mut reply)?;
253
254                self.state = ClientHandshakeState::Done;
255                Ok((reply, need, true))
256            }
257            ClientHandshakeState::Done => Ok((Vec::new(), 0, true)),
258        }
259    }
260
261    fn is_done(&self) -> bool {
262        matches!(self.state, ClientHandshakeState::Done)
263    }
264}
265
266/// Sans-IO RTMP client publish session.
267#[derive(Debug)]
268pub struct ClientSession {
269    config: ClientConfig,
270    handshake: ClientHandshake,
271    handshake_buf: Vec<u8>,
272    assembler: ChunkAssembler,
273    writer: ChunkWriter,
274    state: ClientState,
275    stream_id: Option<u32>,
276    next_txn_id: f64,
277    ack_threshold: u32,
278    bytes_received: u64,
279    bytes_acked: u64,
280    /// The peer's declared limit on OUR outbound bandwidth (§5.4.5's
281    /// `SetPeerBandwidth`), tracked separately from `ack_threshold`
282    /// (#1108/RTMP-W7): it constrains how much *we send*, not how often
283    /// *we acknowledge received bytes* (that's `WindowAckSize`, §5.4.4).
284    /// Not otherwise enforced by this sans-IO engine (it doesn't do its
285    /// own outbound rate limiting), but kept and exposed rather than
286    /// silently discarded or conflated with `ack_threshold`.
287    peer_bandwidth: Option<u32>,
288    /// The window size we last advertised to the peer via our own
289    /// outbound `WindowAckSize` (distinct from `ack_threshold`, which
290    /// tracks the PEER's advertised window for OUR acking of THEIR
291    /// data — #1108/RTMP-W7).
292    advertised_window_ack_size: u32,
293    flv: FlvTagWriter,
294    stream_is_recorded: bool,
295}
296
297impl ClientSession {
298    /// Create a new client session.
299    #[must_use]
300    pub fn new(config: ClientConfig) -> Self {
301        let ack_threshold = config.window_ack_size;
302        let advertised_window_ack_size = config.window_ack_size;
303        let max_in_progress_bytes = config.max_in_progress_bytes;
304        Self {
305            config,
306            handshake: ClientHandshake::new(),
307            handshake_buf: Vec::new(),
308            assembler: ChunkAssembler::new().with_max_in_progress_bytes(max_in_progress_bytes),
309            writer: ChunkWriter::new(),
310            state: ClientState::Init,
311            stream_id: None,
312            next_txn_id: 1.0,
313            ack_threshold,
314            bytes_received: 0,
315            bytes_acked: 0,
316            peer_bandwidth: None,
317            advertised_window_ack_size,
318            flv: FlvTagWriter::default(),
319            stream_is_recorded: false,
320        }
321    }
322
323    /// Produce C0+C1 handshake bytes. Call once at session start.
324    pub fn start(&mut self) -> Vec<u8> {
325        self.handshake.start()
326    }
327
328    /// Feed inbound bytes. Returns `(outbound bytes, events)`.
329    pub fn handle_data(&mut self, input: &[u8]) -> Result<(Vec<u8>, Vec<ClientEvent>)> {
330        let mut out = Vec::new();
331        let mut events = Vec::new();
332
333        let chunk_input = match self.drive_handshake(input, &mut out, &mut events)? {
334            Some(bytes) => bytes,
335            None => return Ok((out, events)),
336        };
337
338        self.bytes_received = self.bytes_received.saturating_add(chunk_input.len() as u64);
339
340        self.assembler.feed(chunk_input);
341        while let Some(msg) = self.assembler.next_message()? {
342            self.dispatch_message(&msg, &mut out, &mut events)?;
343        }
344
345        self.maybe_ack(&mut out);
346        Ok((out, events))
347    }
348
349    /// Encode an audio message (type 8). Only valid in `Publishing` state.
350    pub fn send_audio(&mut self, timestamp: u32, data: &[u8]) -> Result<Vec<u8>> {
351        if self.state != ClientState::Publishing {
352            return Err(RtmpError::Malformed {
353                what: "send_audio: not in Publishing state",
354            });
355        }
356        let msg = Message {
357            chunk_stream_id: 4,
358            timestamp,
359            message_type_id: msg_type::AUDIO,
360            message_stream_id: self.stream_id.unwrap_or(1),
361            payload: data.to_vec(),
362        };
363        self.writer.write(&msg)
364    }
365
366    /// Encode a video message (type 9). Only valid in `Publishing` state.
367    pub fn send_video(&mut self, timestamp: u32, data: &[u8]) -> Result<Vec<u8>> {
368        if self.state != ClientState::Publishing {
369            return Err(RtmpError::Malformed {
370                what: "send_video: not in Publishing state",
371            });
372        }
373        let msg = Message {
374            chunk_stream_id: 5,
375            timestamp,
376            message_type_id: msg_type::VIDEO,
377            message_stream_id: self.stream_id.unwrap_or(1),
378            payload: data.to_vec(),
379        };
380        self.writer.write(&msg)
381    }
382
383    /// Encode a metadata message (`@setDataFrame`/`onMetaData`, type 18).
384    pub fn send_metadata(&mut self, metadata: &[(String, Amf0Value)]) -> Result<Vec<u8>> {
385        if self.state != ClientState::Publishing {
386            return Err(RtmpError::Malformed {
387                what: "send_metadata: not in Publishing state",
388            });
389        }
390        let mut payload = Amf0Value::String("@setDataFrame".to_string()).try_to_bytes()?;
391        payload.extend(Amf0Value::String("onMetaData".to_string()).try_to_bytes()?);
392        let obj = Amf0Value::Object(metadata.to_vec());
393        payload.extend(obj.try_to_bytes()?);
394        let msg = Message {
395            chunk_stream_id: 4,
396            timestamp: 0,
397            message_type_id: msg_type::DATA_AMF0,
398            message_stream_id: self.stream_id.unwrap_or(1),
399            payload,
400        };
401        self.writer.write(&msg)
402    }
403
404    /// Whether the session has reached `Publishing` state.
405    #[must_use]
406    pub fn is_publishing(&self) -> bool {
407        self.state == ClientState::Publishing
408    }
409
410    fn drive_handshake<'a>(
411        &mut self,
412        input: &'a [u8],
413        out: &mut Vec<u8>,
414        events: &mut Vec<ClientEvent>,
415    ) -> Result<Option<&'a [u8]>> {
416        if self.handshake.is_done() && self.state != ClientState::Init {
417            return Ok(Some(input));
418        }
419
420        self.handshake_buf.extend_from_slice(input);
421
422        if !self.handshake.is_done() {
423            match self.handshake.read(&self.handshake_buf) {
424                Ok((reply, consumed, done)) => {
425                    out.extend_from_slice(&reply);
426                    self.handshake_buf.drain(..consumed);
427                    if done {
428                        self.state = ClientState::HandshakeDone;
429                        out.extend_from_slice(&self.build_connect()?);
430                    }
431                }
432                Err(RtmpError::BufferTooShort(..)) => {
433                    return Ok(None);
434                }
435                Err(e) => return Err(e),
436            }
437        }
438
439        if self.handshake.is_done() && !self.handshake_buf.is_empty() {
440            let remaining = core::mem::take(&mut self.handshake_buf);
441            self.bytes_received = self.bytes_received.saturating_add(remaining.len() as u64);
442            self.assembler.feed(&remaining);
443            while let Some(msg) = self.assembler.next_message()? {
444                self.dispatch_message(&msg, out, events)?;
445            }
446        }
447
448        Ok(None)
449    }
450
451    fn build_connect(&mut self) -> Result<Vec<u8>> {
452        let txn_id = self.next_txn_id;
453        self.next_txn_id += 1.0;
454        self.state = ClientState::ConnectSent { txn_id };
455
456        let tc_url = self
457            .config
458            .tc_url
459            .clone()
460            .unwrap_or_else(|| format!("rtmp://localhost/{}", self.config.app));
461
462        let cmd = Command {
463            name: "connect".to_string(),
464            transaction_id: txn_id,
465            arguments: vec![Amf0Value::Object(vec![
466                (
467                    "app".to_string(),
468                    Amf0Value::String(self.config.app.clone()),
469                ),
470                (
471                    "flashVer".to_string(),
472                    Amf0Value::String(FLASH_VER.to_string()),
473                ),
474                ("tcUrl".to_string(), Amf0Value::String(tc_url)),
475                (
476                    "type".to_string(),
477                    Amf0Value::String("nonprivate".to_string()),
478                ),
479            ])],
480        };
481
482        let mut out = Vec::new();
483
484        let set_chunk_size = ProtocolControl::SetChunkSize(self.config.chunk_size);
485        out.extend_from_slice(&self.writer.write(&set_chunk_size.try_to_message()?)?);
486        self.writer.set_chunk_size(self.config.chunk_size);
487
488        let window_ack = ProtocolControl::WindowAckSize(self.config.window_ack_size);
489        out.extend_from_slice(&self.writer.write(&window_ack.to_message())?);
490
491        let msg = Message {
492            chunk_stream_id: COMMAND_CHUNK_STREAM_ID,
493            timestamp: 0,
494            message_type_id: msg_type::COMMAND_AMF0,
495            message_stream_id: 0,
496            payload: cmd.to_body()?,
497        };
498        out.extend_from_slice(&self.writer.write(&msg)?);
499        Ok(out)
500    }
501
502    /// `releaseStream` + `FCPublish` (each `(null, stream_key)`, fire-and-
503    /// forget: their `_result`s carry transaction ids the state machine
504    /// never waits on) then `createStream` — the ffmpeg/OBS/FMLE sequence
505    /// some CDN ingest front ends require (#1108/RTMP-W9).
506    fn build_publish_preamble_and_create_stream(&mut self) -> Result<Vec<u8>> {
507        let mut out = Vec::new();
508        for name in [CMD_RELEASE_STREAM, CMD_FC_PUBLISH] {
509            let txn_id = self.next_txn_id;
510            self.next_txn_id += 1.0;
511            let cmd = Command {
512                name: name.to_string(),
513                transaction_id: txn_id,
514                arguments: vec![
515                    Amf0Value::Null,
516                    Amf0Value::String(self.config.stream_key.clone()),
517                ],
518            };
519            let msg = Message {
520                chunk_stream_id: COMMAND_CHUNK_STREAM_ID,
521                timestamp: 0,
522                message_type_id: msg_type::COMMAND_AMF0,
523                message_stream_id: 0,
524                payload: cmd.to_body()?,
525            };
526            out.extend_from_slice(&self.writer.write(&msg)?);
527        }
528        out.extend_from_slice(&self.build_create_stream()?);
529        Ok(out)
530    }
531
532    fn build_create_stream(&mut self) -> Result<Vec<u8>> {
533        let txn_id = self.next_txn_id;
534        self.next_txn_id += 1.0;
535        self.state = ClientState::CreateStreamSent { txn_id };
536
537        let cmd = Command {
538            name: "createStream".to_string(),
539            transaction_id: txn_id,
540            arguments: vec![Amf0Value::Null],
541        };
542        let msg = Message {
543            chunk_stream_id: COMMAND_CHUNK_STREAM_ID,
544            timestamp: 0,
545            message_type_id: msg_type::COMMAND_AMF0,
546            message_stream_id: 0,
547            payload: cmd.to_body()?,
548        };
549        self.writer.write(&msg)
550    }
551
552    fn build_publish(&mut self) -> Result<Vec<u8>> {
553        self.state = ClientState::PublishSent;
554
555        let cmd = Command {
556            name: "publish".to_string(),
557            transaction_id: 0.0,
558            arguments: vec![
559                Amf0Value::Null,
560                Amf0Value::String(self.config.stream_key.clone()),
561                Amf0Value::String("live".to_string()),
562            ],
563        };
564        let msg = Message {
565            chunk_stream_id: COMMAND_CHUNK_STREAM_ID,
566            timestamp: 0,
567            message_type_id: msg_type::COMMAND_AMF0,
568            message_stream_id: self.stream_id.unwrap_or(1),
569            payload: cmd.to_body()?,
570        };
571        self.writer.write(&msg)
572    }
573
574    /// `SetBufferLength` (§6.7) then `play` (§7.2.2.1) on the created stream.
575    fn build_play(&mut self) -> Result<Vec<u8>> {
576        self.state = ClientState::PlaySent;
577        let stream_id = self.stream_id.unwrap_or(1);
578        let mut out = Vec::new();
579        let buffer = UserControl::SetBufferLength {
580            stream_id,
581            buffer_ms: self.config.play_buffer_ms,
582        };
583        out.extend_from_slice(&self.writer.write(&buffer.to_message())?);
584        let cmd = Command {
585            name: "play".to_string(),
586            transaction_id: 0.0,
587            arguments: vec![
588                Amf0Value::Null,
589                Amf0Value::String(self.config.stream_key.clone()),
590                Amf0Value::Number(PLAY_START_LIVE_OR_RECORDED),
591            ],
592        };
593        let msg = Message {
594            chunk_stream_id: COMMAND_CHUNK_STREAM_ID,
595            timestamp: 0,
596            message_type_id: msg_type::COMMAND_AMF0,
597            message_stream_id: stream_id,
598            payload: cmd.to_body()?,
599        };
600        out.extend_from_slice(&self.writer.write(&msg)?);
601        Ok(out)
602    }
603
604    fn receiving_media(&self) -> bool {
605        matches!(self.state, ClientState::PlaySent | ClientState::Playing)
606    }
607
608    fn emit_media(
609        &mut self,
610        tag_type: u8,
611        timestamp: u32,
612        payload: &[u8],
613        events: &mut Vec<ClientEvent>,
614    ) -> Result<()> {
615        let flv = self.flv.tag(tag_type, timestamp, payload)?;
616        events.push(ClientEvent::Media { flv });
617        Ok(())
618    }
619
620    fn dispatch_message(
621        &mut self,
622        msg: &Message,
623        out: &mut Vec<u8>,
624        events: &mut Vec<ClientEvent>,
625    ) -> Result<()> {
626        if let Some(pc) = ProtocolControl::from_message(msg)? {
627            match pc {
628                ProtocolControl::SetChunkSize(size) => {
629                    self.assembler.set_chunk_size(size);
630                }
631                ProtocolControl::WindowAckSize(size) => {
632                    self.ack_threshold = size;
633                }
634                ProtocolControl::SetPeerBandwidth {
635                    ack_window_size, ..
636                } => {
637                    // #1108/RTMP-W7: §5.4.5 limits the RECEIVER's (i.e.
638                    // our) *output* bandwidth — it says nothing about how
639                    // often we acknowledge inbound bytes, which is
640                    // `WindowAckSize`'s job (§5.4.4) and already handled by
641                    // the arm above. This used to overwrite `ack_threshold`
642                    // with the peer's bandwidth-limit value, and echo that
643                    // same value back as if it were our own advertised
644                    // window. Track it separately; reply with our OWN
645                    // configured window size, and only when it actually
646                    // changed from what we last advertised (private/specs-verified/rtmp/rtmp-runtime/rtmp.md
647                    // §5.4.5: "Receiver SHOULD reply with Window Ack Size
648                    // if its window differs from the last one it
649                    // advertised").
650                    self.peer_bandwidth = Some(ack_window_size);
651                    if self.advertised_window_ack_size != self.config.window_ack_size {
652                        self.advertised_window_ack_size = self.config.window_ack_size;
653                        let ack = ProtocolControl::WindowAckSize(self.advertised_window_ack_size);
654                        out.extend_from_slice(&self.writer.write(&ack.to_message())?);
655                    }
656                }
657                // #1108/RTMP-W2: was ignored — see `ChunkAssembler::abort`'s doc.
658                ProtocolControl::Abort { chunk_stream_id } => {
659                    self.assembler.abort(chunk_stream_id);
660                }
661                _ => {}
662            }
663            return Ok(());
664        }
665        if msg.message_type_id == msg_type::COMMAND_AMF0 {
666            let cmd = Command::parse(&msg.payload)?;
667            self.handle_command(&cmd, out, events)?;
668        }
669        if msg.message_type_id == msg_type::COMMAND_AMF3 {
670            let body = msg
671                .payload
672                .get(1..)
673                .ok_or(RtmpError::BufferTooShort(BufferTooShort {
674                    need: 1,
675                    have: msg.payload.len(),
676                    what: "AMF3 command encoding marker byte",
677                }))?;
678            let cmd = Command::parse(body)?;
679            self.handle_command(&cmd, out, events)?;
680        }
681        if self.receiving_media() {
682            match msg.message_type_id {
683                msg_type::AUDIO | msg_type::VIDEO | msg_type::DATA_AMF0 => {
684                    self.emit_media(msg.message_type_id, msg.timestamp, &msg.payload, events)?;
685                }
686                msg_type::AGGREGATE => {
687                    unpack_aggregate(msg, |tag_type, timestamp, payload| {
688                        self.emit_media(tag_type, timestamp, payload, events)
689                    })?;
690                }
691                _ => {}
692            }
693        }
694        if msg.message_type_id == msg_type::USER_CONTROL {
695            // #1108/RTMP-W8: servers that probe liveness with User Control
696            // PingRequest (event 6 — FMS/Wowza) got no PingResponse and may
697            // have dropped the publisher; malformed/unrecognised event
698            // types are tolerated, same as the server side's inbound
699            // handling.
700            match UserControl::parse(&msg.payload) {
701                Ok(UserControl::PingRequest(ts)) => {
702                    let reply = UserControl::PingResponse(ts);
703                    out.extend_from_slice(&self.writer.write(&reply.to_message())?);
704                }
705                Ok(UserControl::StreamIsRecorded(_)) if self.receiving_media() => {
706                    self.stream_is_recorded = true;
707                }
708                Ok(UserControl::StreamEof(_)) if self.receiving_media() => {
709                    events.push(ClientEvent::StreamEnded);
710                }
711                _ => {}
712            }
713        }
714        Ok(())
715    }
716
717    fn handle_command(
718        &mut self,
719        cmd: &Command,
720        out: &mut Vec<u8>,
721        events: &mut Vec<ClientEvent>,
722    ) -> Result<()> {
723        match cmd.name.as_str() {
724            "_result" => self.handle_result(cmd, out, events),
725            "_error" => {
726                let (code, desc) = extract_status(&cmd.arguments);
727                events.push(ClientEvent::Error {
728                    code,
729                    description: desc,
730                });
731                Ok(())
732            }
733            "onStatus" => self.handle_on_status(cmd, events),
734            _ => Ok(()),
735        }
736    }
737
738    fn handle_result(
739        &mut self,
740        cmd: &Command,
741        out: &mut Vec<u8>,
742        events: &mut Vec<ClientEvent>,
743    ) -> Result<()> {
744        match self.state {
745            ClientState::ConnectSent { txn_id } if (cmd.transaction_id - txn_id).abs() < 0.5 => {
746                let props = match cmd.arguments.first() {
747                    Some(Amf0Value::Object(pairs)) => pairs.clone(),
748                    _ => Vec::new(),
749                };
750                events.push(ClientEvent::Connected { properties: props });
751                self.state = ClientState::Connected;
752                match self.config.mode {
753                    ClientMode::Play => out.extend_from_slice(&self.build_create_stream()?),
754                    _ => out.extend_from_slice(&self.build_publish_preamble_and_create_stream()?),
755                }
756            }
757            ClientState::CreateStreamSent { txn_id }
758                if (cmd.transaction_id - txn_id).abs() < 0.5 =>
759            {
760                let sid = match cmd.arguments.last() {
761                    Some(Amf0Value::Number(n)) => *n as u32,
762                    _ => 1,
763                };
764                self.stream_id = Some(sid);
765                events.push(ClientEvent::StreamCreated { stream_id: sid });
766                self.state = ClientState::StreamCreated;
767                match self.config.mode {
768                    ClientMode::Play => out.extend_from_slice(&self.build_play()?),
769                    _ => out.extend_from_slice(&self.build_publish()?),
770                }
771            }
772            _ => {}
773        }
774        Ok(())
775    }
776
777    fn handle_on_status(&mut self, cmd: &Command, events: &mut Vec<ClientEvent>) -> Result<()> {
778        let (code, desc) = extract_status(&cmd.arguments);
779        if self.config.mode == ClientMode::Play {
780            let is_error = extract_status_level(&cmd.arguments) == STATUS_LEVEL_ERROR
781                || code == STATUS_PLAY_STREAM_NOT_FOUND
782                || code == STATUS_PLAY_FAILED;
783            if is_error {
784                events.push(ClientEvent::Error {
785                    code,
786                    description: desc,
787                });
788            } else if code == STATUS_PLAY_START {
789                self.state = ClientState::Playing;
790                events.push(ClientEvent::Playing {
791                    recorded: self.stream_is_recorded,
792                });
793            } else if code == STATUS_PLAY_STOP || code == STATUS_PLAY_COMPLETE {
794                events.push(ClientEvent::StreamEnded);
795            }
796            return Ok(());
797        }
798        if code == "NetStream.Publish.Start" {
799            self.state = ClientState::Publishing;
800            events.push(ClientEvent::Publishing);
801        } else {
802            events.push(ClientEvent::Error {
803                code,
804                description: desc,
805            });
806        }
807        Ok(())
808    }
809
810    fn maybe_ack(&mut self, out: &mut Vec<u8>) {
811        if self.ack_threshold == 0 {
812            return;
813        }
814        if self.bytes_received.wrapping_sub(self.bytes_acked) >= u64::from(self.ack_threshold) {
815            let seq = (self.bytes_received & 0xFFFF_FFFF) as u32;
816            let ack = ProtocolControl::Acknowledgement(seq);
817            out.extend_from_slice(
818                &self
819                    .writer
820                    .write(&ack.to_message())
821                    .expect("an Acknowledgement control message (4 bytes) never exceeds the 24-bit message_length field"),
822            );
823            self.bytes_acked = self.bytes_received;
824        }
825    }
826}
827
828fn extract_status_level(args: &[Amf0Value]) -> String {
829    args.iter()
830        .find_map(|arg| match arg {
831            Amf0Value::Object(pairs) => pairs.iter().find_map(|(k, v)| match (k.as_str(), v) {
832                ("level", Amf0Value::String(s)) => Some(s.clone()),
833                _ => None,
834            }),
835            _ => None,
836        })
837        .unwrap_or_default()
838}
839
840fn extract_status(args: &[Amf0Value]) -> (String, String) {
841    for arg in args {
842        if let Amf0Value::Object(pairs) = arg {
843            let code = pairs
844                .iter()
845                .find(|(k, _)| k == "code")
846                .and_then(|(_, v)| match v {
847                    Amf0Value::String(s) => Some(s.clone()),
848                    _ => None,
849                })
850                .unwrap_or_default();
851            let desc = pairs
852                .iter()
853                .find(|(k, _)| k == "description")
854                .and_then(|(_, v)| match v {
855                    Amf0Value::String(s) => Some(s.clone()),
856                    _ => None,
857                })
858                .unwrap_or_default();
859            if !code.is_empty() {
860                return (code, desc);
861            }
862        }
863    }
864    (String::new(), String::new())
865}
866
867#[cfg(test)]
868mod tests {
869    use super::*;
870    use crate::handshake;
871    use crate::server::{ServerConfig, ServerSession};
872
873    #[test]
874    fn client_handshake_round_trip() {
875        let mut client_hs = ClientHandshake::new();
876        let mut server_hs = handshake::Handshake::new();
877
878        let c0_c1 = client_hs.start();
879        assert!(!client_hs.is_done());
880
881        let (s0_s1_s2, consumed, _done) = server_hs.read(&c0_c1).unwrap();
882        assert_eq!(consumed, c0_c1.len());
883
884        let (c2, consumed2, done2) = client_hs.read(&s0_s1_s2).unwrap();
885        assert_eq!(consumed2, s0_s1_s2.len());
886        assert!(done2);
887        assert!(client_hs.is_done());
888        assert_eq!(c2.len(), HANDSHAKE_PACKET_LEN);
889
890        let (_reply, consumed3, done3) = server_hs.read(&c2).unwrap();
891        assert_eq!(consumed3, HANDSHAKE_PACKET_LEN);
892        assert!(done3);
893    }
894
895    /// RTMP-W11 (#1108): S0's version byte used to be parsed and discarded.
896    #[test]
897    fn client_handshake_rejects_bad_s0_version() {
898        let mut client_hs = ClientHandshake::new();
899        let mut server_hs = handshake::Handshake::new();
900        let c0_c1 = client_hs.start();
901        let (mut s0_s1_s2, _consumed, _done) = server_hs.read(&c0_c1).unwrap();
902        s0_s1_s2[0] = 6; // RTMPE, not plain RTMP
903        let err = client_hs.read(&s0_s1_s2).unwrap_err();
904        assert!(matches!(err, RtmpError::Malformed { what: "S0 version" }));
905    }
906
907    /// RTMP-W9 (#1108): after `connect`'s `_result` the client must send
908    /// `releaseStream` -> `FCPublish` -> `createStream` (ffmpeg/OBS/FMLE
909    /// order), and `connect` must carry `flashVer`. Fails without the fix
910    /// (the client sent a bare `createStream`).
911    #[test]
912    fn client_publish_sequence_mirrors_ffmpeg() {
913        let config = ClientConfig {
914            app: "live".to_string(),
915            stream_key: "test_key".to_string(),
916            ..ClientConfig::default()
917        };
918        let mut client = ClientSession::new(config);
919        let mut server = ServerSession::new(
920            ServerConfig::default().with_expected_stream_key(Some("test_key".to_string())),
921        );
922        let c0_c1 = client.start();
923        let (s0_s1_s2, _) = server.handle_data(&c0_c1).unwrap();
924        let (mut to_server, _) = client.handle_data(&s0_s1_s2).unwrap();
925        let mut names = Vec::new();
926        let mut connect_has_flash_ver = false;
927        let mut sniff = ChunkAssembler::new();
928        for round in 0..4 {
929            // Round 0's output starts with C2, which is not chunk data.
930            let skip = if round == 0 { HANDSHAKE_PACKET_LEN } else { 0 };
931            sniff.set_chunk_size(client.config.chunk_size);
932            for m in sniff.push(&to_server[skip..]).unwrap() {
933                if m.message_type_id == msg_type::COMMAND_AMF0 {
934                    let c = Command::parse(&m.payload).unwrap();
935                    if c.name == "connect" {
936                        connect_has_flash_ver = matches!(
937                            c.arguments.first(),
938                            Some(Amf0Value::Object(p)) if p.iter().any(|(k, _)| k == "flashVer")
939                        );
940                    }
941                    names.push(c.name);
942                }
943            }
944            let (to_client, _) = server.handle_data(&to_server).unwrap();
945            let (next, _) = client.handle_data(&to_client).unwrap();
946            to_server = next;
947        }
948        assert!(connect_has_flash_ver);
949        assert_eq!(
950            names,
951            [
952                "connect",
953                "releaseStream",
954                "FCPublish",
955                "createStream",
956                "publish"
957            ]
958        );
959        assert!(client.is_publishing());
960    }
961
962    /// RTMP-W8 (#1108): the client never answered a User Control
963    /// PingRequest (event 6 — FMS/Wowza liveness probe), so a server that
964    /// probes with it got no PingResponse and may drop the publisher.
965    #[test]
966    fn client_replies_to_ping_request_with_ping_response() {
967        let config = ClientConfig {
968            app: "live".to_string(),
969            stream_key: "test_key".to_string(),
970            ..ClientConfig::default()
971        };
972        let mut client = ClientSession::new(config);
973        let c0_c1 = client.start();
974        let mut server = ServerSession::new(
975            ServerConfig::default().with_expected_stream_key(Some("test_key".to_string())),
976        );
977        let (s0_s1_s2, _) = server.handle_data(&c0_c1).unwrap();
978        let (_client_out, _) = client.handle_data(&s0_s1_s2).unwrap();
979
980        let ping = UserControl::PingRequest(0xDEAD_BEEF);
981        let bytes = ChunkWriter::new().write(&ping.to_message()).unwrap();
982
983        let (out, _events) = client.handle_data(&bytes).unwrap();
984        let mut assembler = ChunkAssembler::new();
985        let messages = assembler.push(&out).unwrap();
986        let reply = messages
987            .iter()
988            .find(|m| m.message_type_id == msg_type::USER_CONTROL)
989            .map(|m| UserControl::parse(&m.payload).unwrap());
990        assert_eq!(reply, Some(UserControl::PingResponse(0xDEAD_BEEF)));
991    }
992
993    /// RTMP-W7 (#1108): `SetPeerBandwidth` used to overwrite `ack_threshold`
994    /// with the peer's declared OUTBOUND bandwidth limit — a value with no
995    /// relation to how often we should acknowledge inbound bytes
996    /// (`WindowAckSize`'s job, §5.4.4). It's now tracked separately in
997    /// `peer_bandwidth`, and `ack_threshold` is untouched.
998    #[test]
999    fn set_peer_bandwidth_does_not_corrupt_ack_threshold() {
1000        let config = ClientConfig {
1001            app: "live".to_string(),
1002            stream_key: "test_key".to_string(),
1003            ..ClientConfig::default()
1004        };
1005        let original_ack_threshold_config = config.window_ack_size;
1006        let mut client = ClientSession::new(config.clone());
1007        assert_eq!(client.ack_threshold, original_ack_threshold_config);
1008
1009        // Complete the handshake so `handle_data` dispatches chunk messages
1010        // (rather than still buffering handshake bytes).
1011        let c0_c1 = client.start();
1012        let mut server = ServerSession::new(
1013            ServerConfig::default().with_expected_stream_key(Some("test_key".to_string())),
1014        );
1015        let (s0_s1_s2, _) = server.handle_data(&c0_c1).unwrap();
1016        client.handle_data(&s0_s1_s2).unwrap();
1017
1018        let spb = crate::message::ProtocolControl::SetPeerBandwidth {
1019            ack_window_size: 999_999,
1020            limit_type: crate::message::LimitType::Hard,
1021        };
1022        let bytes = ChunkWriter::new().write(&spb.to_message()).unwrap();
1023        let (_out, _events) = client.handle_data(&bytes).unwrap();
1024
1025        assert_eq!(
1026            client.ack_threshold, original_ack_threshold_config,
1027            "ack_threshold must not be overwritten by SetPeerBandwidth"
1028        );
1029        assert_eq!(client.peer_bandwidth, Some(999_999));
1030    }
1031
1032    #[test]
1033    fn client_connect_flow() {
1034        let config = ClientConfig {
1035            app: "live".to_string(),
1036            stream_key: "test_key".to_string(),
1037            ..ClientConfig::default()
1038        };
1039        let mut client = ClientSession::new(config);
1040        let c0_c1 = client.start();
1041
1042        let mut server = ServerSession::new(
1043            ServerConfig::default().with_expected_stream_key(Some("test_key".to_string())),
1044        );
1045
1046        let (s0_s1_s2, server_events) = server.handle_data(&c0_c1).unwrap();
1047        assert!(server_events.is_empty());
1048
1049        let (client_out, _client_events) = client.handle_data(&s0_s1_s2).unwrap();
1050        assert!(
1051            !client_out.is_empty(),
1052            "client should emit C2 + connect + protocol control"
1053        );
1054
1055        let (server_reply, server_events) = server.handle_data(&client_out).unwrap();
1056        assert!(
1057            server_events
1058                .iter()
1059                .any(|e| matches!(e, crate::server::ServerEvent::Connected { .. })),
1060            "server should see connect: {server_events:?}"
1061        );
1062
1063        let (client_out2, client_events2) = client.handle_data(&server_reply).unwrap();
1064        assert!(
1065            client_events2
1066                .iter()
1067                .any(|e| matches!(e, ClientEvent::Connected { .. })),
1068            "client should see Connected: {client_events2:?}"
1069        );
1070        // `client_out2` alone is not a reliable auto-advance signal: the
1071        // server's connect reply also carries a `SetPeerBandwidth` protocol
1072        // control message, which the client acks unconditionally — so bytes
1073        // come back even if `createStream` itself never fires. Check the
1074        // actual state transition instead (issue #933 finding M2).
1075        let _ = client_out2;
1076        assert!(
1077            matches!(client.state, ClientState::CreateStreamSent { .. }),
1078            "client should auto-advance from Connected to CreateStreamSent: {:?}",
1079            client.state
1080        );
1081    }
1082
1083    /// Drives the full client auto-advance —
1084    /// `connect` -> `createStream` -> `publish` — end to end against a real
1085    /// [`ServerSession`], and asserts every state transition actually
1086    /// happens (issue #933 finding M2: the prior version of this test
1087    /// buried its post-`Connected` assertions inside
1088    /// `if !client_out2.is_empty() { .. }` guards, so a broken auto-advance
1089    /// that emitted no bytes would make the test vacuously pass instead of
1090    /// fail).
1091    #[test]
1092    fn client_full_publish_flow() {
1093        let config = ClientConfig {
1094            app: "live".to_string(),
1095            stream_key: "test_key".to_string(),
1096            ..ClientConfig::default()
1097        };
1098        let mut client = ClientSession::new(config);
1099        let c0_c1 = client.start();
1100
1101        let mut server = ServerSession::new(
1102            ServerConfig::default().with_expected_stream_key(Some("test_key".to_string())),
1103        );
1104
1105        // Handshake.
1106        let (s0_s1_s2, server_events) = server.handle_data(&c0_c1).unwrap();
1107        assert!(server_events.is_empty());
1108
1109        // Client completes the handshake and sends C2 + connect.
1110        let (client_out, client_events) = client.handle_data(&s0_s1_s2).unwrap();
1111        assert!(
1112            !client_out.is_empty(),
1113            "client should emit C2 + connect + protocol control"
1114        );
1115        assert!(
1116            client_events.is_empty(),
1117            "no client events expected before the server replies: {client_events:?}"
1118        );
1119        assert_eq!(client.state, ClientState::ConnectSent { txn_id: 1.0 });
1120
1121        // Server completes the handshake and accepts connect.
1122        let (server_reply, server_events) = server.handle_data(&client_out).unwrap();
1123        assert!(
1124            server_events
1125                .iter()
1126                .any(|e| matches!(e, crate::server::ServerEvent::Connected { .. })),
1127            "server should see connect: {server_events:?}"
1128        );
1129
1130        // Client sees Connected and auto-advances: emits createStream.
1131        let (client_out2, client_events2) = client.handle_data(&server_reply).unwrap();
1132        assert!(
1133            client_events2
1134                .iter()
1135                .any(|e| matches!(e, ClientEvent::Connected { .. })),
1136            "client should see Connected: {client_events2:?}"
1137        );
1138        assert!(
1139            !client_out2.is_empty(),
1140            "client should auto-advance from Connected and emit createStream"
1141        );
1142        assert!(matches!(client.state, ClientState::CreateStreamSent { .. }));
1143
1144        // Server replies to createStream with an allocated stream id.
1145        let (server_reply2, _server_events2) = server.handle_data(&client_out2).unwrap();
1146        assert!(
1147            !server_reply2.is_empty(),
1148            "server should reply to createStream"
1149        );
1150
1151        // Client sees StreamCreated and auto-advances: emits publish.
1152        let (client_out3, client_events3) = client.handle_data(&server_reply2).unwrap();
1153        assert!(
1154            client_events3
1155                .iter()
1156                .any(|e| matches!(e, ClientEvent::StreamCreated { .. })),
1157            "client should see StreamCreated: {client_events3:?}"
1158        );
1159        assert!(
1160            !client_out3.is_empty(),
1161            "client should auto-advance from StreamCreated and emit publish"
1162        );
1163        assert_eq!(client.state, ClientState::PublishSent);
1164
1165        // Server accepts publish.
1166        let (server_reply3, server_events3) = server.handle_data(&client_out3).unwrap();
1167        assert!(
1168            server_events3
1169                .iter()
1170                .any(|e| matches!(e, crate::server::ServerEvent::Publish { .. })),
1171            "server should see publish: {server_events3:?}"
1172        );
1173        assert!(
1174            !server_reply3.is_empty(),
1175            "server should reply onStatus for publish"
1176        );
1177
1178        // Client sees Publishing — the auto-advance has run to completion.
1179        let (_client_out4, client_events4) = client.handle_data(&server_reply3).unwrap();
1180        assert!(
1181            client_events4
1182                .iter()
1183                .any(|e| matches!(e, ClientEvent::Publishing)),
1184            "client should see Publishing: {client_events4:?}"
1185        );
1186        assert_eq!(client.state, ClientState::Publishing);
1187        assert!(client.is_publishing());
1188    }
1189
1190    #[test]
1191    fn send_audio_video_while_publishing() {
1192        let config = ClientConfig {
1193            app: "live".to_string(),
1194            stream_key: "test".to_string(),
1195            ..ClientConfig::default()
1196        };
1197        let mut client = ClientSession::new(config);
1198        client.state = ClientState::Publishing;
1199        client.stream_id = Some(1);
1200
1201        let audio = client.send_audio(100, &[0xAA, 0xBB]).unwrap();
1202        assert!(!audio.is_empty());
1203
1204        let video = client.send_video(200, &[0xCC, 0xDD, 0xEE]).unwrap();
1205        assert!(!video.is_empty());
1206
1207        let meta = client
1208            .send_metadata(&[
1209                ("width".to_string(), Amf0Value::Number(1920.0)),
1210                ("height".to_string(), Amf0Value::Number(1080.0)),
1211            ])
1212            .unwrap();
1213        assert!(!meta.is_empty());
1214    }
1215
1216    /// T15: an Amf0 String over the u16 length cap inside the metadata
1217    /// object must surface as `Err`, not a `to_bytes` panic.
1218    #[test]
1219    fn send_metadata_over_range_string_errors_not_panics() {
1220        let mut client = ClientSession::new(ClientConfig {
1221            app: "live".to_string(),
1222            stream_key: "test".to_string(),
1223            ..ClientConfig::default()
1224        });
1225        client.state = ClientState::Publishing;
1226        client.stream_id = Some(1);
1227        let huge = "x".repeat(usize::from(u16::MAX) + 1);
1228        let r = client.send_metadata(&[("title".to_string(), Amf0Value::String(huge))]);
1229        assert!(matches!(r, Err(RtmpError::Unsupported { .. })), "{r:?}");
1230    }
1231
1232    #[test]
1233    fn send_audio_before_publishing_fails() {
1234        let config = ClientConfig {
1235            app: "live".to_string(),
1236            stream_key: "test".to_string(),
1237            ..ClientConfig::default()
1238        };
1239        let mut client = ClientSession::new(config);
1240        assert!(matches!(
1241            client.send_audio(0, &[0x00]),
1242            Err(crate::error::RtmpError::Malformed { .. })
1243        ));
1244    }
1245
1246    #[test]
1247    fn connect_error_produces_event() {
1248        let config = ClientConfig {
1249            app: "live".to_string(),
1250            stream_key: "test".to_string(),
1251            ..ClientConfig::default()
1252        };
1253        let mut client = ClientSession::new(config);
1254        client.handshake.state = ClientHandshakeState::Done;
1255        client.state = ClientState::ConnectSent { txn_id: 1.0 };
1256
1257        let error_cmd = Command {
1258            name: "_error".to_string(),
1259            transaction_id: 1.0,
1260            arguments: vec![
1261                Amf0Value::Null,
1262                Amf0Value::Object(vec![
1263                    (
1264                        "code".to_string(),
1265                        Amf0Value::String("NetConnection.Connect.Rejected".to_string()),
1266                    ),
1267                    (
1268                        "description".to_string(),
1269                        Amf0Value::String("Connection refused".to_string()),
1270                    ),
1271                ]),
1272            ],
1273        };
1274        let msg = Message {
1275            chunk_stream_id: COMMAND_CHUNK_STREAM_ID,
1276            timestamp: 0,
1277            message_type_id: msg_type::COMMAND_AMF0,
1278            message_stream_id: 0,
1279            payload: error_cmd.to_body().unwrap(),
1280        };
1281        let bytes = ChunkWriter::new().write(&msg).unwrap();
1282
1283        let (_, events) = client.handle_data(&bytes).unwrap();
1284        assert!(
1285            events.iter().any(|e| matches!(
1286                e,
1287                ClientEvent::Error { code, .. } if code == "NetConnection.Connect.Rejected"
1288            )),
1289            "expected Error event: {events:?}"
1290        );
1291    }
1292}