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