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