Skip to main content

o_sfu_core/engine/room/state/
shared.rs

1use std::{
2    collections::{BTreeMap, BTreeSet},
3    sync::Arc,
4};
5
6use o_sfu_model::{PeerSnapshot, RecordingState, UserId, UserInfo};
7use o_sfu_router::rtp::{MediaCapabilities, MediaCapabilities as RouterRtpCapabilities};
8use o_sfu_transport::TransportSessionKey;
9
10use super::super::{
11    RoomAdmissionPolicy,
12    media_graph::{ConsumerRouteView, RoomTopology},
13    outbound::{OutboundSender, RemoteTrack, RemoteTrackSnapshot},
14    transition::StagedPublishes,
15};
16use crate::{
17    ConnectionId, RoomMediaLimits, VideoAdaptationTuning,
18    engine::{director::ReceiverAllocation, source_model::UserStreamId},
19};
20
21#[derive(Debug)]
22pub struct RoomState {
23    pub(super) admission_policy: RoomAdmissionPolicy,
24    pub media_limits: RoomMediaLimits,
25    pub video_adaptation_tuning: VideoAdaptationTuning,
26    pub users: BTreeMap<UserId, ActiveUser>,
27    /// rejects stale async callbacks from previous connections
28    pub(super) next_connection_id: u64,
29    next_track_snapshot_revision: u64,
30    pub(super) recording_state: RecordingState,
31    pub(in crate::engine::room) staged_publishes: StagedPublishes,
32    pub(in crate::engine) topology: RoomTopology,
33}
34
35#[derive(Debug)]
36pub struct ActiveUser {
37    pub(super) user_id: Arc<UserId>,
38    pub(super) info: UserInfo,
39    pub(super) server_featured: Option<bool>,
40    pub parsed_client_rtp_capabilities: Option<RouterRtpCapabilities>,
41    pub connection_id: ConnectionId,
42    /// Director's last committed receiver decision for this connection.
43    pub(in crate::engine) allocation: ReceiverAllocation,
44    pub sender: OutboundSender,
45}
46
47impl ActiveUser {
48    pub(super) fn reset_presentation(&mut self) {
49        self.info = UserInfo::default();
50        self.server_featured = None;
51    }
52
53    pub(super) fn apply_info_update(&mut self, info: &UserInfo) {
54        self.info.apply_partial_update(info);
55    }
56
57    pub(in crate::engine) const fn featured(&self) -> Option<bool> {
58        self.server_featured
59    }
60
61    pub(in crate::engine) const fn is_deaf(&self) -> bool {
62        matches!(self.info.is_deaf, Some(true))
63    }
64
65    pub(in crate::engine) const fn is_screensharing(&self) -> bool {
66        matches!(self.info.is_screen_sharing_on, Some(true))
67    }
68
69    pub(in crate::engine) fn set_featured(&mut self, featured: Option<bool>) {
70        self.server_featured = featured;
71    }
72
73    pub(super) fn project_info(&self) -> UserInfo {
74        self.info
75            .clone()
76            .with_featured(self.server_featured)
77            .snapshot_complete()
78    }
79}
80
81impl RoomState {
82    pub fn new(
83        runtime_context: &super::super::RoomRuntimeContext,
84        admission_policy: RoomAdmissionPolicy,
85        media_limits: RoomMediaLimits,
86        video_adaptation_tuning: VideoAdaptationTuning,
87        router_rtp_capabilities: MediaCapabilities,
88    ) -> Self {
89        Self {
90            admission_policy,
91            media_limits,
92            video_adaptation_tuning,
93            users: BTreeMap::new(),
94            next_connection_id: 0,
95            next_track_snapshot_revision: 1,
96            recording_state: RecordingState {
97                recording: Some(false),
98                audio: Some(false),
99                transcription: Some(false),
100                video: Some(false),
101            },
102            staged_publishes: StagedPublishes::default(),
103            topology: RoomTopology::new(
104                runtime_context,
105                router_rtp_capabilities,
106                admission_policy.max_sessions,
107            ),
108        }
109    }
110
111    pub fn user_for_connection(
112        &self,
113        user_id: &UserId,
114        connection_id: ConnectionId,
115    ) -> Option<&ActiveUser> {
116        let user = self.users.get(user_id)?;
117        if user.connection_id != connection_id {
118            return None;
119        }
120        Some(user)
121    }
122
123    pub fn user_mut_for_connection(
124        &mut self,
125        user_id: &UserId,
126        connection_id: ConnectionId,
127    ) -> Option<&mut ActiveUser> {
128        let user = self.users.get_mut(user_id)?;
129        if user.connection_id != connection_id {
130            return None;
131        }
132        Some(user)
133    }
134
135    pub fn recording_state(&self) -> RecordingState {
136        self.recording_state.clone()
137    }
138
139    pub fn transport_user_entries(&self) -> impl Iterator<Item = (&UserId, ConnectionId)> {
140        self.users
141            .iter()
142            .map(|(user_id, user)| (user_id, user.connection_id))
143    }
144
145    /// Returns the transport key for an exact committed router placement.
146    ///
147    /// Use [`Self::committed_transport_user_key`] when placement may be stale.
148    ///
149    /// # Panics
150    ///
151    /// Panics when `user_id` and `connection_id` have no committed router
152    /// placement.
153    pub fn transport_user_key(
154        &self,
155        user_id: &UserId,
156        connection_id: ConnectionId,
157    ) -> TransportSessionKey {
158        if let Some(user) = self.user_for_connection(user_id, connection_id) {
159            return self
160                .topology
161                .transport_user_key(Arc::clone(&user.user_id), connection_id);
162        }
163        self.topology
164            .transport_user_key(user_id.clone(), connection_id)
165    }
166
167    /// Returns `None` unless the exact router placement remains committed.
168    pub fn committed_transport_user_key(
169        &self,
170        user_id: &UserId,
171        connection_id: ConnectionId,
172    ) -> Option<TransportSessionKey> {
173        if let Some(user) = self.user_for_connection(user_id, connection_id) {
174            return self
175                .topology
176                .committed_transport_user_key(Arc::clone(&user.user_id), connection_id);
177        }
178        self.topology
179            .committed_transport_user_key(user_id.clone(), connection_id)
180    }
181
182    pub(in crate::engine) fn committed_consumer_routes(
183        &self,
184    ) -> impl Iterator<Item = ConsumerRouteView<'_>> {
185        self.topology.committed_consumer_routes().filter(|route| {
186            self.user_connection_id(&route.key.receiver)
187                == Some(route.route.consumer_session_key().connection_id())
188        })
189    }
190
191    pub fn user_connection_id(&self, user_id: &UserId) -> Option<ConnectionId> {
192        self.users.get(user_id).map(|user| user.connection_id)
193    }
194
195    pub fn user_snapshots_except(&self, excluded_user_id: &UserId) -> Vec<PeerSnapshot> {
196        self.users
197            .iter()
198            .filter(|(user_id, _session)| *user_id != excluded_user_id)
199            .map(|(user_id, user)| PeerSnapshot {
200                user_id: user_id.clone(),
201                info: user.project_info(),
202            })
203            .collect()
204    }
205
206    pub fn user_info_snapshot(&self, user_id: &UserId) -> Option<(UserId, UserInfo)> {
207        let user = self.users.get(user_id)?;
208        Some((user_id.clone(), user.project_info()))
209    }
210
211    pub(in crate::engine::room) fn remote_track_snapshot_for_user(
212        &mut self,
213        user_id: &UserId,
214        requires_negotiation: bool,
215    ) -> RemoteTrackSnapshot {
216        let revision = self.next_track_snapshot_revision;
217        self.next_track_snapshot_revision = revision.saturating_add(1);
218        RemoteTrackSnapshot {
219            tracks: self.remote_tracks(user_id, self.user_connection_id(user_id)),
220            requires_negotiation,
221            revision,
222        }
223    }
224
225    /// Tracks `connection_id` consumes as the room has them now, for the offer
226    /// that lists their consumer media.
227    ///
228    /// Carries the revision of the newest snapshot built so far, so only a
229    /// snapshot built later supersedes it.
230    pub(in crate::engine::room) fn committed_remote_tracks(
231        &self,
232        user_id: &UserId,
233        connection_id: ConnectionId,
234    ) -> RemoteTrackSnapshot {
235        RemoteTrackSnapshot {
236            tracks: self.remote_tracks(user_id, Some(connection_id)),
237            requires_negotiation: false,
238            revision: self.next_track_snapshot_revision.saturating_sub(1),
239        }
240    }
241
242    fn remote_tracks(
243        &self,
244        user_id: &UserId,
245        connection_id: Option<ConnectionId>,
246    ) -> Vec<RemoteTrack> {
247        self.topology
248            .committed_consumer_routes_for_user(user_id)
249            .filter(|route| {
250                connection_id == Some(route.route.consumer_session_key().connection_id())
251            })
252            .map(|route| {
253                let source = &route.source.descriptor;
254                RemoteTrack {
255                    consumer_media: route.route.consumer_transport_media_id(),
256                    user_id: source.owner().user_id().clone(),
257                    stream_id: source.stream_id().clone(),
258                    producer_active: route.source.active,
259                }
260            })
261            .collect()
262    }
263
264    pub(in crate::engine::room) fn remote_track_snapshots_for_users(
265        &mut self,
266        user_ids: BTreeSet<UserId>,
267        requires_negotiation: bool,
268    ) -> Vec<(OutboundSender, RemoteTrackSnapshot)> {
269        user_ids
270            .into_iter()
271            .filter_map(|user_id| {
272                Some((
273                    self.users.get(&user_id)?.sender.clone(),
274                    self.remote_track_snapshot_for_user(&user_id, requires_negotiation),
275                ))
276            })
277            .collect()
278    }
279
280    pub fn user_stats_counts(&self) -> (u64, BTreeMap<UserStreamId, u64>) {
281        (
282            u64::try_from(self.users.len()).unwrap_or(u64::MAX),
283            self.topology.active_stream_user_counts(),
284        )
285    }
286}