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