arcly_stream/lib.rs
1//! **arcly-stream** — an open-extensible, high-performance live-media streaming
2//! kernel.
3//!
4//! The pub/sub core of a streaming server: lock-free, zero-copy frame fan-out to
5//! an arbitrary number of late-joining subscribers, with instant-start GOP
6//! replay, publish/play authorization, live QoS, a pluggable **multi-protocol
7//! ingestion layer** ([`InboundProtocol`]), and a feature-gated pure-Rust media
8//! plane — all free of any config schema, metrics singleton, or HTTP runtime.
9//! You bring the wire protocols and telemetry by implementing small traits; the
10//! kernel owns the hard, hot-path part.
11//!
12//! ```
13//! use arcly_stream::prelude::*;
14//!
15//! let engine = Engine::builder()
16//! .max_publishers(1000)
17//! .application(AppSpec::new("live").gop_cache(120)) // instant-start
18//! .build();
19//! assert_eq!(engine.list_apps().len(), 1);
20//! ```
21//!
22//! # Architecture
23//!
24//! The crate is layered as a small always-on **kernel**, a feature-gated
25//! **media plane**, and **deferred wire protocols** that exist only as traits:
26//!
27//! ```text
28//! ┌─────────────────────── Core kernel (always on) ───────────────────────┐
29//! │ Engine · StreamHandle (broadcast fan-out, GOP cache, live QoS) │
30//! │ PublishRegistry / PlaybackRegistry / EventBus · Observer · auth · │
31//! │ audit · health · MediaFrame / CodecId · StreamError │
32//! └───────────────────────────────────────────────────────────────────────┘
33//! ▲ implements ▲ feature-gated, pure Rust
34//! │ │
35//! ┌─────┴── Wire protocols & muxers ──┐ ┌───────┴── Media plane ──────────┐
36//! │ rtmp RTMP publish/play (ready) │ │ codec H.264/H.265/AV1/VP9/VVC │
37//! │ rtsp RTSP pull ingest (ready) │ │ hls Packager + segmenter │
38//! │ srt SRT/MPEG-TS ingest (ready) │ │ mpegts MPEG-TS muxer │
39//! │ webrtc WHIP/WHEP signaling+RTP │ │ fmp4 CMAF muxer │
40//! │ Transcoder/ClusterRelay (traits) │ │ record RecordingSink · ingest │
41//! └───────────────────────────────────┘ └─────────────────────────────────┘
42//! ```
43//!
44//! The ingest plane ships four operational wire protocols — [`rtmp`](crate::protocol::rtmp)
45//! (publish + play), [`rtsp`](crate::protocol::rtsp) (client-pull from IP cameras
46//! over TCP-interleaved RTP), [`srt`](crate::protocol::srt) (listener + MPEG-TS
47//! demux), and [`webrtc`](crate::protocol::webrtc) (WHIP/WHEP signaling and
48//! RTP/RTCP routing over a host-supplied [`DtlsSrtpTransport`](crate::protocol::webrtc::DtlsSrtpTransport))
49//! — alongside the [`MpegTsMuxer`](crate::packager::MpegTsMuxer) and
50//! [`Fmp4Muxer`](crate::packager::Fmp4Muxer) egress muxers. ABR/cluster backends
51//! remain trait contracts a host implements.
52//!
53//! ## Design invariants
54//!
55//! - **Zero-copy fan-out** — frames are `bytes::Bytes`; one publish clones an
56//! `Arc<MediaFrame>` pointer to every subscriber, never the payload.
57//! - **No locks on the hot path** — the frame bus is a `tokio::broadcast`
58//! channel; cached CONFIG frames and the GOP head use `ArcSwap` / atomics.
59//! - **No global state** — telemetry ([`Observer`]), authorization
60//! ([`StreamAuthenticator`]), and audit ([`AuditSink`]) are *injected* traits
61//! with no-op/permit-all defaults, never singletons. The engine is
62//! `Send + Sync` and can be instantiated many times per process.
63//! - **Contracts are traits** — protocols depend on [`PublishRegistry`] /
64//! [`PlaybackRegistry`], not on the concrete [`Engine`], so a host can swap in
65//! its own bus.
66//! - **Pluggable ingest** — a new wire protocol is one [`InboundProtocol`]
67//! ([`inbound`]) implementation, registered with
68//! [`EngineBuilder::protocol`](crate::EngineBuilder::protocol). The engine runs
69//! any worker that satisfies the trait; the bundled `RtmpHandler` is just the
70//! first reference implementation.
71//! - **`#![forbid(unsafe_code)]`** — the kernel contains no `unsafe`, enforced
72//! by the compiler. Documentation completeness (`#![deny(missing_docs)]`) and
73//! intra-doc link integrity are compiler-enforced too.
74//!
75//! ## Module layout
76//!
77//! | Module | Responsibility |
78//! |---------------|---------------------------------------------------------------|
79//! | [`frame`] | `MediaFrame`, `CodecId`, `FrameType`, `FrameFlags` |
80//! | [`identity`] | `AppName`, `StreamId`, `StreamKey` (cheap `Arc<str>` ids) |
81//! | [`error`] | `StreamError` and the crate [`Result`] alias |
82//! | [`traits`] | `MediaSource`, `MediaSink`, `ProtocolHandler`, `StorageBackend`, `HwAccelBackend` |
83//! | [`bus`] | `StreamHandle` fan-out (GOP cache, live QoS) + registry contracts |
84//! | [`inbound`] | `InboundProtocol` trait + `IngestContext` / `PublishSession` — the multi-protocol ingestion seam |
85//! | [`engine`] | `Engine`, `EngineBuilder`, `AppSpec` — composition, run loop, source pump, idle reaper |
86//! | [`auth`] | `StreamAuthenticator` publish/play authorization (permit-all default) |
87//! | [`observe`] | `Observer` telemetry hook + `NoopObserver` |
88//! | [`audit`] | `AuditSink` + `AuditPipeline` lifecycle audit trail |
89//! | [`health`] | `HealthCheck` / `HealthRegistry` readiness aggregation |
90//! | [`transcode`] | `Transcoder` / `RenditionSpec` ABR contracts |
91//! | [`cluster`] | `ClusterRelay` origin/edge federation contracts |
92//! | [`testing`] | In-memory helpers for downstream tests |
93//!
94//! ## Cargo features
95//!
96//! | Feature | Effect |
97//! |---|---|
98//! | *(none)* | Pure engine: frame model, bus, traits, auth/audit/health/cluster contracts |
99//! | `codec` | Baseline H.264 NAL/SPS + AAC ADTS parsers ([`codec`]) |
100//! | `codec-h265` / `codec-av1` / `codec-vp9` / `codec-vvc` | Next-gen codec parsers (opt-in, pure Rust) |
101//! | `codecs-all` | Every codec parser at once |
102//! | `storage-fs` | Filesystem [`StorageBackend`] adapter |
103//! | `ingest` | Shared TCP accept loop, keyframe gate, rate limiter, NAL scan |
104//! | `hls` | HLS/LL-HLS packager: `Muxer`/`Packager`, segmenter, playlists ([`packager`]) |
105//! | `mpegts` | Native MPEG-TS `Muxer` (`MpegTsMuxer`) — playable `.ts` segments |
106//! | `fmp4` | Native fragmented-MP4/CMAF `Muxer` ([`Fmp4Muxer`](packager::Fmp4Muxer)) — `ftyp`+`moov` init & `moof`+`mdat` fragments for LL-HLS |
107//! | `rtmp` | Working RTMP publish/play [`ProtocolHandler`](protocol::rtmp::RtmpHandler) |
108//! | `rtsp` | Native RTSP client-pull ingest ([`RtspHandler`](protocol::rtsp::RtspHandler)) — `OPTIONS`/`DESCRIBE`/`SETUP`/`PLAY`/`TEARDOWN`, SDP, TCP-interleaved RTP |
109//! | `srt` | Native SRT listener ingest ([`SrtHandler`](protocol::srt::SrtHandler)) — handshake + MPEG-TS demux (unencrypted) |
110//! | `webrtc` | WHIP/WHEP signaling + RTP/RTCP routing ([`WhipEndpoint`](protocol::webrtc::WhipEndpoint)) over a pluggable `DtlsSrtpTransport` crypto seam |
111//! | `record` | Segment/recording sink over a [`StorageBackend`] ([`record`]) |
112//! | `hls` / `record` | Shared keyframe-boundary [`segment`] timing |
113//! | `metrics` | Prometheus [`Observer`] implementation |
114//! | `auth-token` | Production signed-token [`StreamAuthenticator`] ([`TokenAuthenticator`]) — HMAC-SHA-256, dependency-free |
115//! | `macros` | `#[derive(MediaSink)]`, `#[protocol]` ergonomics |
116//! | `full` | everything |
117//!
118//! Ready-to-use reference implementations ship for the operational traits too:
119//! [`FileAuditSink`] ([`AuditSink`] → file),
120//! [`StandardTelemetry`] (structured-logging [`Observer`]), and the
121//! `metrics`-gated [`PrometheusObserver`](observability::PrometheusObserver).
122
123#![cfg_attr(docsrs, feature(doc_cfg))]
124// The engine contains no `unsafe` — make that a compiler-enforced guarantee so
125// a future change can't quietly introduce it.
126#![forbid(unsafe_code)]
127// Documentation completeness is enforced, not aspirational: every public item
128// carries docs, and intra-doc links must resolve.
129#![deny(missing_docs)]
130#![deny(rustdoc::broken_intra_doc_links)]
131
132pub mod audit;
133pub mod auth;
134pub mod bus;
135pub mod cluster;
136pub mod engine;
137pub mod error;
138pub mod frame;
139pub mod health;
140pub mod identity;
141pub mod inbound;
142pub mod observe;
143pub mod testing;
144pub mod traits;
145pub mod transcode;
146
147// Canonical Annex-B start-code scanner, shared by the codec NAL utilities and
148// the ingest packetizers. Internal; compiled whenever either layer is present.
149#[cfg(any(feature = "_nal", feature = "ingest"))]
150mod bytescan;
151
152// Dependency-free SHA-256 / HMAC-SHA-256 backing the signed-token authenticator.
153#[cfg(feature = "auth-token")]
154mod crypto;
155
156#[cfg(feature = "_codec")]
157#[cfg_attr(docsrs, doc(cfg(feature = "codec")))]
158pub mod codec;
159
160#[cfg(feature = "storage-fs")]
161#[cfg_attr(docsrs, doc(cfg(feature = "storage-fs")))]
162pub mod storage;
163
164#[cfg(feature = "ingest")]
165#[cfg_attr(docsrs, doc(cfg(feature = "ingest")))]
166pub mod protocol;
167
168#[cfg(feature = "hls")]
169#[cfg_attr(docsrs, doc(cfg(feature = "hls")))]
170pub mod packager;
171
172#[cfg(feature = "record")]
173#[cfg_attr(docsrs, doc(cfg(feature = "record")))]
174pub mod record;
175
176#[cfg(any(feature = "hls", feature = "record"))]
177#[cfg_attr(docsrs, doc(cfg(any(feature = "hls", feature = "record"))))]
178pub mod segment;
179
180#[cfg(feature = "metrics")]
181#[cfg_attr(docsrs, doc(cfg(feature = "metrics")))]
182pub mod observability;
183
184// ── Flat re-exports (match sc-core's surface so migration is mechanical) ────
185pub use audit::{AuditAction, AuditPipeline, AuditRecord, AuditSink, FileAuditSink};
186#[cfg(feature = "auth-token")]
187#[cfg_attr(docsrs, doc(cfg(feature = "auth-token")))]
188pub use auth::TokenAuthenticator;
189pub use auth::{AllowAll, Credentials, StreamAuthenticator};
190pub use bus::{
191 EventBus, PlaybackRegistry, PublishRegistry, Qos, StreamEvent, StreamEventKind, StreamHandle,
192 StreamMetadata, StreamState, Subscription,
193};
194pub use cluster::{ClusterRelay, NodeAddr};
195pub use engine::{AppSpec, Engine, EngineBuilder, EngineConfig};
196pub use error::{ProtocolErrorKind, StreamError};
197pub use frame::{AudioFrame, CodecId, FrameFlags, FrameType, MediaFrame, VideoFrame};
198pub use health::{HealthCheck, HealthRegistry, HealthReport, HealthStatus};
199pub use identity::{AppName, StreamId, StreamKey};
200pub use inbound::{InboundProtocol, IngestContext, PublishSession};
201pub use observe::{NoopObserver, Observer, StandardTelemetry};
202pub use traits::{HwAccelBackend, MediaSink, MediaSource, ProtocolHandler, StorageBackend};
203
204// Re-export `bytes` so downstream crates (and doctests) can name `Bytes` — the
205// payload type of every `MediaFrame` — without pinning a separate version.
206pub use async_trait;
207pub use bytes;
208pub use transcode::{RenditionSpec, Transcoder};
209
210/// The crate-wide fallible result. Mirrors `sc-core::Result`.
211pub type Result<T> = std::result::Result<T, StreamError>;
212
213/// Re-exports the derive macros expand against. Stable surface for codegen so
214/// internal files can move without touching the macro crate.
215#[cfg(feature = "macros")]
216#[doc(hidden)]
217pub mod __macro_support {
218 pub use crate::bus::PublishRegistry;
219 pub use crate::traits::{MediaSink, ProtocolHandler};
220 pub use crate::{MediaFrame, Result, StreamError, StreamKey};
221 pub use async_trait::async_trait;
222 pub use std::sync::Arc;
223 pub use tokio_util::sync::CancellationToken;
224}
225
226/// `use arcly_stream::prelude::*;` — everything a downstream user needs.
227pub mod prelude {
228 pub use crate::audit::{AuditPipeline, AuditRecord, AuditSink, FileAuditSink};
229 #[cfg(feature = "auth-token")]
230 pub use crate::auth::TokenAuthenticator;
231 pub use crate::auth::{AllowAll, Credentials, StreamAuthenticator};
232 pub use crate::bus::{
233 EventBus, PlaybackRegistry, PublishRegistry, Qos, StreamEvent, StreamEventKind,
234 StreamHandle, StreamState, Subscription,
235 };
236 pub use crate::cluster::{ClusterRelay, NodeAddr};
237 pub use crate::engine::{AppSpec, Engine, EngineBuilder, EngineConfig};
238 pub use crate::error::{ProtocolErrorKind, StreamError};
239 pub use crate::frame::{CodecId, FrameFlags, FrameType, MediaFrame};
240 pub use crate::health::{HealthCheck, HealthRegistry, HealthStatus};
241 pub use crate::identity::{AppName, StreamId, StreamKey};
242 pub use crate::inbound::{InboundProtocol, IngestContext, PublishSession};
243 pub use crate::observe::{NoopObserver, Observer, StandardTelemetry};
244 #[cfg(feature = "rtsp")]
245 pub use crate::protocol::rtsp::{RtspHandler, RtspSource};
246 #[cfg(feature = "srt")]
247 pub use crate::protocol::srt::SrtHandler;
248 #[cfg(feature = "webrtc")]
249 pub use crate::protocol::webrtc::{
250 DtlsSrtpTransport, WhepEndpoint, WhepResource, WhipEndpoint, WhipResource,
251 };
252 pub use crate::traits::{
253 HwAccelBackend, MediaSink, MediaSource, ProtocolHandler, StorageBackend,
254 };
255 pub use crate::transcode::{RenditionSpec, Transcoder};
256 pub use crate::Result;
257 pub use async_trait::async_trait;
258 pub use tokio_util::sync::CancellationToken;
259
260 #[cfg(feature = "macros")]
261 pub use arcly_stream_macros::{protocol, MediaSink as MediaSinkDerive};
262}