Skip to main content

Crate o_sfu_core

Crate o_sfu_core 

Source
Expand description

Rooms, media sessions and packet forwarding for the SFU server.

Core is, well… the “core” of the SFU. It is where the main job of the SFU happens, where packets are routed, where we decide who gets what and how… Where the async stuff gets nasty and where performance is critical. It is also more business agnostic than the orchestration layer (/src).

Core accepts publication and subscription intent from signaling, maintains media routes between participants and forwards packets through WebRTC transports. Authentication and signaling messages belong to the server runtime. Callers must authenticate users before admission.

RTC workers, packet loops and the MediaTransport handle live in the o-sfu-transport crate. Core depends on it and never the reverse.

Session operations are available through SfuCore and MediaSession in prelude. server integration APIs handle room management, transport configuration, metrics and packet sinks. Bitrate and process-local identifiers live at the crate root.

§Rooms and media transport

RoomManager coordinates room creation, admission and removal. SfuCore::admit_user returns a MediaSession for an admitted connection. Reconnecting replaces the previous connection, so closing an obsolete session cannot remove its replacement.

Room state records publications and subscriptions, while the pure o_sfu_router state machine places each connection on a media worker. Director selects active routes and video encodings per receiver from layout preferences, observed speakers and bandwidth estimates. Codec-specific packet inspection and rewriting belong to o-sfu-transport.

MediaTransport applies room and Director decisions to RTC workers. Workers run on separate threads with str0m connections and UDP sockets. Packet loops forward media through projected routes and packet gates without deciding room policy. Room state guards are released before awaiting transport and signaling effects.

        MediaSession               dirty rooms, snapshots <───────────────┐
     one per connection                       │                           │
              │                               │                           │
              v                               v                           │
         transition                      policy turn                      │
              │                               │                           │
              ├────────> RoomState <──────────┤                           │
              │          one RwLock           │                           │
              v                               v                           │
         RoomEffects                  gates, activity,                    │
              │                       bandwidth targets                   │
              │                               │                           │
              └───────> MediaTransport <──────┘                           │
                              │                                           │
                              │ commands                                  │ [[ main runtime ]] Tokio tasks on thread pool
- - - - - - - - - - - - - - - │ - one command mailbox per worker - - - -  │ - - -
                              │                                           │ [[ media workers ]] 1 worker per thread
         ┌────────────────────┼─────────────────────┐                     │
         │                    v                     │                     │
         │                 control                  │                     │
         │                    │ writes gates        │                     │
         │                    v                     │                     │
         │             PacketLoopState              │                     │
         │                    │ read per packet     │                     │
         │                    v                     │                     │
UDP/Relay ════════════> packet_loop ═══════════════════> UDP, relay       │
 Input   │                    │                     │      Output         │
         │                    v                     │                     │
         │              observations ───────────────┼─────────────────────┘
         │                                          │
         └──── RtcWorker, one OS thread each ───────┘

§Using core

§Construct the services

  1. Call MediaTransport::build with MediaTransportConfig and MediaTransportDeps. Configuration sets the worker count, advertised IP, ports, codecs and bitrate limits, and dependencies supply shared metrics and a packet-sink registry. Once built, every worker has bound its UDP socket. Per-connection RTC state is created during negotiation.
  2. Create RoomRuntimePolicy from the transport’s router_rtp_capabilities. Pass this policy, shared metrics, a transport clone, reservation TTL and departure grace to RoomManager::new. Every room it creates applies its effects through that transport.
  3. Wrap that room manager in an Arc and pass it to SfuCore::new. Sessions negotiate through their room’s transport. Keep the room manager and transport handles for room administration, background work and shutdown.

§Create rooms and admit connections

RoomManager::serve_room reserves a room for a requester address and issuer from validated key bytes and RoomConfig. Matching reservations reuse the current room, while a conflicting key or configuration returns RoomManagerServeError::ConflictingReservation. Use Room::uuid as the room ID for admission and lookup.

For each authenticated connection, create an outbound queue with UserOutboundSender::channel_with_limits. Pass its sender in JoinUserRequest, along with user identity, permissions and MID-reuse support, to SfuCore::admit_user. Admission returns a MediaSession or a RoomManagerJoinError. Keep the receiver in the connection’s signaling loop and handle its events as described below.

§Drive a media session

OperationCaller responsibility
establishRequest initial SDP negotiation after admission. Send returned offers to the client.
answerApply a client SDP answer to the pending negotiation and send any follow-up offer.
publishSubmit a SourcePublishIntent and handle any returned offer.
subscribePass a publisher’s user ID and a map from UserStreamId to SourceSubscriptionIntent.
deactivate_publicationSubmit SourceDeactivateIntent to cancel pending publication or suppress committed media. Committed sources keep their identity and negotiated media.
renegotiateRequest another SDP exchange when a remote-track update requires negotiation.
update_info, broadcastUpdate participant information or send an application message to other room users.
peer_snapshots, endpoint_healthRead current peers or transport health for connection status.
closeAwait connection cleanup before dropping the session, including after errors.

Build publication intent from a stream ID, media kind and SourcePolicy. Translate product concepts such as camera and screen sharing into these values before calling core. Subscription updates are partial: None preserves an existing active or layout preference. Core keeps subscription intent while publishers are absent or not yet negotiated.

Negotiation and subscription failures return SessionError. Use is_client_error to distinguish client or protocol faults from infrastructure failures. Broadcast failures return BroadcastPayloadError.

§Handle outbound events

Drain UserOutboundReceiver::recv_event alongside client input. UserOutboundEvent::Message delivers one of these outputs:

On Overflow or Closed, stop draining and close the connection. Overflow takes precedence over queued output, so continuing to drain would hide the loss of required signaling events.

§Run background work and administration

Run one task to drain source_policy_subscription and pass room IDs from wait_for_update to sync_source_packet_selection_policies_for_runtime_ids. Await each policy update to completion. Call check_expired_room_reservations periodically to remove expired reservations and rooms whose departure grace has elapsed.

Use disconnect_users for administrative removal and stats_snapshots for room statistics. available_features reports room capabilities. Recording start and stop currently return false because no persistent recording backend is enabled.

§Negotiation and cleanup

MediaSession serializes negotiation through mutable access. Core creates SDP offers and accepts client answers, with at most one negotiation pending. Publishing during initial negotiation is deferred until client capabilities are known, and later media changes can require renegotiation.

Forward NegotiationOffer upload slots and SDP to clients. Send remote-track metadata before SDP so clients can identify receiving media sections. MediaSession::answer may return another NegotiationOffer. Keep exchanging offers and answers until negotiation finishes.

use o_sfu_core::prelude::{MediaSession, NegotiationOffer, SessionError};

async fn negotiate(session: &mut MediaSession) -> Result<(), SessionError> {
    let mut pending = session.establish().await?;
    while let Some(offer) = pending {
        // The signaling adapter sends the metadata and offer, then awaits the answer.
        let answer = exchange(offer).await;
        pending = session.answer(&answer).await?;
    }
    Ok(())
}

The same exchange applies to publish and renegotiate results. None means there is no new SDP to send, including when changes wait on a pending negotiation.

Admission and session mutations have cancellation restrictions documented on SfuCore::admit_user and MediaSession. Await these operations to completion once polled so committed state receives its transport and signaling effects. Await MediaSession::close before dropping a session, even on error paths, because Drop performs no room or transport cleanup. MediaTransport::shutdown cancels RTC workers and waits for their threads to exit.

Modules§

engine 🔒
Private media engine implementation tree.
options 🔒
prelude
Caller-facing o-sfu-core API.
server
Server-runtime integration surface.
sfu 🔒
SfuCore::admit_user returns one MediaSession per admitted room connection.

Structs§

Bitrate
Media bitrate in bits per second, with decimal kilo- and megabit units.
ConnectionId
unique identifier for a user’s transport connection within the server process
MediaWorkerId
runtime-local identifier for one rtc media worker
RoomInstanceId
Process-local generation tag for one room lifecycle.