1use itertools::Itertools;
2use o_sfu_model::{UserId, UserInfo};
3use o_sfu_rfc::rtp::{Mid, Rid, Ssrc};
4use o_sfu_router::rtp::{MediaFormat, MediaStream as RouterRtpParameters};
5use o_sfu_transport::{
6 ProducerActivity, SessionUploadEncoding, SourceActivityUpdate, TransportMediaId,
7 TransportSessionKey, TransportSourceKey,
8};
9use tracing::{error, warn};
10
11use super::{
12 super::{
13 outbound::{OutboundSender, RemoteTrackSnapshot},
14 state::{PresenceCommit, RoomState},
15 },
16 ReceiverRouteWork,
17 source_index::PublishedSources,
18 subscription::ReceiverRouteScope,
19};
20use crate::{
21 Bitrate, ConnectionId,
22 engine::source_model::{
23 PublishedSourceDescriptor, PublishedSourceDescriptorParts, PublishedSourceOwner,
24 SourceEncodingDescriptor, SourceEncodingDescriptorParts, SourceModelError,
25 SourcePublishIntent, UploadLayerPolicyRole, UserStreamId,
26 },
27};
28
29#[derive(Debug, Clone)]
30pub struct ValidatedPublish {
31 pub session_key: TransportSessionKey,
32 pub intent: SourcePublishIntent,
33}
34
35#[derive(Debug)]
36pub struct PublishCommit {
37 pub receiver_route_work: ReceiverRouteWork,
38 pub presence: Option<PresenceCommit>,
39}
40
41#[derive(Debug)]
42pub enum PublishIntentPlan {
43 Activate(ProducerActivityCommit),
44 Noop,
45 Queue,
46 Stage(ValidatedPublish),
47}
48
49#[derive(Debug)]
50pub struct ProducerActivityCommit {
51 pub source: TransportSourceKey,
52 pub stream_id: UserStreamId,
53 pub update: SourceActivityUpdate,
54 pub track_snapshots: Vec<(OutboundSender, RemoteTrackSnapshot)>,
55 pub presence: Option<PresenceCommit>,
56}
57
58#[derive(Debug)]
59pub enum ProducerActivityRejection {
60 MissingPublication,
61 StalePublication,
62}
63
64impl RoomState {
65 pub fn apply_publish_intent(
66 &mut self,
67 user_id: &UserId,
68 publisher_connection_id: ConnectionId,
69 intent: &SourcePublishIntent,
70 can_stage: bool,
71 ) -> PublishIntentPlan {
72 let Some(user) = self.users.get(user_id) else {
73 warn!(
74 ?user_id,
75 publisher_connection_id = ?publisher_connection_id,
76 stream_id = %intent.stream_id(),
77 "cannot start publish because the user is missing from room state"
78 );
79 return PublishIntentPlan::Noop;
80 };
81 if user.connection_id != publisher_connection_id {
82 warn!(
83 ?user_id,
84 publisher_connection_id = ?publisher_connection_id,
85 current_connection_id = ?user.connection_id,
86 stream_id = %intent.stream_id(),
87 "cannot start publish because the connection is stale"
88 );
89 return PublishIntentPlan::Noop;
90 }
91 if self
92 .topology
93 .published_source_id(user_id, publisher_connection_id, intent.stream_id())
94 .is_some()
95 {
96 return self
97 .apply_publication_activity(
98 user_id,
99 publisher_connection_id,
100 intent.stream_id(),
101 true,
102 intent.presence(),
103 )
104 .map_or_else(|_| PublishIntentPlan::Noop, PublishIntentPlan::Activate);
105 }
106 if !can_stage {
107 return PublishIntentPlan::Queue;
108 }
109 self.validate_publish(user_id, publisher_connection_id, intent)
110 .map_or(PublishIntentPlan::Noop, PublishIntentPlan::Stage)
111 }
112
113 pub fn validate_publish(
114 &self,
115 user_id: &UserId,
116 publisher_connection_id: ConnectionId,
117 intent: &SourcePublishIntent,
118 ) -> Option<ValidatedPublish> {
119 let Some(user) = self.users.get(user_id) else {
120 warn!(
121 ?user_id,
122 publisher_connection_id = ?publisher_connection_id,
123 stream_id = %intent.stream_id(),
124 "cannot prepare negotiated publish because the user is missing from room state"
125 );
126 return None;
127 };
128 if user.connection_id != publisher_connection_id {
129 warn!(
130 ?user_id,
131 publisher_connection_id = ?publisher_connection_id,
132 current_connection_id = ?user.connection_id,
133 stream_id = %intent.stream_id(),
134 "cannot prepare negotiated publish because the connection is stale"
135 );
136 return None;
137 }
138 if user.parsed_client_rtp_capabilities.is_none() {
139 warn!(
140 ?user_id,
141 publisher_connection_id = ?publisher_connection_id,
142 stream_id = %intent.stream_id(),
143 "cannot prepare negotiated publish because the user is not publish-ready"
144 );
145 return None;
146 }
147 Some(ValidatedPublish {
148 session_key: self.transport_user_key(user_id, publisher_connection_id),
149 intent: intent.clone(),
150 })
151 }
152
153 pub fn commit_publish_reservation(
154 &mut self,
155 publish: ValidatedPublish,
156 consumable_rtp_parameters: RouterRtpParameters,
157 upload_encodings: &[SessionUploadEncoding],
158 transport_media_id: TransportMediaId,
159 ) -> Option<PublishCommit> {
160 self.validate_publish_commit(&publish, transport_media_id)?;
161 let owner_user_id = publish.session_key.user_id().clone();
162 let owner_connection_id = publish.session_key.connection_id();
163 let stream_id = publish.intent.stream_id().clone();
164 let presence = publish.intent.presence().cloned();
165 let source_id = match self.topology.commit_publication(
166 publish,
167 consumable_rtp_parameters,
168 upload_encodings,
169 transport_media_id,
170 ) {
171 Ok(source_id) => source_id,
172 Err(error) => {
173 error!(
174 user_id = ?owner_user_id,
175 ?owner_connection_id,
176 stream_id = %stream_id,
177 ?transport_media_id,
178 ?error,
179 "failed to commit negotiated publication"
180 );
181 return None;
182 }
183 };
184 let receiver_route_work =
185 self.plan_missing_receiver_routes(ReceiverRouteScope::Source(source_id));
186 let presence = presence.and_then(|info| {
187 self.apply_presence_update(&owner_user_id, owner_connection_id, &info)
188 });
189 Some(PublishCommit {
190 receiver_route_work,
191 presence,
192 })
193 }
194
195 pub(in crate::engine::room) fn validate_publish_commit(
196 &self,
197 publish: &ValidatedPublish,
198 transport_media_id: TransportMediaId,
199 ) -> Option<()> {
200 let user_id = publish.session_key.user_id();
201 let connection_id = publish.session_key.connection_id();
202 let Some(user) = self.users.get(user_id) else {
203 warn!(
204 ?user_id,
205 ?connection_id,
206 stream_id = %publish.intent.stream_id(),
207 ?transport_media_id,
208 "cannot commit negotiated publish because the user is missing from room state"
209 );
210 return None;
211 };
212 let publish_ready = user.parsed_client_rtp_capabilities.is_some();
213 if user.connection_id != connection_id || !publish_ready {
214 warn!(
215 ?user_id,
216 ?connection_id,
217 current_connection_id = ?user.connection_id,
218 publish_ready,
219 stream_id = %publish.intent.stream_id(),
220 ?transport_media_id,
221 "cannot commit negotiated publish because the user state changed before commit"
222 );
223 return None;
224 }
225 if self
226 .topology
227 .sources()
228 .id_for_owner_stream(user_id, publish.intent.stream_id())
229 .is_some()
230 {
231 warn!(
232 ?user_id,
233 ?connection_id,
234 stream_id = %publish.intent.stream_id(),
235 ?transport_media_id,
236 "cannot commit negotiated publish because a source already exists for this stream"
237 );
238 return None;
239 }
240 Some(())
241 }
242
243 #[must_use]
244 pub fn producer_stream_id_for_transport_media_id(
245 &self,
246 transport_media_id: TransportMediaId,
247 ) -> Option<UserStreamId> {
248 self.topology
249 .sources()
250 .source_for_transport(transport_media_id)
251 .map(|source| source.descriptor.stream_id().clone())
252 }
253
254 pub fn apply_publication_activity(
255 &mut self,
256 user_id: &UserId,
257 connection_id: ConnectionId,
258 stream_id: &UserStreamId,
259 active: bool,
260 presence: Option<&UserInfo>,
261 ) -> Result<ProducerActivityCommit, ProducerActivityRejection> {
262 let source_id = self
263 .topology
264 .published_source_id(user_id, connection_id, stream_id)
265 .ok_or(ProducerActivityRejection::MissingPublication)?;
266 let revision = self
267 .topology
268 .set_published_source_activity(source_id, connection_id, active)
269 .ok_or(ProducerActivityRejection::StalePublication)?;
270 let source_recipients = self
271 .topology
272 .committed_consumer_user_ids_for_source(source_id);
273 let source = self
274 .topology
275 .sources()
276 .source(source_id)
277 .ok_or(ProducerActivityRejection::StalePublication)?
278 .transport
279 .clone();
280 let update = SourceActivityUpdate::new(ProducerActivity::from_active(active), revision);
281 let presence =
282 presence.and_then(|info| self.apply_presence_update(user_id, connection_id, info));
283 Ok(ProducerActivityCommit {
284 source,
285 stream_id: stream_id.clone(),
286 update,
287 track_snapshots: self.remote_track_snapshots_for_users(source_recipients, false),
288 presence,
289 })
290 }
291}
292
293pub(super) fn allocate_source_descriptor(
294 sources: &mut PublishedSources,
295 publish: &ValidatedPublish,
296 consumable_rtp_parameters: &RouterRtpParameters,
297 upload_encodings: &[SessionUploadEncoding],
298) -> Result<PublishedSourceDescriptor, SourceModelError> {
299 let source_id = sources.allocate_id();
300 let encodings = consumable_rtp_parameters
301 .bindings()
302 .map(|binding| {
303 let upload_profile = upload_profile_for_rid(upload_encodings, binding.rid());
304 SourceEncodingDescriptor::new(SourceEncodingDescriptorParts {
305 encoding_id: sources.allocate_encoding_id(),
306 source_id,
307 rid: binding.rid().map(Rid::new),
308 primary_ssrc: binding.ssrc().map(Ssrc::new),
309 repair_ssrc: None,
310 max_bitrate: binding
311 .max_bitrate()
312 .map(Bitrate::from_bps)
313 .or_else(|| upload_profile.and_then(|(_, encoding)| encoding.max_bitrate)),
314 resolution_scale: upload_profile
315 .and_then(|(_, encoding)| encoding.resolution_scale),
316 max_framerate: upload_profile.and_then(|(_, encoding)| encoding.max_framerate),
317 policy_role: upload_profile.map(|(rank, _)| {
318 upload_layer_policy_role_for_rank(rank, upload_encodings.len())
319 }),
320 negotiated_format: negotiated_format_for_binding(
321 consumable_rtp_parameters,
322 binding.payload_type(),
323 ),
324 })
325 })
326 .collect::<Vec<_>>();
327 PublishedSourceDescriptor::new(PublishedSourceDescriptorParts {
328 source_id,
329 owner: PublishedSourceOwner::new(publish.session_key.user_id().clone()),
330 stream_id: publish.intent.stream_id().clone(),
331 media_kind: publish.intent.media_kind(),
332 policy: publish.intent.policy(),
333 mid: consumable_rtp_parameters.mid().map(Mid::new),
334 encodings,
335 })
336}
337
338fn upload_profile_for_rid<'a>(
339 upload_encodings: &'a [SessionUploadEncoding],
340 rid: Option<&str>,
341) -> Option<(usize, &'a SessionUploadEncoding)> {
342 let rid = rid?;
343 upload_encodings
344 .iter()
345 .enumerate()
346 .find(|(_rank, encoding)| encoding.rid == rid)
347}
348
349const fn upload_layer_policy_role_for_rank(
350 rank: usize,
351 layer_count: usize,
352) -> UploadLayerPolicyRole {
353 if layer_count > 1 && rank + 1 == layer_count {
354 UploadLayerPolicyRole::Featured
355 } else if rank == 0 && layer_count > 2 {
356 UploadLayerPolicyRole::DegradedThumbnail
357 } else {
358 UploadLayerPolicyRole::Thumbnail
359 }
360}
361
362fn negotiated_format_for_binding(
363 parameters: &RouterRtpParameters,
364 payload_type: Option<u8>,
365) -> Option<MediaFormat> {
366 if let Some(payload_type) = payload_type
367 && let Some(format) = parameters
368 .formats()
369 .find(|format| format.payload_type() == payload_type)
370 {
371 return Some(format.clone());
372 }
373 parameters
374 .formats()
375 .find_or_first(|format| !format.codec().is_rtx())
376 .cloned()
377}