Skip to main content

Crate rtmp_runtime

Crate rtmp_runtime 

Source
Expand description

§rtmp-runtime

crates.io docs.rs

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.

§What it does / what it does not

Does: own the RTMP wire layer for both publishing and playing. 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

StandardEditionScopeStatusNotes
Adobe RTMP specification 1.01.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 flowsPartialPublish 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 vendoredValue types and the command set used for ingestPartialAMF3 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 dataFull for outputDemux 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

FeatureDefaultDescription
serdenoSerialize/Deserialize on ServerEvent, ServerConfig, Amf0Value, Command.
tokionoio::AsyncRtmpServer, RtmpConnection, io::AsyncRtmpClient, io::Timeouts and target::RtmpTarget (rtmp://host[:port]/app/key, parsed with url).

The core is std and needs no runtime; it has #![forbid(unsafe_code)].

§Quick start

Replay the real ffmpeg capture through the server session:

use rtmp_runtime::server::{ServerEvent, ServerSession};

let capture = std::fs::read("../fixtures/rtmp/obs-publish.bin").unwrap();
let mut session = ServerSession::with_defaults();
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):

use rtmp_runtime::client::{ClientEvent, ClientSession, RtmpClientConfig};
use rtmp_runtime::server::{RtmpServerConfig, ServerEvent, ServerSession};

let mut config = RtmpClientConfig::default();
config.app = "live".into();
config.stream_key = "key".into();
let mut client = ClientSession::new(config);
let mut server = ServerSession::new(RtmpServerConfig::default());

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 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: ServerConfig::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 max_in_progress_bytes.

§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].

Depends on broadcast-common; 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.

Re-exports§

pub use error::RtmpError;
pub use message::ChunkSize;

Modules§

amf0
AMF0 (Action Message Format 0) value encoding/decoding, used by RTMP command and data messages.
chunk
RTMP chunk stream — basic header, message header, extended timestamp (Adobe RTMP 1.0 §5.3).
client
RTMP client session engine — connect → createStream → publish (Adobe RTMP 1.0 §7.2, NetConnection/NetStream commands).
error
Error type for the RTMP ingest session engine.
flv
FLV (Flash Video) tag framing — Adobe Flash Video File Format Specification v10.1, Annex E: the file header of §E.2 and the tag of §E.4.1.
handshake
RTMP handshake — C0/C1/C2 and S0/S1/S2 (Adobe RTMP 1.0 §5.2).
ids
The RTMP wire identities — §5.1.2 chunk stream id, §5.1.3 message stream id and timestamp, §5.3.1.1’s basic-header encodability rule (reference private/specs-verified/rtmp/rtmp-runtime/rtmp.md).
iotokio
Async tokio socket adapter driving the sans-IO ingest server session over a real tokio::net::TcpStream — the Layer-2 adapter (see private/specs-verified/rtmp/rtmp-runtime/rtmp.md § Layer-2 adapter; mirrors the rtsp_runtime::io tokio adapter shape in this same workspace).
message
RTMP message assembly from chunks, protocol control messages, and the message type catalogue (Adobe RTMP 1.0 §5.4, §6, §7.1).
server
RTMP ingest server session state machine — connect → createStream → publish (Adobe RTMP 1.0 §7.2, NetConnection/NetStream commands).
targettarget
rtmp[s]://host[:port]/app/stream-key -> typed target, built with the url crate. Replaces format!("rtmp://{host}:{port}/{app}"), which produces rtmp://::1:1935/live for an IPv6 address (defect 8) and leaks userinfo/query into tcUrl.

Constants§

RTMP_VERSION
The Adobe RTMP specification version this engine implements.