Skip to main content

srt_runtime/
lib.rs

1//! SRT (Secure Reliable Transport) as specified by the Internet-Draft
2//! `draft-sharabayko-srt-01`: byte-exact codecs for every data and control
3//! packet, and sans-IO engines for the HSv5 Caller/Listener and Rendezvous
4//! handshakes, the ARQ reliability loop (loss detection, NAK, ACK/ACKACK,
5//! RTT), TSBPD delivery with too-late drop, and LiveCC and FileCC congestion
6//! control. Behind features it adds the §6 payload encryption (AES-CTR, RFC 3394
7//! key wrap, PBKDF2 key derivation, KM refresh), the one-connection
8//! [`Link`] engine, and a `tokio` UDP adapter that has been checked against
9//! a real libsrt 1.5.5 peer.
10//!
11//! The core is `no_std` + `alloc` and reads no clock: every engine takes the
12//! caller's time (`tick`, `set_elapsed`, a `broadcast_core::stage::Instant`), and
13//! every bound, timeout and cadence ([`arq::ArqBounds`], `io::IoConfig`,
14//! `link::LinkCadence`) is the caller's. Packets the delivery engine gives up
15//! on are reported as damage, coalesced per sequence run ([`damage`]); a
16//! handshake that is rejected or never completes stays an error. It builds on
17//! `broadcast-core`, `broadcast-common` and `broadcast-net`; `broadcast-client`
18//! (the SRT caller source) and `multimux` (SRT input and push) build on it.
19//!
20//! # Choosing limits
21//!
22//! No limit struct here has a `Default`. Each one offers
23//! `for_profile(broadcast_core::Profile)`, a complete preset whose every
24//! number is a documented constant, and a typed `with_*` setter per field:
25//!
26//! | Profile | Sized for |
27//! |---|---|
28//! | `Embedded` | one program, a few hundred MB of memory, 32-bit or wasm32, few elementary streams (values checked against the 256 MiB budget where exercised, #4834) |
29//! | `Device` | single-service playback on a phone, tablet, TV or desktop, about 30 s of read-ahead |
30//! | `Server` | a live origin or HLS server carrying several programs |
31//! | `Headend` | a whole multiplex with full SI/EPG, up to 2048 PIDs |
32//!
33//! The presets: [`arq::ArqBounds`], [`arq::ReceiverBounds`], [`arq::SenderBounds`],
34//! [`io::ListenerLimits`], [`handshake_sm::HandshakeConfig`]. A preset delivers
35//! a damaged unit flagged; dropping it is the caller's opt-in.
36//!
37//! # Quickstart
38//!
39//! Run a Caller/Listener handshake in memory: the bytes one side emits are
40//! parsed and fed to the other, as a transport would.
41//!
42//! ```rust
43//! use core::time::Duration;
44//!
45//! use srt_runtime::HandshakeConfig;
46//! use srt_runtime::caller::{CallerHandshake, CallerHandshakeState};
47//! use srt_runtime::handshake_sm::HandshakeOutput;
48//! use srt_runtime::listener::{ListenerHandshake, ListenerHandshakeState};
49//! use srt_runtime::packet::ControlPacket;
50//!
51//! fn first_send(outputs: Vec<HandshakeOutput>) -> Option<Vec<u8>> {
52//!     outputs.into_iter().find_map(|o| match o {
53//!         HandshakeOutput::Send(bytes) => Some(bytes),
54//!         _ => None,
55//!     })
56//! }
57//!
58//! let mut caller = CallerHandshake::new(
59//!     0x1111_1111,
60//!     HandshakeConfig::new(
61//!         Duration::from_millis(120),
62//!         1500,
63//!         8192,
64//!         Duration::from_millis(250),
65//!         12,
66//!     )
67//!         .with_latency(Duration::from_millis(180))
68//!         .with_stream_id(Some("live/camera-1".into())),
69//! );
70//! // A real listener derives the SYN cookie from the peer address and a secret.
71//! let mut listener = ListenerHandshake::new(
72//!     0x2222_2222,
73//!     0xC0FF_EE42,
74//!     HandshakeConfig::new(
75//!         Duration::from_millis(120),
76//!         1500,
77//!         8192,
78//!         Duration::from_millis(250),
79//!         12,
80//!     ).with_latency(Duration::from_millis(250)),
81//! );
82//!
83//! let mut to_listener = caller.start().unwrap();
84//! for _ in 0..10 {
85//!     let pkt = ControlPacket::parse(&to_listener).unwrap();
86//!     let Some(reply) = first_send(listener.feed(&pkt).unwrap()) else { break };
87//!     let pkt = ControlPacket::parse(&reply).unwrap();
88//!     match first_send(caller.feed(&pkt).unwrap()) {
89//!         Some(next) => to_listener = next,
90//!         None => break,
91//!     }
92//! }
93//! assert_eq!(caller.state(), CallerHandshakeState::Connected);
94//! assert_eq!(listener.state(), ListenerHandshakeState::Connected);
95//! // Both sides agree on the greater of the two latencies.
96//! assert_eq!(caller.negotiated().unwrap().latency, Duration::from_millis(250));
97//! ```
98//!
99//! # How do I...
100//!
101//! - Parse and re-serialize an SRT packet: [`SrtPacket`],
102//!   [`packet::ControlPacket`], `examples/packet_round_trip.rs`.
103//! - Run a Caller/Listener handshake without sockets: [`CallerHandshake`],
104//!   [`ListenerHandshake`], [`HandshakeConfig`],
105//!   `examples/handshake_loopback.rs`.
106//! - Recover lost packets with NAK and retransmission: [`arq::Sender`],
107//!   [`arq::Receiver`], `examples/arq_loss_recovery.rs`.
108//! - Read an `srt://` URL (stream id, latency, mode, passphrase): [`SrtUrl`],
109//!   `examples/parse_url.rs`.
110//! - Connect over UDP with tokio: [`io::SrtListener`], [`io::SrtSocket`],
111//!   [`io::SrtSocketConfig`], `examples/udp_loopback.rs`.
112//! - Encrypt the payload with a passphrase: [`handshake_sm::CryptoConfig`],
113//!   [`HandshakeConfig::with_crypto`], `examples/udp_loopback.rs`.
114//! - Size the socket receive buffer: `broadcast_net::net::UdpOptions`,
115//!   [`io::SrtSocket::recv_buffer_size`]; no example yet (the README section
116//!   "Sizing the receive buffer" gives the rule).
117//! - Connect two peers in Rendezvous mode: [`RendezvousHandshake`],
118//!   [`RendezvousRole`]; no example yet.
119//! - Drive one connection from your own socket loop: [`Link`], [`CallerLink`],
120//!   [`Delivered`]; no example yet.
121//! - Release data on its delivery time: [`tsbpd::TsbpdScheduler`]; no example
122//!   yet.
123//! - Pace a sender: [`livecc::LiveCC`], [`filecc::FileCc`]; no example yet.
124//!
125//! # Modules
126//!
127//! Wire format: [`packet`] (every data and control packet and handshake
128//! extension), [`url`] (feature `std`, the `srt://` URL).
129//!
130//! Handshakes: [`handshake_sm`] (the shared configuration, outputs and
131//! negotiated parameters), [`caller`], [`listener`], [`rendezvous`], [`cookie`]
132//! (feature `link`, the Listener's SYN cookie).
133//!
134//! Reliability and timing: [`arq`] (sender, receiver, sequence arithmetic,
135//! RTT), [`tsbpd`] (delivery scheduler), [`livecc`] and [`filecc`]
136//! (congestion control), [`damage`] (drops as damage reports).
137//!
138//! Encryption (feature `crypto`): [`crypto`] (AES-CTR, key wrap, key
139//! derivation), [`km_refresh`] (SEK rotation).
140//!
141//! Connections: [`link`] (feature `link`, one connection as a sans-IO engine),
142//! [`io`] (feature `tokio`, the UDP adapter).
143//!
144//! Errors: [`error`].
145//!
146//! # Feature flags
147//!
148//! - `std` (default): the standard library and [`SrtUrl`]; without it the
149//!   crate is `no_std` + `alloc`.
150//! - `serde`: `Serialize` on the public wire types.
151//! - `crypto`: payload encryption, the handshake key exchange and KM refresh.
152//! - `link`: the [`Link`] and [`CallerLink`] engines and the SYN cookie;
153//!   implies `crypto`.
154//! - `tokio`: the [`io`] UDP adapter; implies `std` and `link`.
155//!
156//! # Spec citations
157//!
158//! `draft-sharabayko-srt-01` §3 (packet structure), §4.3.1 (Caller/Listener),
159//! §4.3.2 (Rendezvous), §4.5 to §4.7 (TSBPD and too-late drop), §4.8 and §4.10
160//! (ARQ and RTT), §5.1 (LiveCC), §5.2 (FileCC), §6 (encryption)
161//! (`private/specs-verified/ietf/specs/ietf_draft_sharabayko_srt_01.txt`); RFC
162//! 3394 (`private/specs-verified/ietf/srt-runtime/rfc3394-aes-key-wrap.md`);
163//! RFC 8018 PBKDF2 (`private/specs-verified/ietf/srt-runtime/rfc8018-pbkdf2.md`).
164#![cfg_attr(not(feature = "std"), no_std)]
165#![forbid(unsafe_code)]
166#![deny(missing_docs)]
167#![cfg_attr(docsrs, feature(doc_cfg))]
168
169#[cfg(doctest)]
170#[doc = include_str!("../README.md")]
171struct ReadmeDoctests;
172
173extern crate alloc;
174
175/// Key lengths (bytes) AES key wrap accepts: AES-128/192/256 (FIPS 197).
176pub(crate) const AES_KEY_LENS: [usize; 3] = [16, 24, 32];
177
178pub mod arq;
179pub mod caller;
180#[cfg(feature = "link")]
181#[cfg_attr(docsrs, doc(cfg(feature = "link")))]
182pub mod cookie;
183#[cfg(feature = "crypto")]
184#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
185pub mod crypto;
186pub mod damage;
187pub mod error;
188pub mod filecc;
189pub mod handshake_sm;
190#[cfg(feature = "crypto")]
191#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
192pub mod km_refresh;
193#[cfg(feature = "link")]
194#[cfg_attr(docsrs, doc(cfg(feature = "link")))]
195pub mod link;
196pub mod listener;
197pub mod livecc;
198pub mod packet;
199pub mod presets;
200pub mod rendezvous;
201#[cfg(all(test, feature = "link"))]
202mod test_support;
203pub mod tsbpd;
204
205#[cfg(feature = "std")]
206#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
207pub mod url;
208
209#[cfg(feature = "tokio")]
210#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
211pub mod io;
212
213pub use caller::{CallerHandshake, CallerHandshakeState};
214pub use error::{Error, Result};
215pub use handshake_sm::{HandshakeConfig, HandshakeOutput, NegotiatedParams, RejectionReason};
216#[cfg(feature = "link")]
217#[cfg_attr(docsrs, doc(cfg(feature = "link")))]
218pub use link::{
219    CallerLink, CallerParams, Delivered, DeliveredItem, Link, LinkCounts, LinkEnd, LinkSetup,
220    Payload,
221};
222pub use listener::{ListenerHandshake, ListenerHandshakeState};
223pub use packet::SrtPacket;
224pub use rendezvous::{RendezvousHandshake, RendezvousHandshakeState, RendezvousRole};
225#[cfg(feature = "std")]
226#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
227pub use url::SrtUrl;
228
229/// The Internet-Draft this crate implements packet structure from.
230pub const SPEC: &str = "draft-sharabayko-srt-01";