o_sfu_router/lib.rs
1//! Sans-IO room session placement and RTP capability negotiation.
2//!
3//! Alice, Bob and Carol join a call. Callers commit every connection to router placements
4//! with [`Router`], which resolves the media worker that runs it. Room state outside this
5//! crate records publishers and receivers.
6//!
7//! When Alice publishes camera video, the [`negotiation`] module derives RTP parameters
8//! for her publication, then matches them separately against the receiver capabilities
9//! of Bob and Carol. Every successful match returns compatible RTP parameters as
10//! [`MediaStream`](rtp::MediaStream).
11//!
12//! Both APIs are synchronous and perform no I/O. Callers supply identifiers, choose media
13//! workers and set up packet forwarding from the returned workers and RTP parameters.
14//! Transport cleanup when removing sessions is up to callers too.
15//!
16//! ```text
17//! connections and MediaStream and
18//! router placements MediaCapabilities
19//! | |
20//! v v
21//! +--------------------- o-sfu-router ---------------------+
22//! | Router negotiation |
23//! | session placement RTP compatibility |
24//! +------------|--------------------------|----------------+
25//! v v
26//! media workers MediaStream
27//! ```
28//!
29//! # Placements
30//!
31//! One [`Router`] manages room placements across multiple logical [`RouterId`]s.
32//! [`RouterPlacement`](topology::RouterPlacement) maps logical routers to
33//! [`MediaWorkerId`] values. Worker selection and load measurements belong to callers.
34//! Every admitted user has one current [`ConnectionId`] and home placement.
35//!
36//! # Use the placement API
37//!
38//! Start with [`Router::with_placements`] when worker assignments are known.
39//! [`Router::new`] accepts only one primary router ID and RTP capabilities, so the first
40//! session commit must assign that primary router to some worker. Later commits can add
41//! placements but cannot change worker assignments of existing routers.
42//!
43//! | Operation | Use |
44//! | --- | --- |
45//! | [`Router::commit_session_placement`] | Register user connections and placements. Committing another connection for the same user replaces the previous session. |
46//! | [`Router::committed_media_worker_id`] | Resolve the worker of a connection while it remains current for that user. |
47//! | [`Router::retire_committed_placement`] | Remove sessions only while their connection is current. Returns `None` for obsolete connections. |
48//! | [`Router::remove_session`] | Remove the current session by user ID. |
49//! | [`Router::placement_snapshot`], [`Router::primary_worker`] | Read assigned placements for caller-side worker selection. |
50//! | [`Router::rtp_capabilities`] | Read the capability baseline supplied at construction for RTP negotiation. |
51//!
52//! Mutations fail with [`RouterError`] for duplicate connections, missing sessions or
53//! inconsistent placement assignments. IDs come from callers. Use fresh [`ConnectionId`]
54//! values for every reconnect.
55//!
56//! For delayed disconnect handling, pass the original connection ID to
57//! [`Router::retire_committed_placement`]. [`Router::remove_session`] targets whichever
58//! connection is current. These operations do not close transport sessions or return
59//! transport cleanup plans, so callers must save what cleanup needs before removing
60//! sessions.
61//!
62//! ## A receiver reconnects
63//!
64//! Obsolete connections cannot resolve or retire the replacement session:
65//!
66//! ```
67//! use o_sfu_model::UserId;
68//! use o_sfu_router::{
69//! ConnectionId, MediaWorkerId, Router, RouterError, RouterId,
70//! rtp::MediaCapabilities,
71//! topology::{RouterPlacement, RouterPlacements},
72//! };
73//!
74//! # fn main() -> Result<(), RouterError> {
75//! let source = RouterPlacement {
76//! router: RouterId(1),
77//! media_worker: MediaWorkerId::from_raw(0),
78//! };
79//! let destination = RouterPlacement {
80//! router: RouterId(2),
81//! media_worker: MediaWorkerId::from_raw(1),
82//! };
83//! let mut router = Router::with_placements(
84//! RouterPlacements::new(source, vec![destination]),
85//! MediaCapabilities::default(),
86//! );
87//! let publisher = UserId::from(1_i64);
88//! let receiver = UserId::from(2_i64);
89//! let old_connection = ConnectionId::from_raw(20);
90//! router.commit_session_placement(&publisher, ConnectionId::from_raw(10), source)?;
91//! router.commit_session_placement(&receiver, old_connection, destination)?;
92//! assert_eq!(
93//! router.committed_media_worker_id(&receiver, old_connection),
94//! Some(destination.media_worker),
95//! );
96//!
97//! let new_connection = ConnectionId::from_raw(21);
98//! router.commit_session_placement(&receiver, new_connection, destination)?;
99//! assert_eq!(router.committed_media_worker_id(&receiver, old_connection), None);
100//! assert_eq!(router.retire_committed_placement(&receiver, old_connection), None);
101//! assert_eq!(
102//! router.retire_committed_placement(&receiver, new_connection),
103//! Some(destination.media_worker),
104//! );
105//! # Ok(())
106//! # }
107//! ```
108//!
109//! The empty capabilities above are enough for placement operations. Media forwarding
110//! also requires negotiated RTP parameters and transport setup.
111//!
112//! # Negotiate RTP parameters
113//!
114//! [`rtp::MediaCapabilities`] describes supported codecs and header extensions.
115//! [`rtp::MediaStream`] describes concrete formats, payload types and stream bindings.
116//! Convert transport negotiation results into these types before calling the matching APIs:
117//!
118//! 1. [`derive_consumable_rtp_parameters`](negotiation::derive_consumable_rtp_parameters)
119//! matches producer formats against router capabilities and maps payload types into the
120//! router's forwarding model. Keep this consumable stream with the publication.
121//! 2. [`negotiate_consumer_rtp_parameters`](negotiation::negotiate_consumer_rtp_parameters)
122//! selects compatible formats and feedback for each receiver. Pass the consumable stream
123//! from step 1 and the receiver's capabilities. The result preserves consumable payload types.
124//!
125//! Negotiation fails with [`RtpNegotiationError`](negotiation::RtpNegotiationError).
126//! Producer derivation rejects unsupported media codecs and invalid repair associations.
127//! Consumer negotiation rejects receivers with no compatible media codec. See
128//! [`negotiation`] for an example with payload-type remapping and retransmission formats.
129
130mod model;
131#[cfg(any(test, feature = "test-support"))]
132#[path = "TESTS/test_support/mod.rs"]
133pub mod test_support;
134
135/// Logical router, worker and connection identifiers.
136///
137/// These values identify placement entries. Creating an ID allocates no transport
138/// resources.
139pub mod ids {
140 pub use crate::model::ids::*;
141}
142
143/// Codec capabilities and concrete media parameters accepted by [`negotiation`].
144///
145/// [`MediaCapabilities`](rtp::MediaCapabilities) describes supported codecs and
146/// extensions. [`MediaStream`](rtp::MediaStream) describes formats and bindings
147/// for negotiated media. SDP parsing and packet rewriting belong to the caller.
148pub mod rtp {
149 pub use crate::model::{MediaKind, rtp::*};
150}
151
152/// Match producer media to router capabilities, then to receiver capabilities.
153///
154/// Call [`derive_consumable_rtp_parameters`](negotiation::derive_consumable_rtp_parameters)
155/// once for a publication, then
156/// [`negotiate_consumer_rtp_parameters`](negotiation::negotiate_consumer_rtp_parameters)
157/// for each receiver using that consumable stream. These functions return media
158/// descriptions without modifying [`Router`] or doing transport I/O.
159///
160/// # Payload-type remapping
161///
162/// Here the producer uses payload types 96 and 97, while the router uses 100 and
163/// 101. Derivation resolves the repair association even though RTX appears before
164/// VP8 in the producer formats. Consumer negotiation preserves the mapped pair.
165///
166/// ```
167/// # use o_sfu_rfc::rtp::{
168/// # CodecName, RTP_VIDEO_CLOCK_RATE_HZ as VIDEO_CLOCK_RATE_HZ, codec_name, fmtp,
169/// # };
170/// # use o_sfu_router::{
171/// # MediaKind,
172/// # negotiation::{
173/// # RtpNegotiationError, derive_consumable_rtp_parameters,
174/// # negotiate_consumer_rtp_parameters,
175/// # },
176/// # rtp::{
177/// # MediaCapabilities, MediaCodecCapability, MediaFormat, MediaStream, PayloadType,
178/// # RtcpFeedback, RtcpFeedbackKind,
179/// # },
180/// # };
181/// # fn main() -> Result<(), RtpNegotiationError> {
182/// let producer = MediaStream::new(
183/// vec![
184/// MediaFormat::new(MediaKind::Video, CodecName::Rtx, PayloadType::new(97), VIDEO_CLOCK_RATE_HZ)
185/// .with_parameter(fmtp::RTX_ASSOCIATION, "96"),
186/// MediaFormat::new(MediaKind::Video, CodecName::Vp8, PayloadType::new(96), VIDEO_CLOCK_RATE_HZ)
187/// .with_rtcp_feedback(RtcpFeedback::new(RtcpFeedbackKind::Nack, None)),
188/// ],
189/// vec![],
190/// vec![],
191/// );
192/// let router = MediaCapabilities::new(
193/// vec![
194/// MediaCodecCapability::new(MediaKind::Video, CodecName::Vp8, VIDEO_CLOCK_RATE_HZ)
195/// .with_payload_type(PayloadType::new(100))
196/// .with_rtcp_feedback(RtcpFeedback::new(RtcpFeedbackKind::Nack, None)),
197/// MediaCodecCapability::new(MediaKind::Video, CodecName::Rtx, VIDEO_CLOCK_RATE_HZ)
198/// .with_payload_type(PayloadType::new(101))
199/// .with_parameter(fmtp::RTX_ASSOCIATION, "100"),
200/// ],
201/// vec![],
202/// );
203/// let consumer = MediaCapabilities::new(
204/// vec![
205/// MediaCodecCapability::new(MediaKind::Video, CodecName::Vp8, VIDEO_CLOCK_RATE_HZ)
206/// .with_rtcp_feedback(RtcpFeedback::new(RtcpFeedbackKind::Nack, None)),
207/// MediaCodecCapability::new(MediaKind::Video, CodecName::Rtx, VIDEO_CLOCK_RATE_HZ)
208/// .with_parameter(fmtp::RTX_ASSOCIATION, "100"),
209/// ],
210/// vec![],
211/// );
212///
213/// let consumable = derive_consumable_rtp_parameters(&producer, &router)?;
214/// let negotiated = negotiate_consumer_rtp_parameters(&consumable, &consumer)?;
215///
216/// assert_eq!(
217/// consumable
218/// .formats()
219/// .map(|format| (
220/// format.codec_name(),
221/// format.payload_type(),
222/// format.rtx_associated_payload_type(),
223/// ))
224/// .collect::<Vec<_>>(),
225/// vec![(codec_name::VP8, 100, None), (codec_name::RTX, 101, Some(100))],
226/// );
227/// assert_eq!(negotiated, consumable);
228/// # Ok(())
229/// # }
230/// ```
231pub mod negotiation {
232 #[cfg(any(test, feature = "test-support"))]
233 pub use crate::model::diagnostic::*;
234 pub use crate::model::rtp_negotiation::*;
235}
236
237/// Worker assignments used by [`Router`].
238///
239/// [`RouterPlacement`](topology::RouterPlacement) maps logical routers to workers.
240pub mod topology {
241 pub use crate::model::topology::{PlacementSnapshot, RouterPlacement, RouterPlacements};
242}
243
244pub use ids::{ConnectionId, MediaWorkerId, RouterId};
245pub use model::{MediaKind, Router, RouterError};