Skip to main content

rtmp_runtime/
io.rs

1//! Async `tokio` socket adapter driving the sans-IO ingest server session
2//! over a real `tokio::net::TcpStream` — the Layer-2 adapter (see
3//! `private/specs-verified/rtmp/rtmp-runtime/rtmp.md` § Layer-2 adapter; mirrors the
4//! `rtsp_runtime::io` tokio adapter shape in this same workspace).
5//!
6//! [`ServerSession`] never touches a socket: it turns inbound bytes into
7//! `(reply bytes, [`ServerEvent`]s)`. This module owns the stream as a
8//! [`tokio_util::codec::Framed`] whose decoder feeds every inbound chunk to
9//! [`ServerSession::handle_data`], writes the reply bytes back, and returns
10//! the events — no business logic beyond that plumbing.
11//!
12//! [`ServerSession::handle_data`] buffers partial handshake/chunk input
13//! internally (see its doc comment), so unlike an RTSP or HTTP adapter this
14//! one does not need to detect message boundaries itself: any chunk size,
15//! split anywhere, is fine to feed straight through.
16//!
17//! Every awaited IO is bounded by [`Timeouts`] (W1 SP1.3).
18
19use std::io;
20use std::net::SocketAddr;
21use std::pin::Pin;
22
23use futures_util::{SinkExt, StreamExt};
24use tokio::io::{AsyncRead, AsyncWrite};
25use tokio::net::{TcpListener, TcpStream, ToSocketAddrs};
26use tokio::time::Instant;
27use tokio_util::codec::Framed;
28
29use crate::amf0::Amf0Value;
30use crate::client::{ClientEvent, ClientSession, RtmpClientConfig as SessionClientConfig};
31use crate::codec::{ClientCodec, RtmpSession, ServerCodec, SessionCodec, io_err};
32use crate::ids::Timestamp;
33use crate::server::{ServerEvent, ServerSession};
34use crate::target::RtmpTarget;
35use broadcast_net::timeouts::Timeouts;
36
37fn timed_out(what: &str) -> io::Error {
38    io::Error::new(io::ErrorKind::TimedOut, format!("RTMP {what} timed out"))
39}
40
41/// What an [`AsyncRtmpServer`] is configured by: the sans-IO session settings
42/// and the [`Timeouts`] on every awaited I/O. Build it with
43/// [`RtmpServerConfig::new`], then `with_session`.
44#[derive(Debug, Clone)]
45#[non_exhaustive]
46pub struct RtmpServerConfig {
47    /// The settings each accepted connection's [`ServerSession`] is built from.
48    pub session: crate::server::RtmpServerConfig,
49    /// Bounds on every awaited I/O of every accepted connection.
50    pub timeouts: Timeouts,
51}
52
53impl RtmpServerConfig {
54    /// A config with the caller's `session` settings and `timeouts`.
55    #[must_use]
56    pub fn new(session: crate::server::RtmpServerConfig, timeouts: Timeouts) -> Self {
57        RtmpServerConfig { session, timeouts }
58    }
59
60    /// Replace [`RtmpServerConfig::session`].
61    #[must_use]
62    pub fn with_session(mut self, session: crate::server::RtmpServerConfig) -> Self {
63        self.session = session;
64        self
65    }
66
67    /// Replace [`RtmpServerConfig::timeouts`].
68    #[must_use]
69    pub fn with_timeouts(mut self, timeouts: Timeouts) -> Self {
70        self.timeouts = timeouts;
71        self
72    }
73}
74
75/// A `tokio::net::TcpListener` that accepts inbound RTMP publishers and hands
76/// back a driven [`RtmpConnection`] per connection.
77#[derive(Debug)]
78pub struct AsyncRtmpServer {
79    listener: TcpListener,
80    config: RtmpServerConfig,
81}
82
83impl AsyncRtmpServer {
84    /// Binds a listen address (e.g. `"0.0.0.0:1935"`, the IANA-assigned RTMP
85    /// port). The config's session settings are cloned into a fresh
86    /// [`ServerSession`] for each accepted connection, and its [`Timeouts`]
87    /// bound every awaited I/O of that connection.
88    pub async fn bind<A: ToSocketAddrs>(addr: A, config: RtmpServerConfig) -> io::Result<Self> {
89        let listener = TcpListener::bind(addr).await?;
90        Ok(Self { listener, config })
91    }
92
93    /// Accepts the next inbound connection and wraps it with a fresh
94    /// [`ServerSession`] built from this server's [`RtmpServerConfig::session`].
95    pub async fn accept(&self) -> io::Result<AcceptedRtmpConnection> {
96        let (stream, peer) = self.listener.accept().await?;
97        Ok(AcceptedRtmpConnection::new(
98            RtmpConnection::from_stream(
99                stream,
100                RtmpServerConfig {
101                    session: self.config.session.clone(),
102                    timeouts: self.config.timeouts,
103                },
104            ),
105            peer,
106        ))
107    }
108
109    /// The address this server is actually bound to (useful for `":0"`
110    /// ephemeral-port binds).
111    pub fn local_addr(&self) -> io::Result<SocketAddr> {
112        self.listener.local_addr()
113    }
114}
115
116#[derive(Debug)]
117struct Driver<S, T: RtmpSession> {
118    framed: Framed<S, SessionCodec<T>>,
119    /// Events decoded but not yet handed to the caller. Set synchronously
120    /// together with the reply bytes, so a cancelled flush leaves both in place
121    /// for the next call.
122    ready: Option<Vec<<T as RtmpSession>::Event>>,
123    /// Once set, the connection is done (clean EOF, an end-of-stream event, a
124    /// prior `RtmpError` or a timeout) and further calls return `None` without
125    /// touching the socket again.
126    closed: bool,
127    handshake_deadline: Option<Instant>,
128    /// Armed when a wait starts and cleared only when a batch with events is handed
129    /// out, so `read_idle` bounds a whole frame/batch, not each (possibly empty) chunk
130    /// a peer drips.
131    idle_deadline: Option<Instant>,
132    timeouts: Timeouts,
133}
134
135impl<S: AsyncRead + AsyncWrite + Unpin, T: RtmpSession> Driver<S, T> {
136    fn new(framed: Framed<S, SessionCodec<T>>, timeouts: Timeouts) -> Self {
137        Self {
138            framed,
139            ready: None,
140            closed: false,
141            handshake_deadline: Some(Instant::now() + timeouts.handshake),
142            idle_deadline: None,
143            timeouts,
144        }
145    }
146
147    async fn next_events(&mut self) -> io::Result<Option<Vec<T::Event>>> {
148        if self.closed {
149            return Ok(None);
150        }
151        loop {
152            match tokio::time::timeout(self.timeouts.write, self.framed.flush()).await {
153                Err(_) => {
154                    self.closed = true;
155                    return Err(timed_out("write"));
156                }
157                Ok(Err(e)) => {
158                    self.closed = true;
159                    return Err(e);
160                }
161                Ok(Ok(())) => {}
162            }
163            if let Some(events) = self.ready.take() {
164                if events.iter().any(T::opens_stream) {
165                    self.handshake_deadline = None;
166                }
167                if events.iter().any(T::is_eof) {
168                    self.closed = true;
169                }
170                if !events.is_empty() {
171                    self.idle_deadline = None;
172                }
173                return Ok(Some(events));
174            }
175            let read_idle = self.timeouts.read_idle;
176            let idle = *self
177                .idle_deadline
178                .get_or_insert_with(|| Instant::now() + read_idle);
179            let (deadline, what) = match self.handshake_deadline {
180                Some(h) if h < idle => (h, "handshake"),
181                _ => (idle, "read"),
182            };
183            match tokio::time::timeout_at(deadline, self.framed.next()).await {
184                Err(_) => {
185                    self.closed = true;
186                    return Err(timed_out(what));
187                }
188                Ok(None) => {
189                    self.closed = true;
190                    return Ok(None);
191                }
192                Ok(Some(Err(e))) => {
193                    self.closed = true;
194                    return Err(e);
195                }
196                Ok(Some(Ok(events))) => {
197                    let reply = self.framed.codec_mut().take_reply();
198                    self.framed.write_buffer_mut().extend_from_slice(&reply);
199                    self.ready = Some(events);
200                }
201            }
202        }
203    }
204}
205
206/// An erased, transport-agnostic inbound byte stream: an accepted TCP socket,
207/// a TLS stream wrapping one, or a test's in-memory pipe.
208pub trait RtmpStream: AsyncRead + AsyncWrite + Unpin + Send {}
209
210impl<T: AsyncRead + AsyncWrite + Unpin + Send> RtmpStream for T {}
211
212/// `RtmpConnection`'s default stream type — the erased form — so a caller
213/// naming one `RtmpConnection` does not name its transport.
214pub type BoxStream = Pin<Box<dyn RtmpStream>>;
215
216/// A connection [`AsyncRtmpServer::accept`] just took off its listen socket:
217/// the publisher's address (which its erased stream cannot report) and the
218/// connection itself.
219pub struct AcceptedRtmpConnection {
220    peer: SocketAddr,
221    conn: RtmpConnection,
222}
223
224impl core::fmt::Debug for AcceptedRtmpConnection {
225    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
226        f.debug_struct("AcceptedRtmpConnection")
227            .field("peer", &self.peer)
228            .finish_non_exhaustive()
229    }
230}
231
232impl AcceptedRtmpConnection {
233    /// Wrap an already-accepted connection with the peer it came from.
234    pub fn new(conn: RtmpConnection, peer: SocketAddr) -> Self {
235        Self { peer, conn }
236    }
237
238    /// The remote address of the publisher.
239    pub fn peer_addr(&self) -> SocketAddr {
240        self.peer
241    }
242
243    /// The connection, ready for [`RtmpConnection::next_events`].
244    pub fn into_connection(self) -> RtmpConnection {
245        self.conn
246    }
247}
248
249/// One accepted RTMP connection: a stream (an erased [`BoxStream`] by
250/// default) driving a [`ServerSession`].
251///
252/// [`next_events`](Self::next_events) is the whole surface: read a chunk,
253/// drive the session, write the reply, return the events.
254#[derive(Debug)]
255pub struct RtmpConnection<S = BoxStream> {
256    driver: Driver<S, ServerSession>,
257}
258
259impl RtmpConnection<BoxStream> {
260    /// Wraps an already-connected stream, erasing its type, and drives the
261    /// session `config` carries: the constructor [`AsyncRtmpServer::accept`]
262    /// uses, so one `RtmpConnection` names the connection whatever the
263    /// transport. [`RtmpServerConfig::new`] carries a fresh session (a
264    /// [`RtmpServerConfig`]) and the caller's [`Timeouts`].
265    pub fn from_stream<S>(stream: S, config: RtmpServerConfig) -> Self
266    where
267        S: RtmpStream + 'static,
268    {
269        let erased: BoxStream = Box::pin(stream);
270        Self {
271            driver: Driver::new(
272                Framed::new(erased, ServerCodec::new(ServerSession::new(config.session))),
273                config.timeouts,
274            ),
275        }
276    }
277
278    /// Reads one chunk from the socket, drives [`ServerSession::handle_data`],
279    /// writes the reply bytes back (all of them), and returns the resulting
280    /// events.
281    ///
282    /// Returns `Ok(None)` when the connection is finished: the peer closed
283    /// the socket (clean EOF), or the most recent batch of events included
284    /// [`ServerEvent::Eof`] (so the caller sees that final batch once, then
285    /// `None` on the next call). Once a call returns `None`, every
286    /// subsequent call also returns `None` without reading the socket again.
287    ///
288    /// Cancel-safe: dropping the future at any await point loses neither a reply
289    /// byte nor an event (the reply sits in the framed write buffer, the events
290    /// in `self`, until a later call delivers them).
291    ///
292    /// # Errors
293    /// An [`io::Error`] from the underlying socket read/write, or a mapped
294    /// [`RtmpError`](crate::RtmpError) (kind [`io::ErrorKind::InvalidData`])
295    /// from [`ServerSession::handle_data`]. On an `RtmpError` the session is
296    /// unrecoverable (per `handle_data`'s own doc): this connection is torn
297    /// down immediately — marked closed and not driven further, even if the
298    /// caller keeps calling `next_events`. A deadline expiry
299    /// ([`Timeouts`]) is [`io::ErrorKind::TimedOut`] and closes the
300    /// connection too.
301    pub async fn next_events(&mut self) -> io::Result<Option<Vec<ServerEvent>>> {
302        self.driver.next_events().await
303    }
304}
305
306/// What an [`AsyncRtmpClient`] is configured by: the publish target and the
307/// session settings and the [`Timeouts`] on every awaited I/O. Build it with
308/// `RtmpClientConfig::new` and `with_timeouts`.
309#[derive(Debug, Clone)]
310#[non_exhaustive]
311pub struct RtmpClientConfig {
312    /// The server to publish to (app, stream key, `tcUrl`).
313    pub target: RtmpTarget,
314    /// The settings the [`ClientSession`] is built from; `app`, `stream_key` and `tc_url` are
315    /// replaced by the `target`'s.
316    pub session: SessionClientConfig,
317    /// Bounds on every awaited I/O; `connect` bounds the DNS lookup and TCP
318    /// connect.
319    pub timeouts: Timeouts,
320}
321
322impl RtmpClientConfig {
323    /// A config publishing to `target` with the caller's `session` settings, bounded by the
324    /// caller's `timeouts`.
325    pub fn new(target: RtmpTarget, session: SessionClientConfig, timeouts: Timeouts) -> Self {
326        RtmpClientConfig {
327            target,
328            session,
329            timeouts,
330        }
331    }
332
333    /// Replace [`RtmpClientConfig::timeouts`].
334    #[must_use]
335    pub fn with_timeouts(mut self, timeouts: Timeouts) -> Self {
336        self.timeouts = timeouts;
337        self
338    }
339}
340
341/// A publishing RTMP client over a stream (a [`TcpStream`] by default): the
342/// adapter for [`ClientSession`], mirroring
343/// [`RtmpConnection`]. Every awaited IO is bounded by the config's [`Timeouts`].
344#[derive(Debug)]
345pub struct AsyncRtmpClient<S = TcpStream> {
346    driver: Driver<S, ClientSession>,
347}
348
349impl AsyncRtmpClient<TcpStream> {
350    /// DNS + TCP connect bounded by the config's `timeouts.connect`; `publish`
351    /// is NOT started.
352    ///
353    /// An `rtmps` target is refused: this adapter opens plain TCP, and sending
354    /// RTMP in the clear to a TLS port (443) would leak the stream key. Wrap a
355    /// TLS stream and use [`AsyncRtmpClient::from_stream`] instead.
356    pub async fn connect(config: RtmpClientConfig) -> io::Result<Self> {
357        if config.target.tls {
358            return Err(io::Error::new(
359                io::ErrorKind::Unsupported,
360                "rtmps needs a TLS stream: wrap one and use AsyncRtmpClient::from_stream",
361            ));
362        }
363        let stream = tokio::time::timeout(config.timeouts.connect, async {
364            let addrs = config.target.resolve().await?;
365            TcpStream::connect(&addrs[..]).await
366        })
367        .await
368        .map_err(|_| timed_out("connect"))??;
369        Ok(Self::from_stream(stream, config))
370    }
371}
372
373impl<S: AsyncRead + AsyncWrite + Unpin> AsyncRtmpClient<S> {
374    /// Wraps an already-connected stream (e.g. a TLS one, for an `rtmps`
375    /// target); the handshake bytes are queued and go out with the first call
376    /// that flushes.
377    pub fn from_stream(stream: S, config: RtmpClientConfig) -> Self {
378        let mut cfg = config.session;
379        cfg.app = config.target.app.clone();
380        cfg.stream_key = config.target.stream_key.clone();
381        cfg.tc_url = Some(config.target.tc_url().to_owned());
382        let mut codec = ClientCodec::new(ClientSession::new(cfg));
383        let c0c1 = codec.session_mut().start();
384        let mut framed = Framed::new(stream, codec);
385        framed.write_buffer_mut().extend_from_slice(&c0c1);
386        Self {
387            driver: Driver::new(framed, config.timeouts),
388        }
389    }
390
391    /// Runs handshake -> connect -> createStream -> publish; returns once the
392    /// server accepted the publish. Bounded by [`Timeouts::handshake`] as a
393    /// whole. A server error (`ClientEvent::Error`) is
394    /// [`io::ErrorKind::ConnectionRefused`].
395    pub async fn publish(&mut self) -> io::Result<()> {
396        loop {
397            let Some(events) = self.next_events().await? else {
398                return Err(io::Error::new(
399                    io::ErrorKind::UnexpectedEof,
400                    "peer closed during publish",
401                ));
402            };
403            for e in &events {
404                match e {
405                    ClientEvent::Publishing => return Ok(()),
406                    ClientEvent::Error { code, description } => {
407                        return Err(io::Error::new(
408                            io::ErrorKind::ConnectionRefused,
409                            format!("{code}: {description}"),
410                        ));
411                    }
412                    _ => {}
413                }
414            }
415        }
416    }
417
418    /// Queues one already-framed message and flushes it under `timeouts.write`. A
419    /// cancel during the flush leaves the message queued (sent by the next call),
420    /// never half-framed.
421    async fn queue(&mut self, bytes: Vec<u8>) -> io::Result<()> {
422        self.driver
423            .framed
424            .write_buffer_mut()
425            .extend_from_slice(&bytes);
426        match tokio::time::timeout(self.driver.timeouts.write, self.driver.framed.flush()).await {
427            Err(_) => Err(timed_out("write")),
428            Ok(r) => r,
429        }
430    }
431
432    /// Sends one audio message (FLV audio tag body) at `timestamp`, carried on
433    /// the wire as whole milliseconds.
434    ///
435    /// The adapter reads inbound traffic (server acks, pings, errors) only inside
436    /// [`next_events`](Self::next_events); a caller that only sends must also drive
437    /// `next_events` (e.g. in a `select!`) or the server's acknowledgement window
438    /// is never serviced.
439    pub async fn send_audio(&mut self, timestamp: Timestamp, data: &[u8]) -> io::Result<()> {
440        let bytes = self.encode_audio(timestamp, data)?;
441        self.queue(bytes).await
442    }
443
444    /// Sends one video message (FLV video tag body) at `timestamp`, carried on
445    /// the wire as whole milliseconds.
446    pub async fn send_video(&mut self, timestamp: Timestamp, data: &[u8]) -> io::Result<()> {
447        let bytes = self.encode_video(timestamp, data)?;
448        self.queue(bytes).await
449    }
450
451    /// Sends `@setDataFrame`/`onMetaData` stream metadata.
452    pub async fn send_metadata(&mut self, metadata: &[(String, Amf0Value)]) -> io::Result<()> {
453        let bytes = self.encode_metadata(metadata)?;
454        self.queue(bytes).await
455    }
456
457    /// Sans-IO half of [`send_audio`](Self::send_audio): the chunk-stream-framed
458    /// message bytes for one audio tag, **without writing**. Lets a caller
459    /// driving its own egress (e.g. `multimux`'s `PushTransportEgress`) frame a
460    /// message now and write it verbatim later via
461    /// [`write_frame`](Self::write_frame).
462    pub fn encode_audio(&mut self, timestamp: Timestamp, data: &[u8]) -> io::Result<Vec<u8>> {
463        self.driver
464            .framed
465            .codec_mut()
466            .session_mut()
467            .send_audio(timestamp, data)
468            .map_err(io_err)
469    }
470
471    /// Sans-IO half of [`send_video`](Self::send_video) — see
472    /// [`encode_audio`](Self::encode_audio).
473    pub fn encode_video(&mut self, timestamp: Timestamp, data: &[u8]) -> io::Result<Vec<u8>> {
474        self.driver
475            .framed
476            .codec_mut()
477            .session_mut()
478            .send_video(timestamp, data)
479            .map_err(io_err)
480    }
481
482    /// Sans-IO half of [`send_metadata`](Self::send_metadata) — see
483    /// [`encode_audio`](Self::encode_audio).
484    pub fn encode_metadata(&mut self, metadata: &[(String, Amf0Value)]) -> io::Result<Vec<u8>> {
485        self.driver
486            .framed
487            .codec_mut()
488            .session_mut()
489            .send_metadata(metadata)
490            .map_err(io_err)
491    }
492
493    /// Sans-IO half of sending one message of a
494    /// [`publish_open`](crate::flv::publish_open) plan — see
495    /// [`encode_audio`](Self::encode_audio).
496    pub fn encode_publish_message(
497        &mut self,
498        message: &crate::flv::PublishMessage,
499    ) -> io::Result<Vec<u8>> {
500        self.driver
501            .framed
502            .codec_mut()
503            .session_mut()
504            .send_publish_message(message)
505            .map_err(io_err)
506    }
507
508    /// Writes one already-framed message verbatim (the async half of the
509    /// `encode_*` methods above), bounded by [`Timeouts::write`].
510    pub async fn write_frame(&mut self, bytes: Vec<u8>) -> io::Result<()> {
511        self.queue(bytes).await
512    }
513
514    /// Next batch of server events (acks, errors, close); `Ok(None)` at EOF.
515    /// Same deadline rules and cancel-safety as [`RtmpConnection::next_events`].
516    pub async fn next_events(&mut self) -> io::Result<Option<Vec<ClientEvent>>> {
517        self.driver.next_events().await
518    }
519}
520
521#[cfg(test)]
522mod tests {
523    use super::*;
524    use std::time::Duration;
525    use tokio::io::{AsyncReadExt, AsyncWriteExt};
526
527    fn timeouts() -> Timeouts {
528        Timeouts::new(
529            Duration::from_secs(10),
530            Duration::from_secs(10),
531            Duration::from_secs(30),
532            Duration::from_secs(10),
533        )
534    }
535
536    const FIXTURE: &str = "rtmp/obs-publish.bin";
537
538    /// Replays the real captured `ffmpeg` publish (T8's `obs-publish.bin`)
539    /// over an actual loopback TCP socket, driving `AsyncRtmpServer`/
540    /// `RtmpConnection` end to end: a spawned client task writes the fixture
541    /// bytes and drains the server's replies, while the server side accepts
542    /// the connection and loops `next_events` until the connection closes.
543    ///
544    /// This is the online counterpart of `transmux/tests/it/rtmp_ingest_fixture.rs`'s offline
545    /// replay — it proves the tokio adapter (not just the sans-IO session)
546    /// actually drives a real publish to `Connected` -> `Publish` -> `Media`.
547    #[tokio::test]
548    async fn loopback_replay_of_real_publish_reaches_connected_publish_media() {
549        let fixture = std::fs::read(test_fixtures::path(FIXTURE))
550            .expect("read ../fixtures/rtmp/obs-publish.bin");
551
552        let server = AsyncRtmpServer::bind(
553            "127.0.0.1:0",
554            RtmpServerConfig::new(crate::server::RtmpServerConfig::default(), timeouts()),
555        )
556        .await
557        .expect("bind ephemeral loopback port");
558        let addr = server.local_addr().expect("local_addr");
559
560        // Client task: play back the captured publisher's raw bytes, and
561        // drain whatever the server writes back (so the server's writes
562        // never block on an unread socket buffer), counting the bytes
563        // received — this is what proves `next_events` actually wrote the
564        // session's reply bytes to the socket, not just decoded events.
565        let client = tokio::spawn(async move {
566            let mut stream = TcpStream::connect(addr).await.expect("connect loopback");
567            stream
568                .write_all(&fixture)
569                .await
570                .expect("write fixture bytes");
571            let mut sink = [0u8; 8192];
572            let mut replied_bytes = 0usize;
573            loop {
574                match stream.read(&mut sink).await {
575                    Ok(0) | Err(_) => break,
576                    Ok(n) => replied_bytes += n,
577                }
578            }
579            replied_bytes
580        });
581
582        let mut conn = server
583            .accept()
584            .await
585            .expect("accept the client connection")
586            .into_connection();
587        let mut events = Vec::new();
588        while let Some(batch) = conn
589            .next_events()
590            .await
591            .expect("next_events must not error")
592        {
593            events.extend(batch);
594        }
595        // Close the server-side socket so the client's drain loop observes
596        // EOF and the spawned task actually finishes.
597        drop(conn);
598        let replied_bytes = client.await.expect("client task must not panic");
599
600        // The handshake alone (S0 + S1 + S2, §5.2) is 1 + 1536 + 1536 = 3073
601        // bytes; `connect`/`createStream`/`publish` each add a reply on top.
602        // If `next_events` failed to write the reply bytes back, the client
603        // would observe a bare EOF and this would be 0.
604        const HANDSHAKE_REPLY_LEN: usize = 1 + 1536 + 1536;
605        assert!(
606            replied_bytes >= HANDSHAKE_REPLY_LEN,
607            "next_events must write the session's reply bytes back to the socket \
608             (expected at least the {HANDSHAKE_REPLY_LEN}-byte S0+S1+S2 handshake reply), \
609             got {replied_bytes} bytes"
610        );
611
612        assert!(
613            events
614                .iter()
615                .any(|e| matches!(e, ServerEvent::Connected { app } if app == "live")),
616            "must emit Connected{{app: \"live\"}} over the real socket; got {events:?}"
617        );
618        assert!(
619            events.iter().any(
620                |e| matches!(e, ServerEvent::Publish { stream_key, .. } if stream_key == "testkey")
621            ),
622            "must emit Publish{{stream_key: \"testkey\", ..}} over the real socket; got {events:?}"
623        );
624        let media_count = events
625            .iter()
626            .filter(|e| matches!(e, ServerEvent::Media { .. }))
627            .count();
628        assert!(
629            media_count >= 1,
630            "must emit at least one Media event over the real socket, got {media_count}"
631        );
632    }
633
634    /// I2: the sans-IO `encode_video`/`encode_audio`/`encode_metadata` +
635    /// `write_frame` split round-trips through the server's chunk parser, and
636    /// two video frames exercise chunk-header compression (the second message
637    /// reuses the first's chunk-stream basic header via a type-2/3 header).
638    #[tokio::test]
639    async fn encode_then_write_frames_decode_on_the_server_with_header_compression() {
640        let server = AsyncRtmpServer::bind(
641            "127.0.0.1:0",
642            RtmpServerConfig::new(crate::server::RtmpServerConfig::default(), timeouts()),
643        )
644        .await
645        .expect("bind");
646        let addr = server.local_addr().expect("addr");
647        let target = RtmpTarget::from_parts(&format!("rtmp://{addr}/live"), "live", "testkey")
648            .expect("target");
649
650        // Drive the server concurrently: `publish` needs the server to answer
651        // the handshake/connect/createStream/publish exchange as the client
652        // sends.
653        let server_task = tokio::spawn(async move {
654            let mut conn = server.accept().await.expect("accept").into_connection();
655            // Collect the raw FLV bodies in arrival order, so the test can
656            // check both the count AND the payload bytes/order (a
657            // header-compression bug that still yields 2 events would
658            // otherwise pass).
659            let mut medias: Vec<Vec<u8>> = Vec::new();
660            let is_video = |m: &Vec<u8>| m.contains(&0xAA) || m.contains(&0xBB);
661            while medias.iter().filter(|m| is_video(m)).count() < 2 {
662                match conn.next_events().await {
663                    Ok(Some(batch)) => {
664                        for e in batch {
665                            if let ServerEvent::Media { flv } = e {
666                                medias.push(flv);
667                            }
668                        }
669                    }
670                    Ok(None) | Err(_) => break,
671                }
672            }
673            medias
674        });
675
676        let config =
677            RtmpClientConfig::new(target.clone(), SessionClientConfig::default(), timeouts())
678                .with_timeouts(
679                    timeouts()
680                        .with_connect(Duration::from_secs(30))
681                        .with_handshake(Duration::from_secs(30)),
682                );
683        assert_eq!(config.target.stream_key, "testkey");
684        let mut client = AsyncRtmpClient::connect(config).await.expect("connect");
685        client.publish().await.expect("publish");
686
687        // Two video messages (FLV AVCVIDEOPACKET bodies) via the sans-IO
688        // encode half, then the write half — the shape `multimux`'s egress
689        // uses.
690        let frame_a = client
691            .encode_video(Timestamp::from_millis(0), &[0x17, 0x01, 0, 0, 0, 0xAA])
692            .expect("encode a");
693        let frame_b = client
694            .encode_video(Timestamp::from_millis(33), &[0x17, 0x01, 0, 0, 0, 0xBB])
695            .expect("encode b");
696        // A metadata message too.
697        let meta = client
698            .encode_metadata(&[("width".to_string(), crate::amf0::Amf0Value::Number(1280.0))])
699            .expect("encode meta");
700        for bytes in [meta, frame_a, frame_b] {
701            client.write_frame(bytes).await.expect("write_frame");
702        }
703
704        let medias = server_task.await.expect("server join");
705        // Filter to the two VIDEO frames we sent (the metadata message is also
706        // a media event on some paths), preserving arrival order.
707        let video: Vec<&Vec<u8>> = medias
708            .iter()
709            .filter(|m| m.contains(&0xAA) || m.contains(&0xBB))
710            .collect();
711        assert_eq!(
712            video.len(),
713            2,
714            "both encoded video frames must decode on the server (chunk-header compression exercised): {medias:?}"
715        );
716        // Order + payload bytes: 0xAA first, then 0xBB — a reordered or
717        // corrupt stream fails this.
718        assert!(
719            video[0].contains(&0xAA) && video[1].contains(&0xBB),
720            "frames must arrive in order with their own payloads: {medias:?}"
721        );
722    }
723}