rtmp-runtime 0.13.1

Sans-IO RTMP 1.0 (Adobe Real-Time Messaging Protocol) publish engine for both ends: a driveable ingest server state machine and a publish client over the handshake, chunk stream, AMF0, and message layers; optional tokio socket adapter.
Documentation
# rtmp-runtime

[![crates.io](https://img.shields.io/crates/v/rtmp-runtime.svg)](https://crates.io/crates/rtmp-runtime)
[![docs.rs](https://img.shields.io/docsrs/rtmp-runtime)](https://docs.rs/rtmp-runtime)

Sans-IO RTMP 1.0 publish engine, both ends: an ingest server that receives a live push from OBS or ffmpeg, and a publish client that pushes to a remote RTMP server. An optional `tokio` adapter provides sockets.

The [crate-root guide](https://docs.rs/rtmp-runtime) has the quickstart, the `How do I...` task index with an example for each task, the module map and the feature flags.

## What it does / what it does not

**Does:** own the RTMP wire layer for both publishing and playing, and the FLV tag-body syntax an RTMP media message carries (`flv::VideoTagHeader`, `flv::AudioTagHeader` and their AVC/AAC packet headers, the signed `CompositionTime`, and the `onMetaData` script body), plus `flv::publish_open`, the ordered messages a publisher sends before its first frame. That is the handshake, chunk-stream assembly and writing, protocol control messages, AMF0 commands, and the `connect`, `createStream`, `publish` flow on the server/publish side, plus a sans-IO client in `ClientMode::Play` that runs `connect` -> `createStream` -> `SetBufferLength` + `play` and reports `ClientEvent::Playing`, `ClientEvent::Media { flv }` (FLV tags, first chunk prefixed with the FLV file header), `ClientEvent::StreamEnded` and `ClientEvent::Error`. The server hands the received audio, video and data back as **FLV bytes** (feed them to `transmux`'s FLV demuxer); the client play mode hands the same FLV bytes back through `ClientEvent::Media`.

**Does not:** run the complex (HMAC) handshake, support RTMPE/RTMPS, or implement AMF3 beyond decoding AMF3-encoded command messages. There are no sockets in the core: you feed bytes in and write the returned bytes out.

Typical users: a live-ingest origin (`multimux`'s RTMP input and push output), test publishers, capture tooling.

## Standards supported

| Standard | Edition | Scope | Status | Notes |
|---|---|---|---|---|
| Adobe RTMP specification 1.0 | 1.0 (vendored `adobe_rtmp_1.0`, transcribed in `private/specs-verified/rtmp/rtmp-runtime/rtmp.md`) | §5.2 handshake (simple), §5.3 chunk stream (fmt 0 to 3, 1/2/3-byte csid, extended timestamp), §5.4 protocol control, §6 message format, §7.1 message types, §7.2 command messages for the publish and play flows | Partial | Publish and play (client play mode); no complex handshake. `private/specs-verified/rtmp/rtmp-runtime/rtmp.md` uses its own section numbering |
| Adobe AMF0 (referenced as `[AMF0]` by the RTMP spec) | Not separately vendored | Value types and the command set used for ingest | Partial | AMF3 commands (type 17) decode like AMF0; Data-AMF3 (15) and Shared-Object (16/19) are out of scope |
| Adobe FLV (file format v10.1) | v10.1 (vendored `adobe_flv_f4v_v10_1`) | Server emits FLV tags for audio, video and script data | Full for output | Demux with `transmux` |

Verified against a real ffmpeg publish capture (`../fixtures/rtmp/obs-publish.bin`, provenance in `../fixtures/rtmp/PROVENANCE.md`), replayed whole and in small chunks, and decoded by `transmux` into an H.264 plus AAC `Media`.

## Features

| Feature | Default | Description |
|---|---|---|
| `serde` | no | `Serialize` on `ServerEvent` and `RtmpServerConfig` (write-only); `Serialize`/`Deserialize` on `Amf0Value`, `Command`, limits and FLV wire types. |
| `tokio` | no | `io::AsyncRtmpServer`, `RtmpConnection`, `io::AsyncRtmpClient`, `io::Timeouts` and `target::RtmpTarget` (`rtmp://host[:port]/app/key`, parsed with `url`). |
| `target` | no | `target::RtmpTarget` and the `rtmp[s]://` URL grammar without sockets. Implied by `tokio`. |

The sans-IO core is `no_std` + `alloc`; `tokio` or `target` brings in `std`. There is no async runtime in the core; it has `#![forbid(unsafe_code)]`.

## Quick start

Replay the real ffmpeg capture through the server session:

Every bound is yours: the crate supplies no limit, so a session is built from the numbers you
pass.

```rust
use rtmp_runtime::amf0::Amf0Limits;
use rtmp_runtime::chunk::ChunkLimits;
use rtmp_runtime::server::{RtmpServerConfig, ServerEvent, ServerLimits, ServerSession};

let limits = ServerLimits {
    chunk: ChunkLimits {
        max_chunk_size: 1 << 20,
        max_message_len: 1 << 20,
        max_csids: 64,
        max_in_progress_bytes: 1 << 22,
    },
    amf0: Amf0Limits { max_depth: 16, max_values: 1024 },
    max_command_len: 16 * 1024,
    max_failed_publish_attempts: 3,
};
let capture = std::fs::read("../fixtures/rtmp/obs-publish.bin").unwrap();
let mut session = ServerSession::new(RtmpServerConfig::new(limits, 4096, 2_500_000, 2_500_000));
let mut flv = Vec::new();
let mut published = false;
for chunk in capture.chunks(1400) {
    let (_reply, events) = session.handle_data(chunk).unwrap();
    for ev in events {
        match ev {
            ServerEvent::Connected { app } => assert_eq!(app, "live"),
            ServerEvent::Publish { stream_key, .. } => {
                assert_eq!(stream_key, "testkey");
                published = true;
            }
            ServerEvent::Media { flv: bytes } => flv.extend_from_slice(&bytes),
            _ => {}
        }
    }
}
assert!(published && flv.starts_with(b"FLV"));
```

Or connect the two roles in memory (a publisher and an ingest server, no socket):

```rust
use std::time::Duration;

use rtmp_runtime::amf0::Amf0Limits;
use rtmp_runtime::chunk::ChunkLimits;
use rtmp_runtime::client::{ClientEvent, ClientLimits, ClientSession, RtmpClientConfig};
use rtmp_runtime::server::{RtmpServerConfig, ServerEvent, ServerLimits, ServerSession};

let chunk = ChunkLimits {
    max_chunk_size: 1 << 20,
    max_message_len: 1 << 20,
    max_csids: 64,
    max_in_progress_bytes: 1 << 22,
};
let amf0 = Amf0Limits { max_depth: 16, max_values: 1024 };
let mut config = RtmpClientConfig::new(
    ClientLimits { chunk, amf0 },
    4096,
    2_500_000,
    Duration::from_secs(3),
);
config.app = "live".into();
config.stream_key = "key".into();
let mut client = ClientSession::new(config);
let server_limits = ServerLimits {
    chunk,
    amf0,
    max_command_len: 16 * 1024,
    max_failed_publish_attempts: 3,
};
let mut server = ServerSession::new(RtmpServerConfig::new(server_limits, 4096, 2_500_000, 2_500_000));

let mut to_server = client.start();
let (mut publishing, mut accepted) = (false, false);
for _ in 0..32 {
    let (to_client, sevents) = server.handle_data(&to_server).unwrap();
    accepted |= sevents.iter().any(|e| matches!(e, ServerEvent::Publish { .. }));
    let (next, cevents) = client.handle_data(&to_client).unwrap();
    publishing |= cevents.iter().any(|e| matches!(e, ClientEvent::Publishing));
    to_server = next;
    if publishing && accepted && to_server.is_empty() { break; }
}
assert!(client.is_publishing() && accepted);
```

With the `tokio` feature, `io::AsyncRtmpServer` binds a listener and drives one `ServerSession` per connection, and `io::AsyncRtmpClient` publishes to an `RtmpTarget` URL. See the `ingest_to_flv`, `publish_loopback`, `parse_target` and `capture_publish` examples.

## What is implemented

- **Handshake** (`handshake`): C0/S0, C1/S1, C2/S2, simple form (interoperates with ffmpeg and OBS).
- **Chunk stream** (`chunk`): all four `fmt` header forms, extended timestamps, incremental `ChunkAssembler` (header inheritance, `SetChunkSize`, partial input), `ChunkWriter`.
- **Messages** (`message`): protocol control (SetChunkSize, Abort, Acknowledgement, WindowAckSize, SetPeerBandwidth), User Control events, the message type catalogue.
- **AMF0** (`amf0`): `Amf0Value` and `Command` encode and decode.
- **`server::ServerSession`**: `connect`, `createStream`, `publish`, plus the OBS extras `releaseStream` and `FCPublish`; replies `_result`, StreamBegin and `onStatus`; acknowledgement accounting; optional `expected_stream_key` gate. Events: `Connected`, `Publish`, `Media`, `Eof`, `Unsupported`.
- **`client::ClientSession`**: client handshake and the auto-advancing publish flow, then `send_audio`, `send_video`, `send_metadata`.
- **Security defaults:** `RtmpServerConfig::expected_stream_key = None` admits any publisher, so a server reachable from untrusted networks must set a key (compared in constant time). `Debug` never prints the stream key. In-progress message size is capped by the `max_in_progress_bytes` you pass in `ChunkLimits`; the crate chooses no limit.

## Damage reports

A session never loses content silently: `ServerEvent::Damage` (ingest) and
`ClientEvent::Damage` (publish/play) carry the one report, in wire order with
the events around it, and the session's `damage_policy` decides whether a report
also ends it (`RtmpError::Damage`).

Reported: a message an interrupting header or an `Abort` discarded, a message
whose declared length exceeds what the session will buffer (consumed without
being held, never a connection-ending error), media on a stream id the session
never opened or before `publish`, a message type, user control event or command
this engine does not decode, an AMF0 ECMA-Array whose declared count disagrees
with its contents, an aggregate sub-message whose framing does not hold (the
good ones before it are delivered), and input that ends inside a message. The
tolerant FLV reader's `ResyncWalk::damage` reports the spans it jumped and the
tail it lost.

What stays an error: a chunk stream that cannot be framed at all, a chunk size
outside the protocol's range, an unsupported handshake, and the unparsed-input
backstop.

## Design notes

Bytes-in, (bytes-out, events) engine with partial-input buffering, so it runs on any transport. Wire structures implement symmetric `Parse`/`Serialize`; a chunk `message length` over 24 bits is rejected (`FieldOverflow`) instead of truncated. `RtmpError` is `#[non_exhaustive]`.

## Related crates

Depends on `broadcast-core`, `broadcast-common` and `broadcast-net`; `transmux` (a dev-dependency here) demuxes the FLV the server emits. `multimux` builds its RTMP input and push on this crate; `rtsp-runtime` is the sibling sans-IO client and server engine.

## MSRV and licence

MSRV 1.95.0. Licensed under MIT OR Apache-2.0.