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//! # Quickstart
21//!
22//! Run a Caller/Listener handshake in memory: the bytes one side emits are
23//! parsed and fed to the other, as a transport would.
24//!
25//! ```rust
26//! use core::time::Duration;
27//!
28//! use srt_runtime::HandshakeConfig;
29//! use srt_runtime::caller::{CallerHandshake, CallerHandshakeState};
30//! use srt_runtime::handshake_sm::HandshakeOutput;
31//! use srt_runtime::listener::{ListenerHandshake, ListenerHandshakeState};
32//! use srt_runtime::packet::ControlPacket;
33//!
34//! fn first_send(outputs: Vec<HandshakeOutput>) -> Option<Vec<u8>> {
35//!     outputs.into_iter().find_map(|o| match o {
36//!         HandshakeOutput::Send(bytes) => Some(bytes),
37//!         _ => None,
38//!     })
39//! }
40//!
41//! let mut caller = CallerHandshake::new(
42//!     0x1111_1111,
43//!     HandshakeConfig::new(
44//!         Duration::from_millis(120),
45//!         1500,
46//!         8192,
47//!         Duration::from_millis(250),
48//!         12,
49//!     )
50//!         .with_latency(Duration::from_millis(180))
51//!         .with_stream_id(Some("live/camera-1".into())),
52//! );
53//! // A real listener derives the SYN cookie from the peer address and a secret.
54//! let mut listener = ListenerHandshake::new(
55//!     0x2222_2222,
56//!     0xC0FF_EE42,
57//!     HandshakeConfig::new(
58//!         Duration::from_millis(120),
59//!         1500,
60//!         8192,
61//!         Duration::from_millis(250),
62//!         12,
63//!     ).with_latency(Duration::from_millis(250)),
64//! );
65//!
66//! let mut to_listener = caller.start().unwrap();
67//! for _ in 0..10 {
68//!     let pkt = ControlPacket::parse(&to_listener).unwrap();
69//!     let Some(reply) = first_send(listener.feed(&pkt).unwrap()) else { break };
70//!     let pkt = ControlPacket::parse(&reply).unwrap();
71//!     match first_send(caller.feed(&pkt).unwrap()) {
72//!         Some(next) => to_listener = next,
73//!         None => break,
74//!     }
75//! }
76//! assert_eq!(caller.state(), CallerHandshakeState::Connected);
77//! assert_eq!(listener.state(), ListenerHandshakeState::Connected);
78//! // Both sides agree on the greater of the two latencies.
79//! assert_eq!(caller.negotiated().unwrap().latency, Duration::from_millis(250));
80//! ```
81//!
82//! # How do I...
83//!
84//! - Parse and re-serialize an SRT packet: [`SrtPacket`],
85//!   [`packet::ControlPacket`], `examples/packet_round_trip.rs`.
86//! - Run a Caller/Listener handshake without sockets: [`CallerHandshake`],
87//!   [`ListenerHandshake`], [`HandshakeConfig`],
88//!   `examples/handshake_loopback.rs`.
89//! - Recover lost packets with NAK and retransmission: [`arq::Sender`],
90//!   [`arq::Receiver`], `examples/arq_loss_recovery.rs`.
91//! - Read an `srt://` URL (stream id, latency, mode, passphrase): [`SrtUrl`],
92//!   `examples/parse_url.rs`.
93//! - Connect over UDP with tokio: [`io::SrtListener`], [`io::SrtSocket`],
94//!   [`io::SrtSocketConfig`], `examples/udp_loopback.rs`.
95//! - Encrypt the payload with a passphrase: [`handshake_sm::CryptoConfig`],
96//!   [`HandshakeConfig::with_crypto`], `examples/udp_loopback.rs`.
97//! - Size the socket receive buffer: `broadcast_net::net::UdpOptions`,
98//!   [`io::SrtSocket::recv_buffer_size`]; no example yet (the README section
99//!   "Sizing the receive buffer" gives the rule).
100//! - Connect two peers in Rendezvous mode: [`RendezvousHandshake`],
101//!   [`RendezvousRole`]; no example yet.
102//! - Drive one connection from your own socket loop: [`Link`], [`CallerLink`],
103//!   [`Delivered`]; no example yet.
104//! - Release data on its delivery time: [`tsbpd::TsbpdScheduler`]; no example
105//!   yet.
106//! - Pace a sender: [`livecc::LiveCC`], [`filecc::FileCc`]; no example yet.
107//!
108//! # Modules
109//!
110//! Wire format: [`packet`] (every data and control packet and handshake
111//! extension), [`url`] (feature `std`, the `srt://` URL).
112//!
113//! Handshakes: [`handshake_sm`] (the shared configuration, outputs and
114//! negotiated parameters), [`caller`], [`listener`], [`rendezvous`], [`cookie`]
115//! (feature `link`, the Listener's SYN cookie).
116//!
117//! Reliability and timing: [`arq`] (sender, receiver, sequence arithmetic,
118//! RTT), [`tsbpd`] (delivery scheduler), [`livecc`] and [`filecc`]
119//! (congestion control), [`damage`] (drops as damage reports).
120//!
121//! Encryption (feature `crypto`): [`crypto`] (AES-CTR, key wrap, key
122//! derivation), [`km_refresh`] (SEK rotation).
123//!
124//! Connections: [`link`] (feature `link`, one connection as a sans-IO engine),
125//! [`io`] (feature `tokio`, the UDP adapter).
126//!
127//! Errors: [`error`].
128//!
129//! # Feature flags
130//!
131//! - `std` (default): the standard library and [`SrtUrl`]; without it the
132//!   crate is `no_std` + `alloc`.
133//! - `serde`: `Serialize` on the public wire types.
134//! - `crypto`: payload encryption, the handshake key exchange and KM refresh.
135//! - `link`: the [`Link`] and [`CallerLink`] engines and the SYN cookie;
136//!   implies `crypto`.
137//! - `tokio`: the [`io`] UDP adapter; implies `std` and `link`.
138//!
139//! # Spec citations
140//!
141//! `draft-sharabayko-srt-01` §3 (packet structure), §4.3.1 (Caller/Listener),
142//! §4.3.2 (Rendezvous), §4.5 to §4.7 (TSBPD and too-late drop), §4.8 and §4.10
143//! (ARQ and RTT), §5.1 (LiveCC), §5.2 (FileCC), §6 (encryption)
144//! (`private/specs-verified/ietf/specs/ietf_draft_sharabayko_srt_01.txt`); RFC
145//! 3394 (`private/specs-verified/ietf/srt-runtime/rfc3394-aes-key-wrap.md`);
146//! RFC 8018 PBKDF2 (`private/specs-verified/ietf/srt-runtime/rfc8018-pbkdf2.md`).
147#![cfg_attr(not(feature = "std"), no_std)]
148#![forbid(unsafe_code)]
149#![deny(missing_docs)]
150#![cfg_attr(docsrs, feature(doc_cfg))]
151
152#[cfg(doctest)]
153#[doc = include_str!("../README.md")]
154struct ReadmeDoctests;
155
156extern crate alloc;
157
158/// Key lengths (bytes) AES key wrap accepts: AES-128/192/256 (FIPS 197).
159pub(crate) const AES_KEY_LENS: [usize; 3] = [16, 24, 32];
160
161pub mod arq;
162pub mod caller;
163#[cfg(feature = "link")]
164#[cfg_attr(docsrs, doc(cfg(feature = "link")))]
165pub mod cookie;
166#[cfg(feature = "crypto")]
167#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
168pub mod crypto;
169pub mod damage;
170pub mod error;
171pub mod filecc;
172pub mod handshake_sm;
173#[cfg(feature = "crypto")]
174#[cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
175pub mod km_refresh;
176#[cfg(feature = "link")]
177#[cfg_attr(docsrs, doc(cfg(feature = "link")))]
178pub mod link;
179pub mod listener;
180pub mod livecc;
181pub mod packet;
182pub mod rendezvous;
183#[cfg(all(test, feature = "link"))]
184mod test_support;
185pub mod tsbpd;
186
187#[cfg(feature = "std")]
188#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
189pub mod url;
190
191#[cfg(feature = "tokio")]
192#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
193pub mod io;
194
195pub use caller::{CallerHandshake, CallerHandshakeState};
196pub use error::{Error, Result};
197pub use handshake_sm::{HandshakeConfig, HandshakeOutput, NegotiatedParams, RejectionReason};
198#[cfg(feature = "link")]
199#[cfg_attr(docsrs, doc(cfg(feature = "link")))]
200pub use link::{
201    CallerLink, CallerParams, Delivered, DeliveredItem, Link, LinkCounts, LinkEnd, LinkSetup,
202    Payload,
203};
204pub use listener::{ListenerHandshake, ListenerHandshakeState};
205pub use packet::SrtPacket;
206pub use rendezvous::{RendezvousHandshake, RendezvousHandshakeState, RendezvousRole};
207#[cfg(feature = "std")]
208#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
209pub use url::SrtUrl;
210
211/// The Internet-Draft this crate implements packet structure from.
212pub const SPEC: &str = "draft-sharabayko-srt-01";