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//! [`docs/rtmp.md`](../README.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};
31use crate::codec::{ClientCodec, ServerCodec, 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/// One accepted RTMP connection: a stream (a [`TcpStream`] by default) driving a
143/// [`ServerSession`].
144///
145/// [`next_events`](Self::next_events) is the whole surface: read a chunk,
146/// drive the session, write the reply, return the events.
147#[derive(Debug)]
148pub struct RtmpConnection<S = TcpStream> {
149 framed: Framed<S, ServerCodec>,
150 /// Events decoded but not yet handed to the caller. Set synchronously
151 /// together with the reply bytes, so a cancelled flush leaves both in place
152 /// for the next call.
153 ready: Option<Vec<ServerEvent>>,
154 /// Once set, the connection is done (clean EOF, `ServerEvent::Eof`, a prior
155 /// `RtmpError` or a timeout) and further calls to `next_events` return
156 /// `None` without touching the socket again.
157 closed: bool,
158 handshake_deadline: Option<Instant>,
159 /// Armed when a wait starts and cleared only when a batch with events is handed
160 /// out, so `read_idle` bounds a whole frame/batch, not each (possibly empty) chunk
161 /// a peer drips.
162 idle_deadline: Option<Instant>,
163 timeouts: RtmpTimeouts,
164}
165
166impl RtmpConnection<TcpStream> {
167 /// The remote address of the connected publisher.
168 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
169 self.framed.get_ref().peer_addr()
170 }
171}
172
173impl<S: AsyncRead + AsyncWrite + Unpin> RtmpConnection<S> {
174 /// Wraps an already-connected stream with a session and explicit
175 /// [`RtmpTimeouts`].
176 pub fn from_stream(stream: S, session: ServerSession, timeouts: RtmpTimeouts) -> Self {
177 Self {
178 framed: Framed::new(stream, ServerCodec::new(session)),
179 ready: None,
180 closed: false,
181 handshake_deadline: Some(Instant::now() + timeouts.handshake),
182 idle_deadline: None,
183 timeouts,
184 }
185 }
186
187 /// Reads one chunk from the socket, drives [`ServerSession::handle_data`],
188 /// writes the reply bytes back (all of them), and returns the resulting
189 /// events.
190 ///
191 /// Returns `Ok(None)` when the connection is finished: the peer closed
192 /// the socket (clean EOF), or the most recent batch of events included
193 /// [`ServerEvent::Eof`] (so the caller sees that final batch once, then
194 /// `None` on the next call). Once a call returns `None`, every
195 /// subsequent call also returns `None` without reading the socket again.
196 ///
197 /// Cancel-safe: dropping the future at any await point loses neither a reply
198 /// byte nor an event (the reply sits in the framed write buffer, the events
199 /// in `self`, until a later call delivers them).
200 ///
201 /// # Errors
202 /// An [`io::Error`] from the underlying socket read/write, or a mapped
203 /// [`RtmpError`](crate::RtmpError) (kind [`io::ErrorKind::InvalidData`])
204 /// from [`ServerSession::handle_data`]. On an `RtmpError` the session is
205 /// unrecoverable (per `handle_data`'s own doc): this connection is torn
206 /// down immediately — marked closed and not driven further, even if the
207 /// caller keeps calling `next_events`. A deadline expiry
208 /// ([`RtmpTimeouts`]) is [`io::ErrorKind::TimedOut`] and closes the
209 /// connection too.
210 pub async fn next_events(&mut self) -> io::Result<Option<Vec<ServerEvent>>> {
211 if self.closed {
212 return Ok(None);
213 }
214 loop {
215 // 1. Drain whatever a cancelled earlier call left in the write buffer.
216 match tokio::time::timeout(self.timeouts.write, self.framed.flush()).await {
217 Err(_) => {
218 self.closed = true;
219 return Err(timed_out("write"));
220 }
221 Ok(Err(e)) => {
222 self.closed = true;
223 return Err(e);
224 }
225 Ok(Ok(())) => {}
226 }
227 // 2. Hand out events whose reply is now fully written.
228 if let Some(events) = self.ready.take() {
229 if events
230 .iter()
231 .any(|e| matches!(e, ServerEvent::Connected { .. }))
232 {
233 self.handshake_deadline = None;
234 }
235 if events.iter().any(|e| matches!(e, ServerEvent::Eof)) {
236 self.closed = true;
237 }
238 if !events.is_empty() {
239 self.idle_deadline = None;
240 }
241 return Ok(Some(events));
242 }
243 // 3. Wait for the next batch under ONE deadline (handshake or
244 // read-idle, whichever is nearer).
245 let read_idle = self.timeouts.read_idle;
246 let idle = *self
247 .idle_deadline
248 .get_or_insert_with(|| Instant::now() + read_idle);
249 let (deadline, what) = match self.handshake_deadline {
250 Some(h) if h < idle => (h, "handshake"),
251 _ => (idle, "read"),
252 };
253 match tokio::time::timeout_at(deadline, self.framed.next()).await {
254 Err(_) => {
255 self.closed = true;
256 return Err(timed_out(what));
257 }
258 Ok(None) => {
259 self.closed = true;
260 return Ok(None);
261 }
262 Ok(Some(Err(e))) => {
263 self.closed = true;
264 return Err(e);
265 }
266 Ok(Some(Ok(events))) => {
267 // Synchronous from here to the next await: reply and events
268 // move together.
269 let reply = self.framed.codec_mut().take_reply();
270 self.framed.write_buffer_mut().extend_from_slice(&reply);
271 self.ready = Some(events);
272 }
273 }
274 }
275 }
276}
277
278/// A publishing RTMP client over a stream (a [`TcpStream`] by default): the
279/// adapter for [`ClientSession`](crate::client::ClientSession), mirroring
280/// [`RtmpConnection`]. Every awaited IO is bounded by [`RtmpTimeouts`].
281#[derive(Debug)]
282pub struct AsyncRtmpClient<S = TcpStream> {
283 framed: Framed<S, ClientCodec>,
284 ready: Option<Vec<ClientEvent>>,
285 closed: bool,
286 handshake_deadline: Option<Instant>,
287 /// Armed when a wait starts and cleared only when a batch with events is handed
288 /// out, so `read_idle` bounds a whole frame/batch, not each (possibly empty) chunk
289 /// a peer drips.
290 idle_deadline: Option<Instant>,
291 timeouts: RtmpTimeouts,
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(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 framed,
323 ready: None,
324 closed: false,
325 handshake_deadline: Some(Instant::now() + timeouts.handshake),
326 idle_deadline: None,
327 timeouts,
328 }
329 }
330
331 /// Runs handshake -> connect -> createStream -> publish; returns once the
332 /// server accepted the publish. Bounded by [`RtmpTimeouts::handshake`] as a
333 /// whole. A server error (`ClientEvent::Error`) is
334 /// [`io::ErrorKind::ConnectionRefused`].
335 pub async fn publish(&mut self) -> io::Result<()> {
336 loop {
337 let Some(events) = self.next_events().await? else {
338 return Err(io::Error::new(
339 io::ErrorKind::UnexpectedEof,
340 "peer closed during publish",
341 ));
342 };
343 for e in &events {
344 match e {
345 ClientEvent::Publishing => return Ok(()),
346 ClientEvent::Error { code, description } => {
347 return Err(io::Error::new(
348 io::ErrorKind::ConnectionRefused,
349 format!("{code}: {description}"),
350 ));
351 }
352 _ => {}
353 }
354 }
355 }
356 }
357
358 /// Queues one already-framed message and flushes it under `timeouts.write`. A
359 /// cancel during the flush leaves the message queued (sent by the next call),
360 /// never half-framed.
361 async fn queue(&mut self, bytes: Vec<u8>) -> io::Result<()> {
362 self.framed.write_buffer_mut().extend_from_slice(&bytes);
363 match tokio::time::timeout(self.timeouts.write, self.framed.flush()).await {
364 Err(_) => Err(timed_out("write")),
365 Ok(r) => r,
366 }
367 }
368
369 /// Sends one audio message (FLV audio tag body) at `timestamp` ms.
370 ///
371 /// The adapter reads inbound traffic (server acks, pings, errors) only inside
372 /// [`next_events`](Self::next_events); a caller that only sends must also drive
373 /// `next_events` (e.g. in a `select!`) or the server's acknowledgement window
374 /// is never serviced.
375 pub async fn send_audio(&mut self, timestamp: u32, data: &[u8]) -> io::Result<()> {
376 let bytes = self.encode_audio(timestamp, data)?;
377 self.queue(bytes).await
378 }
379
380 /// Sends one video message (FLV video tag body) at `timestamp` ms.
381 pub async fn send_video(&mut self, timestamp: u32, data: &[u8]) -> io::Result<()> {
382 let bytes = self.encode_video(timestamp, data)?;
383 self.queue(bytes).await
384 }
385
386 /// Sends `@setDataFrame`/`onMetaData` stream metadata.
387 pub async fn send_metadata(&mut self, metadata: &[(String, Amf0Value)]) -> io::Result<()> {
388 let bytes = self.encode_metadata(metadata)?;
389 self.queue(bytes).await
390 }
391
392 /// Sans-IO half of [`send_audio`](Self::send_audio): the chunk-stream-framed
393 /// message bytes for one audio tag, **without writing**. Lets a caller
394 /// driving its own egress (e.g. `multimux`'s `PushTransportEgress`) frame a
395 /// message now and write it verbatim later via
396 /// [`write_frame`](Self::write_frame).
397 pub fn encode_audio(&mut self, timestamp: u32, data: &[u8]) -> io::Result<Vec<u8>> {
398 self.framed
399 .codec_mut()
400 .session_mut()
401 .send_audio(timestamp, data)
402 .map_err(io_err)
403 }
404
405 /// Sans-IO half of [`send_video`](Self::send_video) — see
406 /// [`encode_audio`](Self::encode_audio).
407 pub fn encode_video(&mut self, timestamp: u32, data: &[u8]) -> io::Result<Vec<u8>> {
408 self.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.framed
419 .codec_mut()
420 .session_mut()
421 .send_metadata(metadata)
422 .map_err(io_err)
423 }
424
425 /// Writes one already-framed message verbatim (the async half of the
426 /// `encode_*` methods above), bounded by [`RtmpTimeouts::write`].
427 pub async fn write_frame(&mut self, bytes: Vec<u8>) -> io::Result<()> {
428 self.queue(bytes).await
429 }
430
431 /// Next batch of server events (acks, errors, close); `Ok(None)` at EOF.
432 /// Same deadline rules and cancel-safety as [`RtmpConnection::next_events`].
433 pub async fn next_events(&mut self) -> io::Result<Option<Vec<ClientEvent>>> {
434 if self.closed {
435 return Ok(None);
436 }
437 loop {
438 match tokio::time::timeout(self.timeouts.write, self.framed.flush()).await {
439 Err(_) => {
440 self.closed = true;
441 return Err(timed_out("write"));
442 }
443 Ok(Err(e)) => {
444 self.closed = true;
445 return Err(e);
446 }
447 Ok(Ok(())) => {}
448 }
449 if let Some(events) = self.ready.take() {
450 if events.iter().any(|e| matches!(e, ClientEvent::Publishing)) {
451 self.handshake_deadline = None;
452 }
453 if events.iter().any(|e| matches!(e, ClientEvent::Closed)) {
454 self.closed = true;
455 }
456 if !events.is_empty() {
457 self.idle_deadline = None;
458 }
459 return Ok(Some(events));
460 }
461 let read_idle = self.timeouts.read_idle;
462 let idle = *self
463 .idle_deadline
464 .get_or_insert_with(|| Instant::now() + read_idle);
465 let (deadline, what) = match self.handshake_deadline {
466 Some(h) if h < idle => (h, "handshake"),
467 _ => (idle, "read"),
468 };
469 match tokio::time::timeout_at(deadline, self.framed.next()).await {
470 Err(_) => {
471 self.closed = true;
472 return Err(timed_out(what));
473 }
474 Ok(None) => {
475 self.closed = true;
476 return Ok(None);
477 }
478 Ok(Some(Err(e))) => {
479 self.closed = true;
480 return Err(e);
481 }
482 Ok(Some(Ok(events))) => {
483 let reply = self.framed.codec_mut().take_reply();
484 self.framed.write_buffer_mut().extend_from_slice(&reply);
485 self.ready = Some(events);
486 }
487 }
488 }
489 }
490}
491
492#[cfg(test)]
493mod tests {
494 use super::*;
495 use tokio::io::{AsyncReadExt, AsyncWriteExt};
496
497 const FIXTURE: &str = concat!(
498 env!("CARGO_MANIFEST_DIR"),
499 "/tests/fixtures/obs-publish.bin"
500 );
501
502 /// Replays the real captured `ffmpeg` publish (T8's `obs-publish.bin`)
503 /// over an actual loopback TCP socket, driving `AsyncRtmpServer`/
504 /// `RtmpConnection` end to end: a spawned client task writes the fixture
505 /// bytes and drains the server's replies, while the server side accepts
506 /// the connection and loops `next_events` until the connection closes.
507 ///
508 /// This is the online counterpart of `tests/it/ingest_fixture.rs`'s offline
509 /// replay — it proves the tokio adapter (not just the sans-IO session)
510 /// actually drives a real publish to `Connected` -> `Publish` -> `Media`.
511 #[tokio::test]
512 async fn loopback_replay_of_real_publish_reaches_connected_publish_media() {
513 let fixture = std::fs::read(FIXTURE).expect("read tests/fixtures/obs-publish.bin");
514
515 let server = AsyncRtmpServer::bind("127.0.0.1:0", ServerConfig::default())
516 .await
517 .expect("bind ephemeral loopback port");
518 let addr = server.local_addr().expect("local_addr");
519
520 // Client task: play back the captured publisher's raw bytes, and
521 // drain whatever the server writes back (so the server's writes
522 // never block on an unread socket buffer), counting the bytes
523 // received — this is what proves `next_events` actually wrote the
524 // session's reply bytes to the socket, not just decoded events.
525 let client = tokio::spawn(async move {
526 let mut stream = TcpStream::connect(addr).await.expect("connect loopback");
527 stream
528 .write_all(&fixture)
529 .await
530 .expect("write fixture bytes");
531 let mut sink = [0u8; 8192];
532 let mut replied_bytes = 0usize;
533 loop {
534 match stream.read(&mut sink).await {
535 Ok(0) | Err(_) => break,
536 Ok(n) => replied_bytes += n,
537 }
538 }
539 replied_bytes
540 });
541
542 let mut conn = server.accept().await.expect("accept the client connection");
543 let mut events = Vec::new();
544 while let Some(batch) = conn
545 .next_events()
546 .await
547 .expect("next_events must not error")
548 {
549 events.extend(batch);
550 }
551 // Close the server-side socket so the client's drain loop observes
552 // EOF and the spawned task actually finishes.
553 drop(conn);
554 let replied_bytes = client.await.expect("client task must not panic");
555
556 // The handshake alone (S0 + S1 + S2, §5.2) is 1 + 1536 + 1536 = 3073
557 // bytes; `connect`/`createStream`/`publish` each add a reply on top.
558 // If `next_events` failed to write the reply bytes back, the client
559 // would observe a bare EOF and this would be 0.
560 const HANDSHAKE_REPLY_LEN: usize = 1 + 1536 + 1536;
561 assert!(
562 replied_bytes >= HANDSHAKE_REPLY_LEN,
563 "next_events must write the session's reply bytes back to the socket \
564 (expected at least the {HANDSHAKE_REPLY_LEN}-byte S0+S1+S2 handshake reply), \
565 got {replied_bytes} bytes"
566 );
567
568 assert!(
569 events
570 .iter()
571 .any(|e| matches!(e, ServerEvent::Connected { app } if app == "live")),
572 "must emit Connected{{app: \"live\"}} over the real socket; got {events:?}"
573 );
574 assert!(
575 events.iter().any(
576 |e| matches!(e, ServerEvent::Publish { stream_key, .. } if stream_key == "testkey")
577 ),
578 "must emit Publish{{stream_key: \"testkey\", ..}} over the real socket; got {events:?}"
579 );
580 let media_count = events
581 .iter()
582 .filter(|e| matches!(e, ServerEvent::Media { .. }))
583 .count();
584 assert!(
585 media_count >= 1,
586 "must emit at least one Media event over the real socket, got {media_count}"
587 );
588 }
589
590 /// I2: the sans-IO `encode_video`/`encode_audio`/`encode_metadata` +
591 /// `write_frame` split round-trips through the server's chunk parser, and
592 /// two video frames exercise chunk-header compression (the second message
593 /// reuses the first's chunk-stream basic header via a type-2/3 header).
594 #[tokio::test]
595 async fn encode_then_write_frames_decode_on_the_server_with_header_compression() {
596 let server = AsyncRtmpServer::bind("127.0.0.1:0", ServerConfig::default())
597 .await
598 .expect("bind");
599 let addr = server.local_addr().expect("addr");
600 let target = RtmpTarget::from_parts(&format!("rtmp://{addr}/live"), "live", "testkey")
601 .expect("target");
602
603 // Drive the server concurrently: `publish` needs the server to answer
604 // the handshake/connect/createStream/publish exchange as the client
605 // sends.
606 let server_task = tokio::spawn(async move {
607 let mut conn = server.accept().await.expect("accept");
608 // Collect the raw FLV bodies in arrival order, so the test can
609 // check both the count AND the payload bytes/order (a
610 // header-compression bug that still yields 2 events would
611 // otherwise pass).
612 let mut medias: Vec<Vec<u8>> = Vec::new();
613 let is_video = |m: &Vec<u8>| m.contains(&0xAA) || m.contains(&0xBB);
614 while medias.iter().filter(|m| is_video(m)).count() < 2 {
615 match conn.next_events().await {
616 Ok(Some(batch)) => {
617 for e in batch {
618 if let ServerEvent::Media { flv } = e {
619 medias.push(flv);
620 }
621 }
622 }
623 Ok(None) | Err(_) => break,
624 }
625 }
626 medias
627 });
628
629 let mut client = AsyncRtmpClient::connect(&target, RtmpTimeouts::default())
630 .await
631 .expect("connect");
632 client.publish().await.expect("publish");
633
634 // Two video messages (FLV AVCVIDEOPACKET bodies) via the sans-IO
635 // encode half, then the write half — the shape `multimux`'s egress
636 // uses.
637 let frame_a = client
638 .encode_video(0, &[0x17, 0x01, 0, 0, 0, 0xAA])
639 .expect("encode a");
640 let frame_b = client
641 .encode_video(33, &[0x17, 0x01, 0, 0, 0, 0xBB])
642 .expect("encode b");
643 // A metadata message too.
644 let meta = client
645 .encode_metadata(&[("width".to_string(), crate::amf0::Amf0Value::Number(1280.0))])
646 .expect("encode meta");
647 for bytes in [meta, frame_a, frame_b] {
648 client.write_frame(bytes).await.expect("write_frame");
649 }
650
651 let medias = server_task.await.expect("server join");
652 // Filter to the two VIDEO frames we sent (the metadata message is also
653 // a media event on some paths), preserving arrival order.
654 let video: Vec<&Vec<u8>> = medias
655 .iter()
656 .filter(|m| m.contains(&0xAA) || m.contains(&0xBB))
657 .collect();
658 assert_eq!(
659 video.len(),
660 2,
661 "both encoded video frames must decode on the server (chunk-header compression exercised): {medias:?}"
662 );
663 // Order + payload bytes: 0xAA first, then 0xBB — a reordered or
664 // corrupt stream fails this.
665 assert!(
666 video[0].contains(&0xAA) && video[1].contains(&0xBB),
667 "frames must arrive in order with their own payloads: {medias:?}"
668 );
669 }
670}