Skip to main content

rtmp_runtime/
client.rs

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