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//! | `cluster` | In-process reference [`ClusterRelay`] + `ClusterDirectory` (origin/edge federation) |
115//! | `auth-token` | Production signed-token [`StreamAuthenticator`] ([`TokenAuthenticator`]) — HMAC-SHA-256, dependency-free |
116//! | `macros` | `#[derive(MediaSink)]`, `#[protocol]` ergonomics |
117//! | `full` | everything |
118//!
119//! Ready-to-use reference implementations ship for the operational traits too:
120//! [`FileAuditSink`] ([`AuditSink`] → file),
121//! [`StandardTelemetry`] (structured-logging [`Observer`]), and the
122//! `metrics`-gated [`PrometheusObserver`](observability::PrometheusObserver).
123
124#![cfg_attr(docsrs, feature(doc_cfg))]
125// The engine contains no `unsafe` — make that a compiler-enforced guarantee so
126// a future change can't quietly introduce it.
127#![forbid(unsafe_code)]
128// Documentation completeness is enforced, not aspirational: every public item
129// carries docs, and intra-doc links must resolve.
130#![deny(missing_docs)]
131#![deny(rustdoc::broken_intra_doc_links)]
132
133pub mod audit;
134pub mod auth;
135pub mod bus;
136pub mod cluster;
137pub mod engine;
138pub mod error;
139pub mod frame;
140pub mod health;
141pub mod identity;
142pub mod inbound;
143pub mod observe;
144pub mod testing;
145pub mod traits;
146pub mod transcode;
147
148// Canonical Annex-B start-code scanner, shared by the codec NAL utilities and
149// the ingest packetizers. Internal; compiled whenever either layer is present.
150#[cfg(any(feature = "_nal", feature = "ingest"))]
151mod bytescan;
152
153// Dependency-free SHA-256 / HMAC-SHA-256 backing the signed-token authenticator.
154#[cfg(feature = "auth-token")]
155mod crypto;
156
157#[cfg(feature = "_codec")]
158#[cfg_attr(docsrs, doc(cfg(feature = "codec")))]
159pub mod codec;
160
161#[cfg(feature = "storage-fs")]
162#[cfg_attr(docsrs, doc(cfg(feature = "storage-fs")))]
163pub mod storage;
164
165#[cfg(feature = "ingest")]
166#[cfg_attr(docsrs, doc(cfg(feature = "ingest")))]
167pub mod protocol;
168
169#[cfg(feature = "hls")]
170#[cfg_attr(docsrs, doc(cfg(feature = "hls")))]
171pub mod packager;
172
173#[cfg(feature = "record")]
174#[cfg_attr(docsrs, doc(cfg(feature = "record")))]
175pub mod record;
176
177#[cfg(any(feature = "hls", feature = "record"))]
178#[cfg_attr(docsrs, doc(cfg(any(feature = "hls", feature = "record"))))]
179pub mod segment;
180
181#[cfg(feature = "metrics")]
182#[cfg_attr(docsrs, doc(cfg(feature = "metrics")))]
183pub mod observability;
184
185// ── Flat re-exports (match sc-core's surface so migration is mechanical) ────
186pub use audit::{AuditAction, AuditPipeline, AuditRecord, AuditSink, FileAuditSink};
187#[cfg(feature = "auth-token")]
188#[cfg_attr(docsrs, doc(cfg(feature = "auth-token")))]
189pub use auth::TokenAuthenticator;
190pub use auth::{AllowAll, Credentials, StreamAuthenticator};
191pub use bus::{
192 EventBus, PlaybackRegistry, PublishRegistry, Qos, StreamEvent, StreamEventKind, StreamHandle,
193 StreamMetadata, StreamState, Subscription,
194};
195pub use cluster::{ClusterRelay, NodeAddr};
196pub use engine::{AppSpec, Engine, EngineBuilder, EngineConfig};
197pub use error::{ProtocolErrorKind, StreamError};
198pub use frame::{AudioFrame, CodecId, FrameFlags, FrameType, MediaFrame, VideoFrame};
199pub use health::{HealthCheck, HealthRegistry, HealthReport, HealthStatus};
200pub use identity::{AppName, StreamId, StreamKey};
201pub use inbound::{InboundProtocol, IngestContext, PublishSession};
202pub use observe::{NoopObserver, Observer, StandardTelemetry};
203pub use traits::{HwAccelBackend, MediaSink, MediaSource, ProtocolHandler, StorageBackend};
204
205// Re-export `bytes` so downstream crates (and doctests) can name `Bytes` — the
206// payload type of every `MediaFrame` — without pinning a separate version.
207pub use async_trait;
208pub use bytes;
209pub use transcode::{RenditionSpec, Transcoder};
210
211/// The crate-wide fallible result. Mirrors `sc-core::Result`.
212pub type Result<T> = std::result::Result<T, StreamError>;
213
214/// Re-exports the derive macros expand against. Stable surface for codegen so
215/// internal files can move without touching the macro crate.
216#[cfg(feature = "macros")]
217#[doc(hidden)]
218pub mod __macro_support {
219 pub use crate::bus::PublishRegistry;
220 pub use crate::traits::{MediaSink, ProtocolHandler};
221 pub use crate::{MediaFrame, Result, StreamError, StreamKey};
222 pub use async_trait::async_trait;
223 pub use std::sync::Arc;
224 pub use tokio_util::sync::CancellationToken;
225}
226
227/// `use arcly_stream::prelude::*;` — everything a downstream user needs.
228pub mod prelude {
229 pub use crate::audit::{AuditPipeline, AuditRecord, AuditSink, FileAuditSink};
230 #[cfg(feature = "auth-token")]
231 pub use crate::auth::TokenAuthenticator;
232 pub use crate::auth::{AllowAll, Credentials, StreamAuthenticator};
233 pub use crate::bus::{
234 EventBus, PlaybackRegistry, PublishRegistry, Qos, StreamEvent, StreamEventKind,
235 StreamHandle, StreamState, Subscription,
236 };
237 pub use crate::cluster::{ClusterRelay, NodeAddr};
238 pub use crate::engine::{AppSpec, Engine, EngineBuilder, EngineConfig};
239 pub use crate::error::{ProtocolErrorKind, StreamError};
240 pub use crate::frame::{CodecId, FrameFlags, FrameType, MediaFrame};
241 pub use crate::health::{HealthCheck, HealthRegistry, HealthStatus};
242 pub use crate::identity::{AppName, StreamId, StreamKey};
243 pub use crate::inbound::{InboundProtocol, IngestContext, PublishSession};
244 pub use crate::observe::{NoopObserver, Observer, StandardTelemetry};
245 #[cfg(feature = "rtsp")]
246 pub use crate::protocol::rtsp::{RtspHandler, RtspSource};
247 #[cfg(feature = "srt")]
248 pub use crate::protocol::srt::SrtHandler;
249 #[cfg(feature = "webrtc")]
250 pub use crate::protocol::webrtc::{
251 DtlsSrtpTransport, WhepEndpoint, WhepResource, WhipEndpoint, WhipResource,
252 };
253 pub use crate::traits::{
254 HwAccelBackend, MediaSink, MediaSource, ProtocolHandler, StorageBackend,
255 };
256 pub use crate::transcode::{RenditionSpec, Transcoder};
257 pub use crate::Result;
258 pub use async_trait::async_trait;
259 pub use tokio_util::sync::CancellationToken;
260
261 #[cfg(feature = "macros")]
262 pub use arcly_stream_macros::{protocol, MediaSink as MediaSinkDerive};
263}