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