o_sfu_core/lib.rs
1//! Rooms, media sessions and packet forwarding for the SFU server.
2//!
3//! Core is, well... the "core" of the SFU. It is where the main job of the SFU happens,
4//! where packets are routed, where we decide who gets what and how... Where the async stuff
5//! gets nasty and where performance is critical. It is also more business agnostic than the
6//! orchestration layer (/src).
7//!
8//! Core accepts publication and subscription intent from signaling, maintains media routes
9//! between participants and forwards packets through WebRTC transports. Authentication and
10//! signaling messages belong to the server runtime. Callers must authenticate users before
11//! admission.
12//!
13//! RTC workers, packet loops and the [`MediaTransport`](server::transport::MediaTransport)
14//! handle live in the `o-sfu-transport` crate. Core depends on it and never the reverse.
15//!
16//! Session operations are available through [`SfuCore`](prelude::SfuCore) and
17//! [`MediaSession`](prelude::MediaSession) in [`prelude`]. [`server`] integration APIs handle
18//! room management, transport configuration, metrics and packet sinks. [`Bitrate`] and
19//! process-local identifiers live at the crate root.
20//!
21//! # Rooms and media transport
22//!
23//! [`RoomManager`](server::room::RoomManager) coordinates room creation, admission and removal.
24//! [`SfuCore::admit_user`](prelude::SfuCore::admit_user) returns a
25//! [`MediaSession`](prelude::MediaSession) for an admitted connection. Reconnecting replaces
26//! the previous connection, so closing an obsolete session cannot remove its replacement.
27//!
28//! Room state records publications and subscriptions, while the pure [`o_sfu_router`] state
29//! machine places each connection on a media worker. Director selects active routes and video
30//! encodings per receiver from layout preferences, observed speakers and bandwidth estimates.
31//! Codec-specific packet inspection and rewriting belong to `o-sfu-transport`.
32//!
33//! [`MediaTransport`](server::transport::MediaTransport) applies room and Director decisions to
34//! RTC workers. Workers run on separate threads with `str0m` connections and UDP sockets.
35//! Packet loops forward media through projected routes and packet gates without deciding room
36//! policy. Room state guards are released before awaiting transport and signaling effects.
37//!
38//! ```text
39//! MediaSession dirty rooms, snapshots <───────────────┐
40//! one per connection │ │
41//! │ │ │
42//! v v │
43//! transition policy turn │
44//! │ │ │
45//! ├────────> RoomState <──────────┤ │
46//! │ one RwLock │ │
47//! v v │
48//! RoomEffects gates, activity, │
49//! │ bandwidth targets │
50//! │ │ │
51//! └───────> MediaTransport <──────┘ │
52//! │ │
53//! │ commands │ [[ main runtime ]] Tokio tasks on thread pool
54//! - - - - - - - - - - - - - - - │ - one command mailbox per worker - - - - │ - - -
55//! │ │ [[ media workers ]] 1 worker per thread
56//! ┌────────────────────┼─────────────────────┐ │
57//! │ v │ │
58//! │ control │ │
59//! │ │ writes gates │ │
60//! │ v │ │
61//! │ PacketLoopState │ │
62//! │ │ read per packet │ │
63//! │ v │ │
64//! UDP/Relay ════════════> packet_loop ═══════════════════> UDP, relay │
65//! Input │ │ │ Output │
66//! │ v │ │
67//! │ observations ───────────────┼─────────────────────┘
68//! │ │
69//! └──── RtcWorker, one OS thread each ───────┘
70//! ```
71//!
72//! # Using core
73//!
74//! ## Construct the services
75//!
76//! 1. Call [`MediaTransport::build`](server::transport::MediaTransport::build) with
77//! [`MediaTransportConfig`](server::transport::MediaTransportConfig) and
78//! [`MediaTransportDeps`](server::transport::MediaTransportDeps). Configuration sets the
79//! worker count, advertised IP, ports, codecs and bitrate limits, and dependencies supply
80//! shared metrics and a packet-sink registry. Once built, every worker has bound its UDP
81//! socket. Per-connection RTC state is created during negotiation.
82//! 2. Create [`RoomRuntimePolicy`](server::room::RoomRuntimePolicy) from the transport's
83//! [`router_rtp_capabilities`](server::transport::MediaTransport::router_rtp_capabilities).
84//! Pass this policy, shared metrics, a transport clone, reservation TTL and departure grace
85//! to [`RoomManager::new`](server::room::RoomManager::new). Every room it creates applies
86//! its effects through that transport.
87//! 3. Wrap that room manager in an `Arc` and pass it to
88//! [`SfuCore::new`](prelude::SfuCore::new). Sessions negotiate through their room's
89//! transport. Keep the room manager and transport handles for room administration,
90//! background work and shutdown.
91//!
92//! ## Create rooms and admit connections
93//!
94//! [`RoomManager::serve_room`](server::room::RoomManager::serve_room) reserves a room for a
95//! requester address and issuer from validated key bytes and
96//! [`RoomConfig`](server::room::RoomConfig). Matching reservations reuse the current room,
97//! while a conflicting key or configuration returns
98//! [`RoomManagerServeError::ConflictingReservation`](server::room::RoomManagerServeError::ConflictingReservation).
99//! Use [`Room::uuid`](server::room::Room::uuid) as the room ID for admission and lookup.
100//!
101//! For each authenticated connection, create an outbound queue with
102//! [`UserOutboundSender::channel_with_limits`](server::room::UserOutboundSender::channel_with_limits).
103//! Pass its sender in [`JoinUserRequest`](server::room::JoinUserRequest), along with user
104//! identity, permissions and MID-reuse support, to
105//! [`SfuCore::admit_user`](prelude::SfuCore::admit_user). Admission returns a
106//! [`MediaSession`](prelude::MediaSession) or a
107//! [`RoomManagerJoinError`](server::room::RoomManagerJoinError). Keep the receiver in the
108//! connection's signaling loop and handle its events as described below.
109//!
110//! ## Drive a media session
111//!
112//! | Operation | Caller responsibility |
113//! | --- | --- |
114//! | [`establish`](prelude::MediaSession::establish) | Request initial SDP negotiation after admission. Send returned offers to the client. |
115//! | [`answer`](prelude::MediaSession::answer) | Apply a client SDP answer to the pending negotiation and send any follow-up offer. |
116//! | [`publish`](prelude::MediaSession::publish) | Submit a [`SourcePublishIntent`](prelude::SourcePublishIntent) and handle any returned offer. |
117//! | [`subscribe`](prelude::MediaSession::subscribe) | Pass a publisher's user ID and a map from [`UserStreamId`](prelude::UserStreamId) to [`SourceSubscriptionIntent`](prelude::SourceSubscriptionIntent). |
118//! | [`deactivate_publication`](prelude::MediaSession::deactivate_publication) | Submit [`SourceDeactivateIntent`](prelude::SourceDeactivateIntent) to cancel pending publication or suppress committed media. Committed sources keep their identity and negotiated media. |
119//! | [`renegotiate`](prelude::MediaSession::renegotiate) | Request another SDP exchange when a remote-track update requires negotiation. |
120//! | [`update_info`](prelude::MediaSession::update_info), [`broadcast`](prelude::MediaSession::broadcast) | Update participant information or send an application message to other room users. |
121//! | [`peer_snapshots`](prelude::MediaSession::peer_snapshots), [`endpoint_health`](prelude::MediaSession::endpoint_health) | Read current peers or transport health for connection status. |
122//! | [`close`](prelude::MediaSession::close) | Await connection cleanup before dropping the session, including after errors. |
123//!
124//! Build publication intent from a stream ID, media kind and
125//! [`SourcePolicy`](prelude::SourcePolicy). Translate product concepts such as camera and
126//! screen sharing into these values before calling core. Subscription updates are partial:
127//! `None` preserves an existing active or layout preference. Core keeps subscription intent
128//! while publishers are absent or not yet negotiated.
129//!
130//! Negotiation and subscription failures return [`SessionError`](prelude::SessionError).
131//! Use [`is_client_error`](prelude::SessionError::is_client_error) to distinguish client or
132//! protocol faults from infrastructure failures. Broadcast failures return
133//! [`BroadcastPayloadError`](server::room::BroadcastPayloadError).
134//!
135//! ## Handle outbound events
136//!
137//! Drain [`UserOutboundReceiver::recv_event`](server::room::UserOutboundReceiver::recv_event)
138//! alongside client input. [`UserOutboundEvent::Message`](server::room::UserOutboundEvent::Message)
139//! delivers one of these outputs:
140//!
141//! - [`UserOutbound::Message`](server::room::UserOutbound::Message): translate room events
142//! into signaling messages for the client.
143//! - [`UserOutbound::RemoteTracks`](server::room::UserOutbound::RemoteTracks): save the snapshot's
144//! `requires_negotiation` flag, pass the snapshot to
145//! [`fresh_remote_tracks`](prelude::MediaSession::fresh_remote_tracks) and send any returned
146//! track metadata. Call [`renegotiate`](prelude::MediaSession::renegotiate) when the flag is set.
147//! - [`UserOutbound::Close`](server::room::UserOutbound::Close): stop the connection and await
148//! session cleanup.
149//!
150//! On [`Overflow`](server::room::UserOutboundEvent::Overflow) or
151//! [`Closed`](server::room::UserOutboundEvent::Closed), stop draining and close the
152//! connection. Overflow takes precedence over queued output, so continuing to drain would
153//! hide the loss of required signaling events.
154//!
155//! ## Run background work and administration
156//!
157//! Run one task to drain
158//! [`source_policy_subscription`](server::transport::MediaTransport::source_policy_subscription)
159//! and pass room IDs from [`wait_for_update`](server::transport::SourcePolicyUpdateSubscription::wait_for_update)
160//! to [`sync_source_packet_selection_policies_for_runtime_ids`](server::room::RoomManager::sync_source_packet_selection_policies_for_runtime_ids).
161//! Await each policy update to completion. Call
162//! [`check_expired_room_reservations`](server::room::RoomManager::check_expired_room_reservations)
163//! periodically to remove expired reservations and rooms whose departure grace has elapsed.
164//!
165//! Use [`disconnect_users`](server::room::RoomManager::disconnect_users) for administrative
166//! removal and [`stats_snapshots`](server::room::RoomManager::stats_snapshots) for room statistics.
167//! [`available_features`](prelude::MediaSession::available_features) reports room capabilities.
168//! Recording start and stop currently return `false` because no persistent recording backend
169//! is enabled.
170//!
171//! # Negotiation and cleanup
172//!
173//! [`MediaSession`](prelude::MediaSession) serializes negotiation through mutable access. Core
174//! creates SDP offers and accepts client answers, with at most one negotiation pending.
175//! Publishing during initial negotiation is deferred until client capabilities are known, and
176//! later media changes can require renegotiation.
177//!
178//! Forward [`NegotiationOffer`](prelude::NegotiationOffer) upload slots and SDP to clients.
179//! Send remote-track metadata before SDP so clients can identify receiving media sections.
180//! [`MediaSession::answer`](prelude::MediaSession::answer) may return another
181//! [`NegotiationOffer`](prelude::NegotiationOffer). Keep exchanging offers and answers
182//! until negotiation finishes.
183//!
184//! ```no_run
185//! use o_sfu_core::prelude::{MediaSession, NegotiationOffer, SessionError};
186//!
187//! # async fn exchange(_: NegotiationOffer) -> String { unimplemented!() }
188//! async fn negotiate(session: &mut MediaSession) -> Result<(), SessionError> {
189//! let mut pending = session.establish().await?;
190//! while let Some(offer) = pending {
191//! // The signaling adapter sends the metadata and offer, then awaits the answer.
192//! let answer = exchange(offer).await;
193//! pending = session.answer(&answer).await?;
194//! }
195//! Ok(())
196//! }
197//! ```
198//!
199//! The same exchange applies to [`publish`](prelude::MediaSession::publish) and
200//! [`renegotiate`](prelude::MediaSession::renegotiate) results. `None` means there is no new
201//! SDP to send, including when changes wait on a pending negotiation.
202//!
203//! Admission and session mutations have cancellation restrictions documented on
204//! [`SfuCore::admit_user`](prelude::SfuCore::admit_user) and
205//! [`MediaSession`](prelude::MediaSession). Await these operations to completion once polled so
206//! committed state receives its transport and signaling effects. Await
207//! [`MediaSession::close`](prelude::MediaSession::close) before dropping a session, even on
208//! error paths, because `Drop` performs no room or transport cleanup.
209//! [`MediaTransport::shutdown`](server::transport::MediaTransport::shutdown) cancels RTC
210//! workers and waits for their threads to exit.
211
212pub use o_sfu_model::Bitrate;
213pub use o_sfu_router::{ConnectionId, MediaWorkerId};
214pub use o_sfu_transport::RoomInstanceId;
215
216mod engine;
217mod options;
218pub mod prelude;
219pub mod server;
220mod sfu;
221
222pub(crate) use options::{
223 RoomMediaLimits, RoomWorkerPolicy, RuntimeFeatureFlags, VideoAdaptationTuning,
224};