1use std::{
4 collections::{BTreeMap, BTreeSet},
5 sync::Arc,
6};
7
8use o_sfu_model::UserId;
9use o_sfu_router::{
10 MediaKind, Router, RouterError,
11 rtp::{MediaCapabilities, MediaStream as RouterRtpParameters},
12};
13use o_sfu_transport::{
14 SessionUploadEncoding, SourceActivityRevision, TransportConsumerRoute, TransportMediaId,
15 TransportSessionKey, TransportSourceKey, TransportTeardown,
16};
17use tracing::error;
18
19use super::{
20 CommittedConsumerSetup, ConsumerRouteView, ConsumerSetupTarget, DeclaredConsumerSetup,
21 PendingConsumerRouteView, PendingConsumerSetup, PublishedSource, ReceiverRouteActivity,
22 SubscriptionKey, ValidatedPublish,
23 producer::allocate_source_descriptor,
24 route_graph::{Attached, RouteGraph},
25 source_index::PublishedSources,
26};
27use crate::{
28 ConnectionId, MediaWorkerId, RoomInstanceId,
29 engine::{
30 director::{PendingUpgrade, RouteAllocation},
31 room::{
32 RoomMediaCounts, RoomRuntimeContext, RouterPlacement,
33 effects::transport::RoomTransportPlan, outbound::OutboundSender,
34 },
35 source_model::{
36 ActiveSpeakerSourceRole, PublishedSourceId, SourceModelError, SourceSubscriptionIntent,
37 UserStreamId,
38 },
39 },
40};
41
42#[cfg(test)]
43#[path = "TESTS/topology_support.rs"]
44mod topology_support;
45
46#[derive(Debug)]
57pub struct RoomTopology {
58 instance: RoomInstanceId,
59 sources: PublishedSources,
60 route_graph: RouteGraph,
61 router: Router,
62 video_allocation_revision: u64,
64}
65
66#[derive(Debug)]
74pub struct SessionPlacementCommit {
75 pub transport_session_key: TransportSessionKey,
76 pub replacement_transport_plan: RoomTransportPlan,
78}
79
80#[derive(Debug)]
81pub(in crate::engine::room) struct ConsumerActivityCommit {
82 pub(super) update: Option<ReceiverRouteActivity>,
83 pub(super) evictions: usize,
84}
85
86#[derive(Debug)]
87pub enum SessionPlacementRejection {
88 MissingPreviousSession { previous_connection: ConnectionId },
89 Router(RouterError),
90}
91
92impl RoomTopology {
93 pub fn new(
94 runtime_context: &RoomRuntimeContext,
95 router_rtp_capabilities: MediaCapabilities,
96 pending_target_limit: usize,
97 ) -> Self {
98 Self {
99 instance: runtime_context.instance(),
100 sources: PublishedSources::default(),
101 route_graph: RouteGraph::new(pending_target_limit),
102 router: Router::new(runtime_context.primary_router(), router_rtp_capabilities),
103 video_allocation_revision: 0,
104 }
105 }
106
107 pub(in crate::engine) const fn video_allocation_revision(&self) -> u64 {
108 self.video_allocation_revision
109 }
110
111 fn invalidate_video_allocation(&mut self) {
112 self.video_allocation_revision = self.video_allocation_revision.wrapping_add(1);
113 }
114
115 pub(in crate::engine::room) fn router(&self) -> &Router {
116 &self.router
117 }
118
119 pub(in crate::engine) fn sources(&self) -> &PublishedSources {
120 &self.sources
121 }
122
123 pub(in crate::engine) fn route_graph(&self) -> &RouteGraph {
124 &self.route_graph
125 }
126
127 #[must_use]
129 pub fn committed_transport_user_key(
130 &self,
131 user_id: impl Into<Arc<UserId>>,
132 connection_id: ConnectionId,
133 ) -> Option<TransportSessionKey> {
134 let user_id = user_id.into();
135 let worker = self
136 .router
137 .committed_media_worker_id(user_id.as_ref(), connection_id)?;
138 Some(self.transport_session_key(user_id, connection_id, worker))
139 }
140
141 #[must_use]
150 #[expect(
151 clippy::unreachable,
152 reason = "current room operations require committed connection placement and must not synthesize a transport worker"
153 )]
154 pub fn transport_user_key(
155 &self,
156 user_id: impl Into<Arc<UserId>>,
157 connection_id: ConnectionId,
158 ) -> TransportSessionKey {
159 let user_id = user_id.into();
160 let Some(worker) = self
161 .router
162 .committed_media_worker_id(user_id.as_ref(), connection_id)
163 else {
164 unreachable!("transport session key lookup requires committed connection placement");
165 };
166 self.transport_session_key(user_id, connection_id, worker)
167 }
168
169 fn transport_session_key(
170 &self,
171 user_id: Arc<UserId>,
172 connection_id: ConnectionId,
173 media_worker_id: MediaWorkerId,
174 ) -> TransportSessionKey {
175 TransportSessionKey::new(self.instance, media_worker_id, connection_id, user_id)
176 }
177
178 pub fn retire_committed_placement(
180 &mut self,
181 user_id: &UserId,
182 connection_id: ConnectionId,
183 ) -> Option<TransportSessionKey> {
184 let media_worker = self
185 .router
186 .retire_committed_placement(user_id, connection_id)?;
187 Some(self.transport_session_key(user_id.clone().into(), connection_id, media_worker))
188 }
189
190 #[must_use]
192 pub fn media_counts(&self) -> RoomMediaCounts {
193 RoomMediaCounts {
194 publications: self.sources.publication_count(),
195 subscriptions: self.route_graph.subscription_count(),
196 }
197 }
198
199 #[must_use]
201 pub(in crate::engine::room) fn published_source_id(
202 &self,
203 owner: &UserId,
204 connection: ConnectionId,
205 stream_id: &UserStreamId,
206 ) -> Option<PublishedSourceId> {
207 let id = self.sources.id_for_owner_stream(owner, stream_id)?;
208 let source = self.sources.source(id)?;
209 (source.transport.session_key().connection_id() == connection).then_some(id)
210 }
211
212 pub(in crate::engine::room) fn active_stream_user_counts(&self) -> BTreeMap<UserStreamId, u64> {
214 let mut users_by_stream: BTreeMap<UserStreamId, BTreeSet<UserId>> = BTreeMap::new();
215 for source in self.sources.iter().filter(|source| source.active) {
216 users_by_stream
217 .entry(source.descriptor.stream_id().clone())
218 .or_default()
219 .insert(source.descriptor.owner().user_id().clone());
220 }
221 users_by_stream
222 .into_iter()
223 .map(|(stream_id, users)| (stream_id, u64::try_from(users.len()).unwrap_or(u64::MAX)))
224 .collect()
225 }
226
227 #[must_use]
229 pub(in crate::engine) fn active_speaker_detector_owner(
230 &self,
231 transport_media_id: TransportMediaId,
232 ) -> Option<UserId> {
233 let source = self.sources.source_for_transport(transport_media_id)?;
234 let detector_policy = source.descriptor.policy().active_speaker()?;
235 if detector_policy.role() != ActiveSpeakerSourceRole::Detector {
236 return None;
237 }
238 let owner = source.descriptor.owner().user_id();
239 self.sources
240 .owner_has_promotable_source_in_group(owner, detector_policy.group())
241 .then(|| owner.clone())
242 }
243
244 pub(in crate::engine::room) fn committed_consumer_routes(
245 &self,
246 ) -> impl Iterator<Item = ConsumerRouteView<'_>> {
247 self.route_graph
248 .attached()
249 .filter_map(|attached| self.consumer_route(attached))
250 }
251
252 pub(in crate::engine) fn committed_consumer_routes_for_user(
253 &self,
254 user_id: &UserId,
255 ) -> impl Iterator<Item = ConsumerRouteView<'_>> {
256 self.route_graph
257 .attached_for_receiver(user_id)
258 .filter_map(|attached| self.consumer_route(attached))
259 }
260
261 pub(super) fn detach_declined_consumers(
262 &mut self,
263 session: &TransportSessionKey,
264 declined: &[TransportMediaId],
265 ) -> (Vec<TransportTeardown>, bool) {
266 let routes = self
267 .route_graph
268 .detach_declined_consumers(session, declined);
269 let detached = !routes.is_empty();
270 if detached {
271 self.invalidate_video_allocation();
272 }
273 let teardown = Self::media_teardowns([], routes).collect();
274 (teardown, detached)
275 }
276
277 pub(in crate::engine::room) fn pending_consumer_routes_for_user(
278 &self,
279 user_id: &UserId,
280 ) -> impl Iterator<Item = PendingConsumerRouteView<'_>> {
281 self.route_graph
282 .attached_for_receiver(user_id)
283 .filter(|(_, _, current)| current.is_pending())
284 .filter_map(|(_, intent, current)| {
285 let source = self.sources.source(current.source_id)?;
286 Some(PendingConsumerRouteView {
287 source,
288 intent,
289 allocation: current.allocation,
290 })
291 })
292 }
293
294 pub(in crate::engine::room) fn committed_consumer_user_ids_for_source(
295 &self,
296 source_id: PublishedSourceId,
297 ) -> BTreeSet<UserId> {
298 self.route_graph
299 .attached_for_source(source_id)
300 .filter(|(_, _, current)| current.committed().is_some())
301 .map(|(key, _, _)| key.receiver.clone())
302 .collect()
303 }
304
305 pub(in crate::engine::room) fn committed_consumer_user_ids_for_owner_sources(
306 &self,
307 user_id: &UserId,
308 ) -> BTreeSet<UserId> {
309 let route_graph = &self.route_graph;
310 self.sources
311 .ids_for_owner(user_id)
312 .flat_map(|source_id| route_graph.attached_for_source(source_id))
313 .filter(|(_, _, current)| current.committed().is_some())
314 .map(|(key, _, _)| key.receiver.clone())
315 .collect()
316 }
317
318 #[must_use]
319 pub(in crate::engine) fn committed_consumer_route_for_key(
320 &self,
321 key: &SubscriptionKey,
322 ) -> Option<ConsumerRouteView<'_>> {
323 self.consumer_route(self.route_graph.current(key)?)
324 }
325
326 pub(super) fn missing_consumer_targets_for_source<'a>(
328 &mut self,
329 source_id: PublishedSourceId,
330 receivers: impl IntoIterator<Item = (&'a UserId, ConnectionId)>,
331 ) -> Vec<ConsumerSetupTarget> {
332 receivers
333 .into_iter()
334 .filter_map(|(user, connection)| self.consumer_target(user, connection, source_id))
335 .collect()
336 }
337
338 fn consumer_target(
339 &mut self,
340 user_id: &UserId,
341 connection_id: ConnectionId,
342 source_id: PublishedSourceId,
343 ) -> Option<ConsumerSetupTarget> {
344 let consumer_session = self.committed_transport_user_key(user_id.clone(), connection_id)?;
345 let (sources, route_graph) = (&self.sources, &mut self.route_graph);
346 Self::attach_consumer_target(route_graph, &consumer_session, sources.source(source_id)?)
347 }
348
349 fn attach_consumer_target(
351 route_graph: &mut RouteGraph,
352 consumer_session: &TransportSessionKey,
353 source: &PublishedSource,
354 ) -> Option<ConsumerSetupTarget> {
355 if source.descriptor.owner().user_id() == consumer_session.user_id() {
356 return None;
357 }
358 let target = ConsumerSetupTarget::new(consumer_session.clone(), source);
359 route_graph
360 .attach_for_setup(target.subscription_key(), target.source_id)
361 .then_some(target)
362 }
363
364 pub(super) fn missing_consumer_targets(
368 &mut self,
369 user_id: &UserId,
370 connection_id: ConnectionId,
371 include_source: impl Fn(&PublishedSource) -> bool,
372 ) -> Vec<ConsumerSetupTarget> {
373 let Some(consumer_session) =
374 self.committed_transport_user_key(user_id.clone(), connection_id)
375 else {
376 return Vec::new();
377 };
378 let (sources, route_graph) = (&self.sources, &mut self.route_graph);
379 sources
380 .iter()
381 .filter(|source| include_source(source))
382 .filter_map(|source| {
383 Self::attach_consumer_target(route_graph, &consumer_session, source)
384 })
385 .collect()
386 }
387
388 pub(in crate::engine) fn update_consumer_allocation(
392 &mut self,
393 key: &SubscriptionKey,
394 source_id: PublishedSourceId,
395 route: &TransportConsumerRoute,
396 update: impl FnOnce(&mut RouteAllocation),
397 ) -> bool {
398 let updated = self
399 .route_graph
400 .update_allocation(key, source_id, route, update);
401 if updated {
402 self.invalidate_video_allocation();
403 }
404 updated
405 }
406
407 pub(in crate::engine) fn update_consumer_upgrade(
409 &mut self,
410 key: &SubscriptionKey,
411 source_id: PublishedSourceId,
412 route: &TransportConsumerRoute,
413 pending_upgrade: Option<PendingUpgrade>,
414 ) -> bool {
415 if !self
416 .sources
417 .source(source_id)
418 .is_some_and(|source| source.active)
419 {
420 return false;
421 }
422 self.route_graph
423 .update_upgrade(key, source_id, route, pending_upgrade)
424 }
425
426 fn detach_user_sources(
427 &mut self,
428 user_id: &UserId,
429 ) -> (Vec<TransportSourceKey>, Vec<TransportConsumerRoute>) {
430 let mut sources = Vec::new();
431 let mut removed = Vec::new();
432 let source_ids = self.sources.ids_for_owner(user_id).collect::<Vec<_>>();
433 for source_id in source_ids {
434 if let Some((source, routes)) = self.remove_source(source_id) {
435 sources.push(source.transport);
436 removed.extend(routes);
437 }
438 }
439 (sources, removed)
440 }
441
442 fn remove_source(
443 &mut self,
444 source_id: PublishedSourceId,
445 ) -> Option<(PublishedSource, Vec<TransportConsumerRoute>)> {
446 let source = self.sources.remove(source_id)?;
447 let routes = self.route_graph.detach_source(source_id);
448 self.invalidate_video_allocation();
449 Some((source, routes))
450 }
451
452 fn consumer_route<'a>(
453 &'a self,
454 (key, intent, current): Attached<'a>,
455 ) -> Option<ConsumerRouteView<'a>> {
456 let committed = current.committed()?;
457 let source = self.sources.source(current.source_id)?;
458 Some(ConsumerRouteView {
459 key,
460 route: &committed.route,
461 pending_upgrade: committed.pending_upgrade,
462 source,
463 intent,
464 allocation: current.allocation,
465 })
466 }
467
468 pub(in crate::engine::room) fn commit_publication(
472 &mut self,
473 publish: ValidatedPublish,
474 rtp: RouterRtpParameters,
475 encodings: &[SessionUploadEncoding],
476 media: TransportMediaId,
477 ) -> Result<PublishedSourceId, SourceModelError> {
478 let descriptor = allocate_source_descriptor(&mut self.sources, &publish, &rtp, encodings)?;
479 let source_id = descriptor.source_id();
480 self.sources.insert(PublishedSource {
481 descriptor,
482 transport: TransportSourceKey::new(publish.session_key, media),
483 rtp,
484 active: true,
485 activity_revision: SourceActivityRevision::default(),
486 });
487 Ok(source_id)
488 }
489
490 fn media_teardowns(
491 sources: impl IntoIterator<Item = TransportSourceKey>,
492 routes: impl IntoIterator<Item = TransportConsumerRoute>,
493 ) -> impl Iterator<Item = TransportTeardown> {
494 sources
495 .into_iter()
496 .map(|source| {
497 TransportTeardown::remove_media(
498 source.session_key().clone(),
499 source.transport_media_id(),
500 )
501 })
502 .chain(routes.into_iter().map(|route| {
503 TransportTeardown::remove_media(
504 route.consumer_session_key().clone(),
505 route.consumer_transport_media_id(),
506 )
507 }))
508 }
509
510 pub fn set_published_source_activity(
515 &mut self,
516 source_id: PublishedSourceId,
517 connection_id: ConnectionId,
518 active: bool,
519 ) -> Option<SourceActivityRevision> {
520 let source = self.sources.source_mut(source_id)?;
521 if source.transport.session_key().connection_id() != connection_id
522 || source.active == active
523 {
524 return None;
525 }
526 source.active = active;
527 source.activity_revision = source.activity_revision.next();
528 let revision = source.activity_revision;
529 if !active {
530 self.route_graph.clear_source_upgrades(source_id);
531 }
532 self.invalidate_video_allocation();
533 Some(revision)
534 }
535
536 pub fn commit_session_placement(
547 &mut self,
548 user_id: &UserId,
549 connection_id: ConnectionId,
550 previous_connection: Option<ConnectionId>,
551 home_placement: RouterPlacement,
552 ) -> Result<SessionPlacementCommit, SessionPlacementRejection> {
553 let previous_session_key = if let Some(previous_connection) = previous_connection {
555 let Some(key) = self.committed_transport_user_key(user_id.clone(), previous_connection)
556 else {
557 return Err(SessionPlacementRejection::MissingPreviousSession {
558 previous_connection,
559 });
560 };
561 Some(key)
562 } else {
563 None
564 };
565 let media_worker = self
566 .router
567 .commit_session_placement(user_id, connection_id, home_placement)
568 .map_err(SessionPlacementRejection::Router)?;
569 self.route_graph.publisher_joined(user_id);
570 let transport_session_key =
571 self.transport_session_key(user_id.clone().into(), connection_id, media_worker);
572 let replacement_transport_plan = previous_session_key.as_ref().map_or_else(
573 RoomTransportPlan::default,
574 |replaced_session_key| {
575 let close_session = TransportTeardown::close_session(replaced_session_key.clone());
576 let (_, removed_sources) = self.detach_user_sources(user_id);
579 self.route_graph.reset_receiver_for_replacement(user_id);
580 let teardown = Self::media_teardowns([], removed_sources).chain([close_session]);
581 RoomTransportPlan::from_teardown(teardown)
582 },
583 );
584 if previous_session_key.is_some() {
585 self.invalidate_video_allocation();
586 }
587 Ok(SessionPlacementCommit {
588 transport_session_key,
589 replacement_transport_plan,
590 })
591 }
592
593 pub fn remove_session(&mut self, user_id: &UserId) -> (RoomTransportPlan, usize) {
595 let (sources, mut removed) = self.detach_user_sources(user_id);
596 removed.extend(self.route_graph.remove_receiver(user_id));
597 let evictions = self.route_graph.publisher_left(user_id);
598 self.invalidate_video_allocation();
599 let teardown = Self::media_teardowns(sources, removed);
600 if let Some(error) = self.router.remove_session(user_id).err() {
601 error!(?user_id, ?error, "failed to remove user from room router");
602 }
603 (RoomTransportPlan::from_teardown(teardown), evictions)
604 }
605
606 pub(super) fn commit_consumer_setup(
610 &mut self,
611 setup: DeclaredConsumerSetup,
612 allocation: RouteAllocation,
613 ) -> Result<CommittedConsumerSetup, TransportConsumerRoute> {
614 let DeclaredConsumerSetup {
615 pending:
616 PendingConsumerSetup {
617 target,
618 reservation,
619 sender,
620 rtp: _,
621 },
622 route,
623 } = setup;
624 let active = allocation.delivers(self.route_graph.intent(&target.subscription_key()));
625 let declared_active = reservation.declared_activity().is_active();
626 if !self
627 .route_graph
628 .commit(reservation, route.clone(), allocation)
629 {
630 return Err(route);
631 }
632 self.invalidate_video_allocation();
633 Ok(CommittedConsumerSetup {
634 target,
635 route,
636 sender,
637 transport_activity_update: (active != declared_active).then_some(active),
638 })
639 }
640
641 pub(super) fn reserve_consumer_setup(
643 &mut self,
644 target: ConsumerSetupTarget,
645 allocation: RouteAllocation,
646 sender: OutboundSender,
647 rtp: RouterRtpParameters,
648 ) -> Option<PendingConsumerSetup> {
649 let reservation = self.route_graph.reserve_consumer_setup(
650 target.subscription_key(),
651 target.source_id,
652 allocation,
653 )?;
654 Some(PendingConsumerSetup {
655 target,
656 reservation,
657 sender,
658 rtp,
659 })
660 }
661
662 pub(super) fn release_consumer_setup(&mut self, setup: &PendingConsumerSetup) {
663 self.route_graph.release_consumer_setup(&setup.reservation);
664 }
665
666 pub(in crate::engine::room) fn apply_subscription_intent(
672 &mut self,
673 key: &SubscriptionKey,
674 connection_id: ConnectionId,
675 intent: SourceSubscriptionIntent,
676 receiver_deafened: bool,
677 publisher_present: bool,
678 ) -> ConsumerActivityCommit {
679 let mut commit = ConsumerActivityCommit {
680 update: None,
681 evictions: 0,
682 };
683 if intent.is_empty() {
684 return commit;
685 }
686 commit.evictions = self
687 .route_graph
688 .merge_intent(key, intent, publisher_present);
689 self.invalidate_video_allocation();
690 let Some(active) = intent.active() else {
691 return commit;
692 };
693 let Some(source) = self
694 .sources
695 .id_for_owner_stream(&key.publisher, &key.stream)
696 .and_then(|source_id| self.sources.source(source_id))
697 else {
698 return commit;
699 };
700 let Some(allocation) = self.route_graph.attached_allocation_mut(
701 key,
702 source.descriptor.source_id(),
703 connection_id,
704 ) else {
705 return commit;
706 };
707 if active && receiver_deafened && source.descriptor.media_kind() == MediaKind::Audio {
709 allocation.pause_for_deaf_receiver();
710 }
711 commit.update = self
712 .committed_consumer_route_for_key(key)
713 .filter(|route| route.route.consumer_session_key().connection_id() == connection_id)
714 .map(|route| ReceiverRouteActivity::new(route.target(), route.delivery_active()));
715 commit
716 }
717}