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::{Parse, Serialize};
12
13use crate::RtmpError;
14use crate::amf0::{Amf0Value, Command};
15use crate::chunk::{ChunkAssembler, ChunkWriter, DEFAULT_MAX_IN_PROGRESS_BYTES, Message};
16use crate::flv_bridge::{FlvTagWriter, unpack_aggregate};
17use crate::handshake::{
18    EchoPacket, HANDSHAKE_PACKET_LEN, HandshakePacket, RTMP_VERSION, Version, default_random_fill,
19};
20use crate::message::{ProtocolControl, UserControl, msg_type};
21
22type Result<T> = core::result::Result<T, RtmpError>;
23
24const COMMAND_CHUNK_STREAM_ID: u32 = 3;
25const VERSION_LEN: usize = 1;
26/// `flashVer` announced in `connect`: the Flash Media Live Encoder
27/// identity that ingest services key their publisher-compatibility
28/// handling on (what ffmpeg/OBS announce; #1108/RTMP-W9).
29const FLASH_VER: &str = "FMLE/3.0 (compatible; rtmp-runtime)";
30/// FMLE-style publish preamble commands sent before `createStream`
31/// (Adobe FMLE publish sequence, as ffmpeg's `rtmpproto` emits it).
32const CMD_RELEASE_STREAM: &str = "releaseStream";
33const CMD_FC_PUBLISH: &str = "FCPublish";
34/// `play` Start argument (§7.2.2.1): `-2` plays the live stream of that name, else a recorded
35/// one, else waits for a live one.
36const PLAY_START_LIVE_OR_RECORDED: f64 = -2.0;
37/// Default playback buffer length announced with SetBufferLength before `play` (§6.7), ms.
38pub const DEFAULT_PLAY_BUFFER_MS: u32 = 3_000;
39const STATUS_PLAY_START: &str = "NetStream.Play.Start";
40const STATUS_PLAY_STOP: &str = "NetStream.Play.Stop";
41const STATUS_PLAY_COMPLETE: &str = "NetStream.Play.Complete";
42const STATUS_PLAY_STREAM_NOT_FOUND: &str = "NetStream.Play.StreamNotFound";
43const STATUS_PLAY_FAILED: &str = "NetStream.Play.Failed";
44const STATUS_LEVEL_ERROR: &str = "error";
45
46/// What a [`ClientSession`] does after `connect` and `createStream`.
47#[non_exhaustive]
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
49pub enum ClientMode {
50    /// `publish` a stream (§7.2.2.6): the session sends audio, video and metadata.
51    #[default]
52    Publish,
53    /// `play` a stream (§7.2.2.1): the session receives audio, video and data.
54    Play,
55}
56
57impl ClientMode {
58    /// The NetStream command this mode ends in.
59    #[must_use]
60    pub fn name(&self) -> &'static str {
61        match self {
62            Self::Publish => "publish",
63            Self::Play => "play",
64        }
65    }
66}
67
68broadcast_common::impl_spec_display!(ClientMode);
69
70/// Configuration for a [`ClientSession`].
71#[non_exhaustive]
72#[derive(Clone)]
73pub struct ClientConfig {
74    /// Publish (default) or play.
75    pub mode: ClientMode,
76    /// Playback buffer length announced to the server before `play` (§6.7 SetBufferLength),
77    /// milliseconds. Play mode only.
78    pub play_buffer_ms: u32,
79    /// Outbound chunk size (§5.4.1).
80    pub chunk_size: u32,
81    /// Window Acknowledgement Size (§5.4.4).
82    pub window_ack_size: u32,
83    /// RTMP `app` name for the `connect` command.
84    pub app: String,
85    /// Publishing name (stream key) for the `publish` command, or the stream name `play` asks
86    /// for in play mode.
87    pub stream_key: String,
88    /// `tcUrl` for the `connect` command (e.g. `rtmp://host/app`).
89    pub tc_url: Option<String>,
90    /// Ceiling on the total payload bytes this session's
91    /// [`ChunkAssembler`] may buffer across **all** in-progress messages
92    /// at once (#1108/RTMP-W1); see
93    /// [`crate::chunk::DEFAULT_MAX_IN_PROGRESS_BYTES`] for the default.
94    pub max_in_progress_bytes: usize,
95}
96
97/// Manual `Debug`: the stream key is a publish secret and never renders
98/// (issue #1142).
99impl core::fmt::Debug for ClientConfig {
100    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
101        f.debug_struct("ClientConfig")
102            .field("mode", &self.mode)
103            .field("play_buffer_ms", &self.play_buffer_ms)
104            .field("chunk_size", &self.chunk_size)
105            .field("window_ack_size", &self.window_ack_size)
106            .field("app", &self.app)
107            .field("stream_key", &"<redacted>")
108            .field("tc_url", &self.tc_url)
109            .field("max_in_progress_bytes", &self.max_in_progress_bytes)
110            .finish()
111    }
112}
113
114impl Default for ClientConfig {
115    fn default() -> Self {
116        Self {
117            mode: ClientMode::Publish,
118            play_buffer_ms: DEFAULT_PLAY_BUFFER_MS,
119            chunk_size: 4096,
120            window_ack_size: 2_500_000,
121            app: String::new(),
122            stream_key: String::new(),
123            tc_url: None,
124            max_in_progress_bytes: DEFAULT_MAX_IN_PROGRESS_BYTES,
125        }
126    }
127}
128
129/// Typed events [`ClientSession::handle_data`] surfaces.
130#[non_exhaustive]
131#[derive(Debug, Clone, PartialEq)]
132pub enum ClientEvent {
133    /// Server accepted `connect`.
134    Connected {
135        /// Properties from `_result`.
136        properties: Vec<(String, Amf0Value)>,
137    },
138    /// Server allocated a stream id.
139    StreamCreated {
140        /// The allocated message stream id.
141        stream_id: u32,
142    },
143    /// Server accepted `publish` — session is now publishing.
144    Publishing,
145    /// Server accepted `play` (`NetStream.Play.Start`): media follows. Play mode only.
146    Playing {
147        /// The server announced the stream as recorded (User Control StreamIsRecorded, §6.7)
148        /// before starting it, so its end is final; a live stream's end is not.
149        recorded: bool,
150    },
151    /// One FLV chunk of played media: the payload of a single Audio(8)/Video(9)/Data-AMF0(18)
152    /// message as an FLV tag (+ `PreviousTagSize`), the very first chunk prefixed with the FLV
153    /// file header. Concatenating every chunk in order yields a valid FLV stream. Play mode only.
154    Media {
155        /// FLV bytes for this tag.
156        flv: Vec<u8>,
157    },
158    /// The played stream ended: User Control Stream EOF (§6.7) or `NetStream.Play.Stop` /
159    /// `NetStream.Play.Complete`. Play mode only.
160    StreamEnded,
161    /// Server returned an error.
162    Error {
163        /// Status code.
164        code: String,
165        /// Description.
166        description: String,
167    },
168    /// Session closed.
169    Closed,
170}
171
172#[derive(Debug, Clone, Copy, PartialEq)]
173enum ClientState {
174    Init,
175    HandshakeDone,
176    ConnectSent { txn_id: f64 },
177    Connected,
178    CreateStreamSent { txn_id: f64 },
179    StreamCreated,
180    PublishSent,
181    Publishing,
182    PlaySent,
183    Playing,
184}
185
186/// Client-side handshake: generate C0+C1, consume S0+S1+S2, produce C2.
187#[derive(Debug)]
188struct ClientHandshake {
189    state: ClientHandshakeState,
190    local_time: u32,
191    local_random: [u8; 1528],
192}
193
194#[derive(Debug)]
195enum ClientHandshakeState {
196    SendC0C1,
197    WaitS0S1S2,
198    Done,
199}
200
201impl ClientHandshake {
202    fn new() -> Self {
203        Self {
204            state: ClientHandshakeState::SendC0C1,
205            local_time: 0,
206            local_random: default_random_fill(),
207        }
208    }
209
210    fn start(&mut self) -> Vec<u8> {
211        let c0 = Version(RTMP_VERSION);
212        let c1 = HandshakePacket {
213            time: self.local_time,
214            zero: 0,
215            random: self.local_random,
216        };
217        let mut out = vec![0u8; VERSION_LEN + HANDSHAKE_PACKET_LEN];
218        c0.serialize_into(&mut out[..VERSION_LEN]).unwrap();
219        c1.serialize_into(&mut out[VERSION_LEN..]).unwrap();
220        self.state = ClientHandshakeState::WaitS0S1S2;
221        out
222    }
223
224    fn read(&mut self, input: &[u8]) -> Result<(Vec<u8>, usize, bool)> {
225        match &self.state {
226            ClientHandshakeState::SendC0C1 => Ok((Vec::new(), 0, false)),
227            ClientHandshakeState::WaitS0S1S2 => {
228                let need = VERSION_LEN + HANDSHAKE_PACKET_LEN + HANDSHAKE_PACKET_LEN;
229                if input.len() < need {
230                    return Err(RtmpError::BufferTooShort {
231                        need,
232                        have: input.len(),
233                        what: "S0+S1+S2",
234                    });
235                }
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 = std::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 (docs/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.payload.get(1..).ok_or(RtmpError::BufferTooShort {
671                need: 1,
672                have: msg.payload.len(),
673                what: "AMF3 command encoding marker byte",
674            })?;
675            let cmd = Command::parse(body)?;
676            self.handle_command(&cmd, out, events)?;
677        }
678        if self.receiving_media() {
679            match msg.message_type_id {
680                msg_type::AUDIO | msg_type::VIDEO | msg_type::DATA_AMF0 => {
681                    self.emit_media(msg.message_type_id, msg.timestamp, &msg.payload, events)?;
682                }
683                msg_type::AGGREGATE => {
684                    unpack_aggregate(msg, |tag_type, timestamp, payload| {
685                        self.emit_media(tag_type, timestamp, payload, events)
686                    })?;
687                }
688                _ => {}
689            }
690        }
691        if msg.message_type_id == msg_type::USER_CONTROL {
692            // #1108/RTMP-W8: servers that probe liveness with User Control
693            // PingRequest (event 6 — FMS/Wowza) got no PingResponse and may
694            // have dropped the publisher; malformed/unrecognised event
695            // types are tolerated, same as the server side's inbound
696            // handling.
697            match UserControl::parse(&msg.payload) {
698                Ok(UserControl::PingRequest(ts)) => {
699                    let reply = UserControl::PingResponse(ts);
700                    out.extend_from_slice(&self.writer.write(&reply.to_message())?);
701                }
702                Ok(UserControl::StreamIsRecorded(_)) if self.receiving_media() => {
703                    self.stream_is_recorded = true;
704                }
705                Ok(UserControl::StreamEof(_)) if self.receiving_media() => {
706                    events.push(ClientEvent::StreamEnded);
707                }
708                _ => {}
709            }
710        }
711        Ok(())
712    }
713
714    fn handle_command(
715        &mut self,
716        cmd: &Command,
717        out: &mut Vec<u8>,
718        events: &mut Vec<ClientEvent>,
719    ) -> Result<()> {
720        match cmd.name.as_str() {
721            "_result" => self.handle_result(cmd, out, events),
722            "_error" => {
723                let (code, desc) = extract_status(&cmd.arguments);
724                events.push(ClientEvent::Error {
725                    code,
726                    description: desc,
727                });
728                Ok(())
729            }
730            "onStatus" => self.handle_on_status(cmd, events),
731            _ => Ok(()),
732        }
733    }
734
735    fn handle_result(
736        &mut self,
737        cmd: &Command,
738        out: &mut Vec<u8>,
739        events: &mut Vec<ClientEvent>,
740    ) -> Result<()> {
741        match self.state {
742            ClientState::ConnectSent { txn_id } if (cmd.transaction_id - txn_id).abs() < 0.5 => {
743                let props = match cmd.arguments.first() {
744                    Some(Amf0Value::Object(pairs)) => pairs.clone(),
745                    _ => Vec::new(),
746                };
747                events.push(ClientEvent::Connected { properties: props });
748                self.state = ClientState::Connected;
749                match self.config.mode {
750                    ClientMode::Play => out.extend_from_slice(&self.build_create_stream()?),
751                    _ => out.extend_from_slice(&self.build_publish_preamble_and_create_stream()?),
752                }
753            }
754            ClientState::CreateStreamSent { txn_id }
755                if (cmd.transaction_id - txn_id).abs() < 0.5 =>
756            {
757                let sid = match cmd.arguments.last() {
758                    Some(Amf0Value::Number(n)) => *n as u32,
759                    _ => 1,
760                };
761                self.stream_id = Some(sid);
762                events.push(ClientEvent::StreamCreated { stream_id: sid });
763                self.state = ClientState::StreamCreated;
764                match self.config.mode {
765                    ClientMode::Play => out.extend_from_slice(&self.build_play()?),
766                    _ => out.extend_from_slice(&self.build_publish()?),
767                }
768            }
769            _ => {}
770        }
771        Ok(())
772    }
773
774    fn handle_on_status(&mut self, cmd: &Command, events: &mut Vec<ClientEvent>) -> Result<()> {
775        let (code, desc) = extract_status(&cmd.arguments);
776        if self.config.mode == ClientMode::Play {
777            let is_error = extract_status_level(&cmd.arguments) == STATUS_LEVEL_ERROR
778                || code == STATUS_PLAY_STREAM_NOT_FOUND
779                || code == STATUS_PLAY_FAILED;
780            if is_error {
781                events.push(ClientEvent::Error {
782                    code,
783                    description: desc,
784                });
785            } else if code == STATUS_PLAY_START {
786                self.state = ClientState::Playing;
787                events.push(ClientEvent::Playing {
788                    recorded: self.stream_is_recorded,
789                });
790            } else if code == STATUS_PLAY_STOP || code == STATUS_PLAY_COMPLETE {
791                events.push(ClientEvent::StreamEnded);
792            }
793            return Ok(());
794        }
795        if code == "NetStream.Publish.Start" {
796            self.state = ClientState::Publishing;
797            events.push(ClientEvent::Publishing);
798        } else {
799            events.push(ClientEvent::Error {
800                code,
801                description: desc,
802            });
803        }
804        Ok(())
805    }
806
807    fn maybe_ack(&mut self, out: &mut Vec<u8>) {
808        if self.ack_threshold == 0 {
809            return;
810        }
811        if self.bytes_received.wrapping_sub(self.bytes_acked) >= u64::from(self.ack_threshold) {
812            let seq = (self.bytes_received & 0xFFFF_FFFF) as u32;
813            let ack = ProtocolControl::Acknowledgement(seq);
814            out.extend_from_slice(
815                &self
816                    .writer
817                    .write(&ack.to_message())
818                    .expect("an Acknowledgement control message (4 bytes) never exceeds the 24-bit message_length field"),
819            );
820            self.bytes_acked = self.bytes_received;
821        }
822    }
823}
824
825fn extract_status_level(args: &[Amf0Value]) -> String {
826    args.iter()
827        .find_map(|arg| match arg {
828            Amf0Value::Object(pairs) => pairs.iter().find_map(|(k, v)| match (k.as_str(), v) {
829                ("level", Amf0Value::String(s)) => Some(s.clone()),
830                _ => None,
831            }),
832            _ => None,
833        })
834        .unwrap_or_default()
835}
836
837fn extract_status(args: &[Amf0Value]) -> (String, String) {
838    for arg in args {
839        if let Amf0Value::Object(pairs) = arg {
840            let code = pairs
841                .iter()
842                .find(|(k, _)| k == "code")
843                .and_then(|(_, v)| match v {
844                    Amf0Value::String(s) => Some(s.clone()),
845                    _ => None,
846                })
847                .unwrap_or_default();
848            let desc = pairs
849                .iter()
850                .find(|(k, _)| k == "description")
851                .and_then(|(_, v)| match v {
852                    Amf0Value::String(s) => Some(s.clone()),
853                    _ => None,
854                })
855                .unwrap_or_default();
856            if !code.is_empty() {
857                return (code, desc);
858            }
859        }
860    }
861    (String::new(), String::new())
862}
863
864#[cfg(test)]
865mod tests {
866    use super::*;
867    use crate::handshake;
868    use crate::server::{ServerConfig, ServerSession};
869
870    #[test]
871    fn client_handshake_round_trip() {
872        let mut client_hs = ClientHandshake::new();
873        let mut server_hs = handshake::Handshake::new();
874
875        let c0_c1 = client_hs.start();
876        assert!(!client_hs.is_done());
877
878        let (s0_s1_s2, consumed, _done) = server_hs.read(&c0_c1).unwrap();
879        assert_eq!(consumed, c0_c1.len());
880
881        let (c2, consumed2, done2) = client_hs.read(&s0_s1_s2).unwrap();
882        assert_eq!(consumed2, s0_s1_s2.len());
883        assert!(done2);
884        assert!(client_hs.is_done());
885        assert_eq!(c2.len(), HANDSHAKE_PACKET_LEN);
886
887        let (_reply, consumed3, done3) = server_hs.read(&c2).unwrap();
888        assert_eq!(consumed3, HANDSHAKE_PACKET_LEN);
889        assert!(done3);
890    }
891
892    /// RTMP-W11 (#1108): S0's version byte used to be parsed and discarded.
893    #[test]
894    fn client_handshake_rejects_bad_s0_version() {
895        let mut client_hs = ClientHandshake::new();
896        let mut server_hs = handshake::Handshake::new();
897        let c0_c1 = client_hs.start();
898        let (mut s0_s1_s2, _consumed, _done) = server_hs.read(&c0_c1).unwrap();
899        s0_s1_s2[0] = 6; // RTMPE, not plain RTMP
900        let err = client_hs.read(&s0_s1_s2).unwrap_err();
901        assert!(matches!(err, RtmpError::Malformed { what: "S0 version" }));
902    }
903
904    /// RTMP-W9 (#1108): after `connect`'s `_result` the client must send
905    /// `releaseStream` -> `FCPublish` -> `createStream` (ffmpeg/OBS/FMLE
906    /// order), and `connect` must carry `flashVer`. Fails without the fix
907    /// (the client sent a bare `createStream`).
908    #[test]
909    fn client_publish_sequence_mirrors_ffmpeg() {
910        let config = ClientConfig {
911            app: "live".to_string(),
912            stream_key: "test_key".to_string(),
913            ..ClientConfig::default()
914        };
915        let mut client = ClientSession::new(config);
916        let mut server = ServerSession::new(
917            ServerConfig::default().with_expected_stream_key(Some("test_key".to_string())),
918        );
919        let c0_c1 = client.start();
920        let (s0_s1_s2, _) = server.handle_data(&c0_c1).unwrap();
921        let (mut to_server, _) = client.handle_data(&s0_s1_s2).unwrap();
922        let mut names = Vec::new();
923        let mut connect_has_flash_ver = false;
924        let mut sniff = ChunkAssembler::new();
925        for round in 0..4 {
926            // Round 0's output starts with C2, which is not chunk data.
927            let skip = if round == 0 { HANDSHAKE_PACKET_LEN } else { 0 };
928            sniff.set_chunk_size(client.config.chunk_size);
929            for m in sniff.push(&to_server[skip..]).unwrap() {
930                if m.message_type_id == msg_type::COMMAND_AMF0 {
931                    let c = Command::parse(&m.payload).unwrap();
932                    if c.name == "connect" {
933                        connect_has_flash_ver = matches!(
934                            c.arguments.first(),
935                            Some(Amf0Value::Object(p)) if p.iter().any(|(k, _)| k == "flashVer")
936                        );
937                    }
938                    names.push(c.name);
939                }
940            }
941            let (to_client, _) = server.handle_data(&to_server).unwrap();
942            let (next, _) = client.handle_data(&to_client).unwrap();
943            to_server = next;
944        }
945        assert!(connect_has_flash_ver);
946        assert_eq!(
947            names,
948            [
949                "connect",
950                "releaseStream",
951                "FCPublish",
952                "createStream",
953                "publish"
954            ]
955        );
956        assert!(client.is_publishing());
957    }
958
959    /// RTMP-W8 (#1108): the client never answered a User Control
960    /// PingRequest (event 6 — FMS/Wowza liveness probe), so a server that
961    /// probes with it got no PingResponse and may drop the publisher.
962    #[test]
963    fn client_replies_to_ping_request_with_ping_response() {
964        let config = ClientConfig {
965            app: "live".to_string(),
966            stream_key: "test_key".to_string(),
967            ..ClientConfig::default()
968        };
969        let mut client = ClientSession::new(config);
970        let c0_c1 = client.start();
971        let mut server = ServerSession::new(
972            ServerConfig::default().with_expected_stream_key(Some("test_key".to_string())),
973        );
974        let (s0_s1_s2, _) = server.handle_data(&c0_c1).unwrap();
975        let (_client_out, _) = client.handle_data(&s0_s1_s2).unwrap();
976
977        let ping = UserControl::PingRequest(0xDEAD_BEEF);
978        let bytes = ChunkWriter::new().write(&ping.to_message()).unwrap();
979
980        let (out, _events) = client.handle_data(&bytes).unwrap();
981        let mut assembler = ChunkAssembler::new();
982        let messages = assembler.push(&out).unwrap();
983        let reply = messages
984            .iter()
985            .find(|m| m.message_type_id == msg_type::USER_CONTROL)
986            .map(|m| UserControl::parse(&m.payload).unwrap());
987        assert_eq!(reply, Some(UserControl::PingResponse(0xDEAD_BEEF)));
988    }
989
990    /// RTMP-W7 (#1108): `SetPeerBandwidth` used to overwrite `ack_threshold`
991    /// with the peer's declared OUTBOUND bandwidth limit — a value with no
992    /// relation to how often we should acknowledge inbound bytes
993    /// (`WindowAckSize`'s job, §5.4.4). It's now tracked separately in
994    /// `peer_bandwidth`, and `ack_threshold` is untouched.
995    #[test]
996    fn set_peer_bandwidth_does_not_corrupt_ack_threshold() {
997        let config = ClientConfig {
998            app: "live".to_string(),
999            stream_key: "test_key".to_string(),
1000            ..ClientConfig::default()
1001        };
1002        let original_ack_threshold_config = config.window_ack_size;
1003        let mut client = ClientSession::new(config.clone());
1004        assert_eq!(client.ack_threshold, original_ack_threshold_config);
1005
1006        // Complete the handshake so `handle_data` dispatches chunk messages
1007        // (rather than still buffering handshake bytes).
1008        let c0_c1 = client.start();
1009        let mut server = ServerSession::new(
1010            ServerConfig::default().with_expected_stream_key(Some("test_key".to_string())),
1011        );
1012        let (s0_s1_s2, _) = server.handle_data(&c0_c1).unwrap();
1013        client.handle_data(&s0_s1_s2).unwrap();
1014
1015        let spb = crate::message::ProtocolControl::SetPeerBandwidth {
1016            ack_window_size: 999_999,
1017            limit_type: crate::message::LimitType::Hard,
1018        };
1019        let bytes = ChunkWriter::new().write(&spb.to_message()).unwrap();
1020        let (_out, _events) = client.handle_data(&bytes).unwrap();
1021
1022        assert_eq!(
1023            client.ack_threshold, original_ack_threshold_config,
1024            "ack_threshold must not be overwritten by SetPeerBandwidth"
1025        );
1026        assert_eq!(client.peer_bandwidth, Some(999_999));
1027    }
1028
1029    #[test]
1030    fn client_connect_flow() {
1031        let config = ClientConfig {
1032            app: "live".to_string(),
1033            stream_key: "test_key".to_string(),
1034            ..ClientConfig::default()
1035        };
1036        let mut client = ClientSession::new(config);
1037        let c0_c1 = client.start();
1038
1039        let mut server = ServerSession::new(
1040            ServerConfig::default().with_expected_stream_key(Some("test_key".to_string())),
1041        );
1042
1043        let (s0_s1_s2, server_events) = server.handle_data(&c0_c1).unwrap();
1044        assert!(server_events.is_empty());
1045
1046        let (client_out, _client_events) = client.handle_data(&s0_s1_s2).unwrap();
1047        assert!(
1048            !client_out.is_empty(),
1049            "client should emit C2 + connect + protocol control"
1050        );
1051
1052        let (server_reply, server_events) = server.handle_data(&client_out).unwrap();
1053        assert!(
1054            server_events
1055                .iter()
1056                .any(|e| matches!(e, crate::server::ServerEvent::Connected { .. })),
1057            "server should see connect: {server_events:?}"
1058        );
1059
1060        let (client_out2, client_events2) = client.handle_data(&server_reply).unwrap();
1061        assert!(
1062            client_events2
1063                .iter()
1064                .any(|e| matches!(e, ClientEvent::Connected { .. })),
1065            "client should see Connected: {client_events2:?}"
1066        );
1067        // `client_out2` alone is not a reliable auto-advance signal: the
1068        // server's connect reply also carries a `SetPeerBandwidth` protocol
1069        // control message, which the client acks unconditionally — so bytes
1070        // come back even if `createStream` itself never fires. Check the
1071        // actual state transition instead (issue #933 finding M2).
1072        let _ = client_out2;
1073        assert!(
1074            matches!(client.state, ClientState::CreateStreamSent { .. }),
1075            "client should auto-advance from Connected to CreateStreamSent: {:?}",
1076            client.state
1077        );
1078    }
1079
1080    /// Drives the full client auto-advance —
1081    /// `connect` -> `createStream` -> `publish` — end to end against a real
1082    /// [`ServerSession`], and asserts every state transition actually
1083    /// happens (issue #933 finding M2: the prior version of this test
1084    /// buried its post-`Connected` assertions inside
1085    /// `if !client_out2.is_empty() { .. }` guards, so a broken auto-advance
1086    /// that emitted no bytes would make the test vacuously pass instead of
1087    /// fail).
1088    #[test]
1089    fn client_full_publish_flow() {
1090        let config = ClientConfig {
1091            app: "live".to_string(),
1092            stream_key: "test_key".to_string(),
1093            ..ClientConfig::default()
1094        };
1095        let mut client = ClientSession::new(config);
1096        let c0_c1 = client.start();
1097
1098        let mut server = ServerSession::new(
1099            ServerConfig::default().with_expected_stream_key(Some("test_key".to_string())),
1100        );
1101
1102        // Handshake.
1103        let (s0_s1_s2, server_events) = server.handle_data(&c0_c1).unwrap();
1104        assert!(server_events.is_empty());
1105
1106        // Client completes the handshake and sends C2 + connect.
1107        let (client_out, client_events) = client.handle_data(&s0_s1_s2).unwrap();
1108        assert!(
1109            !client_out.is_empty(),
1110            "client should emit C2 + connect + protocol control"
1111        );
1112        assert!(
1113            client_events.is_empty(),
1114            "no client events expected before the server replies: {client_events:?}"
1115        );
1116        assert_eq!(client.state, ClientState::ConnectSent { txn_id: 1.0 });
1117
1118        // Server completes the handshake and accepts connect.
1119        let (server_reply, server_events) = server.handle_data(&client_out).unwrap();
1120        assert!(
1121            server_events
1122                .iter()
1123                .any(|e| matches!(e, crate::server::ServerEvent::Connected { .. })),
1124            "server should see connect: {server_events:?}"
1125        );
1126
1127        // Client sees Connected and auto-advances: emits createStream.
1128        let (client_out2, client_events2) = client.handle_data(&server_reply).unwrap();
1129        assert!(
1130            client_events2
1131                .iter()
1132                .any(|e| matches!(e, ClientEvent::Connected { .. })),
1133            "client should see Connected: {client_events2:?}"
1134        );
1135        assert!(
1136            !client_out2.is_empty(),
1137            "client should auto-advance from Connected and emit createStream"
1138        );
1139        assert!(matches!(client.state, ClientState::CreateStreamSent { .. }));
1140
1141        // Server replies to createStream with an allocated stream id.
1142        let (server_reply2, _server_events2) = server.handle_data(&client_out2).unwrap();
1143        assert!(
1144            !server_reply2.is_empty(),
1145            "server should reply to createStream"
1146        );
1147
1148        // Client sees StreamCreated and auto-advances: emits publish.
1149        let (client_out3, client_events3) = client.handle_data(&server_reply2).unwrap();
1150        assert!(
1151            client_events3
1152                .iter()
1153                .any(|e| matches!(e, ClientEvent::StreamCreated { .. })),
1154            "client should see StreamCreated: {client_events3:?}"
1155        );
1156        assert!(
1157            !client_out3.is_empty(),
1158            "client should auto-advance from StreamCreated and emit publish"
1159        );
1160        assert_eq!(client.state, ClientState::PublishSent);
1161
1162        // Server accepts publish.
1163        let (server_reply3, server_events3) = server.handle_data(&client_out3).unwrap();
1164        assert!(
1165            server_events3
1166                .iter()
1167                .any(|e| matches!(e, crate::server::ServerEvent::Publish { .. })),
1168            "server should see publish: {server_events3:?}"
1169        );
1170        assert!(
1171            !server_reply3.is_empty(),
1172            "server should reply onStatus for publish"
1173        );
1174
1175        // Client sees Publishing — the auto-advance has run to completion.
1176        let (_client_out4, client_events4) = client.handle_data(&server_reply3).unwrap();
1177        assert!(
1178            client_events4
1179                .iter()
1180                .any(|e| matches!(e, ClientEvent::Publishing)),
1181            "client should see Publishing: {client_events4:?}"
1182        );
1183        assert_eq!(client.state, ClientState::Publishing);
1184        assert!(client.is_publishing());
1185    }
1186
1187    #[test]
1188    fn send_audio_video_while_publishing() {
1189        let config = ClientConfig {
1190            app: "live".to_string(),
1191            stream_key: "test".to_string(),
1192            ..ClientConfig::default()
1193        };
1194        let mut client = ClientSession::new(config);
1195        client.state = ClientState::Publishing;
1196        client.stream_id = Some(1);
1197
1198        let audio = client.send_audio(100, &[0xAA, 0xBB]).unwrap();
1199        assert!(!audio.is_empty());
1200
1201        let video = client.send_video(200, &[0xCC, 0xDD, 0xEE]).unwrap();
1202        assert!(!video.is_empty());
1203
1204        let meta = client
1205            .send_metadata(&[
1206                ("width".to_string(), Amf0Value::Number(1920.0)),
1207                ("height".to_string(), Amf0Value::Number(1080.0)),
1208            ])
1209            .unwrap();
1210        assert!(!meta.is_empty());
1211    }
1212
1213    /// T15: an Amf0 String over the u16 length cap inside the metadata
1214    /// object must surface as `Err`, not a `to_bytes` panic.
1215    #[test]
1216    fn send_metadata_over_range_string_errors_not_panics() {
1217        let mut client = ClientSession::new(ClientConfig {
1218            app: "live".to_string(),
1219            stream_key: "test".to_string(),
1220            ..ClientConfig::default()
1221        });
1222        client.state = ClientState::Publishing;
1223        client.stream_id = Some(1);
1224        let huge = "x".repeat(usize::from(u16::MAX) + 1);
1225        let r = client.send_metadata(&[("title".to_string(), Amf0Value::String(huge))]);
1226        assert!(matches!(r, Err(RtmpError::Unsupported { .. })), "{r:?}");
1227    }
1228
1229    #[test]
1230    fn send_audio_before_publishing_fails() {
1231        let config = ClientConfig {
1232            app: "live".to_string(),
1233            stream_key: "test".to_string(),
1234            ..ClientConfig::default()
1235        };
1236        let mut client = ClientSession::new(config);
1237        assert!(client.send_audio(0, &[0x00]).is_err());
1238    }
1239
1240    #[test]
1241    fn connect_error_produces_event() {
1242        let config = ClientConfig {
1243            app: "live".to_string(),
1244            stream_key: "test".to_string(),
1245            ..ClientConfig::default()
1246        };
1247        let mut client = ClientSession::new(config);
1248        client.handshake.state = ClientHandshakeState::Done;
1249        client.state = ClientState::ConnectSent { txn_id: 1.0 };
1250
1251        let error_cmd = Command {
1252            name: "_error".to_string(),
1253            transaction_id: 1.0,
1254            arguments: vec![
1255                Amf0Value::Null,
1256                Amf0Value::Object(vec![
1257                    (
1258                        "code".to_string(),
1259                        Amf0Value::String("NetConnection.Connect.Rejected".to_string()),
1260                    ),
1261                    (
1262                        "description".to_string(),
1263                        Amf0Value::String("Connection refused".to_string()),
1264                    ),
1265                ]),
1266            ],
1267        };
1268        let msg = Message {
1269            chunk_stream_id: COMMAND_CHUNK_STREAM_ID,
1270            timestamp: 0,
1271            message_type_id: msg_type::COMMAND_AMF0,
1272            message_stream_id: 0,
1273            payload: error_cmd.to_body().unwrap(),
1274        };
1275        let bytes = ChunkWriter::new().write(&msg).unwrap();
1276
1277        let (_, events) = client.handle_data(&bytes).unwrap();
1278        assert!(
1279            events.iter().any(|e| matches!(
1280                e,
1281                ClientEvent::Error { code, .. } if code == "NetConnection.Connect.Rejected"
1282            )),
1283            "expected Error event: {events:?}"
1284        );
1285    }
1286}