o_sfu_core/engine/director/
commit.rs1use std::{collections::BTreeMap, time::Instant};
11
12use o_sfu_router::MediaKind;
13use o_sfu_telemetry::{metrics::BudgetSolverOutcome, schema::event as telemetry_event};
14use tracing::info;
15
16use super::{
17 action::{ConsumerPacketSelectionUpdate, FeaturedUserUpdate, ReceiverUpdate, UpgradeChange},
18 allocation::ReceiverVideoBudgetDiagnostics,
19 planner::VideoRouteTransition,
20};
21use crate::{
22 Bitrate, ConnectionId,
23 engine::{
24 observability,
25 room::{MessageFanout, Room, RoomEventMessage, RoomState},
26 source_model::{
27 PolicyPauseReason, SourceAdaptationPolicy, SourceEncodingId, SourceSelector,
28 },
29 },
30};
31
32pub(super) fn commit_allocations(
34 state: &mut RoomState,
35 updates: &mut [Vec<ConsumerPacketSelectionUpdate>],
36 receivers: &[ReceiverUpdate],
37 video_allocation_revision: u64,
38 outstanding_controls: &BTreeMap<ConnectionId, usize>,
39 now: Instant,
40) -> Option<Instant> {
41 let allocation_plan_is_current =
42 state.topology.video_allocation_revision() == video_allocation_revision;
43 let reconcile_planned_budgets =
44 !allocation_plan_is_current || outstanding_controls.values().any(|count| *count > 0);
45 let receiver_controls_accepted = |connection| {
46 outstanding_controls
47 .get(&connection)
48 .is_none_or(|count| *count == 0)
49 };
50 let mut next_deadline = None;
51 if allocation_plan_is_current {
54 for receiver in receivers {
55 let accepted = receiver_controls_accepted(receiver.connection_id);
56 let Some(user) =
57 state.user_mut_for_connection(&receiver.receiver, receiver.connection_id)
58 else {
59 continue;
60 };
61 let soft_pause_deadline = receiver.allocation.soft_pause_deadline;
62 if soft_pause_deadline.is_none() || accepted {
64 user.allocation.soft_pause_deadline = soft_pause_deadline;
65 }
66 let deadline = if accepted {
70 receiver.next_deadline
71 } else {
72 receiver.retained_deadline
73 };
74 if let Some(deadline) = deadline.filter(|deadline| *deadline > now) {
75 next_deadline =
76 Some(next_deadline.map_or(deadline, |next: Instant| next.min(deadline)));
77 }
78 }
79 for route in receivers
82 .iter()
83 .flat_map(|receiver| &receiver.budget_routes)
84 .filter(|route| route.interrupts_upgrade)
85 {
86 state
87 .topology
88 .update_consumer_upgrade(&route.key, route.source_id, &route.route, None);
89 }
90 for update in updates.iter().flatten() {
91 if update.interrupts_upgrade {
92 state.topology.update_consumer_upgrade(
93 &update.key,
94 update.source_id,
95 &update.route,
96 None,
97 );
98 }
99 }
100 }
101 for batch in updates {
102 batch.retain_mut(|update| {
103 let committed = state.topology.update_consumer_allocation(
104 &update.key,
105 update.source_id,
106 &update.route,
107 |allocation| *allocation = update.allocation,
108 );
109 if committed
112 && update.transition.is_some()
113 && reconcile_planned_budgets
114 && !route_transition_remains_observable(state, update)
115 {
116 update.transition = None;
117 }
118 if let UpgradeChange::Set(pending_upgrade) = update.upgrade
119 && committed
120 && allocation_plan_is_current
121 && receiver_controls_accepted(update.route.consumer_session_key().connection_id())
122 && state.user_connection_id(&update.key.receiver)
123 == Some(update.route.consumer_session_key().connection_id())
124 {
125 state.topology.update_consumer_upgrade(
126 &update.key,
127 update.source_id,
128 &update.route,
129 pending_upgrade,
130 );
131 }
132 committed
133 });
134 }
135 for receiver in receivers {
136 let budget = if reconcile_planned_budgets && !receiver.budget_routes.is_empty() {
137 reconciled_budget(state, receiver)
138 } else {
139 allocation_plan_is_current.then_some(receiver.allocation.budget)
140 };
141 if let Some(budget) = budget
142 && let Some(user) =
143 state.user_mut_for_connection(&receiver.receiver, receiver.connection_id)
144 {
145 user.allocation.budget = budget;
146 }
147 }
148 next_deadline
149}
150
151fn route_transition_remains_observable(
152 state: &RoomState,
153 update: &ConsumerPacketSelectionUpdate,
154) -> bool {
155 state.user_connection_id(&update.key.receiver)
156 == Some(update.route.consumer_session_key().connection_id())
157 && state
158 .topology
159 .committed_consumer_route_for_key(&update.key)
160 .is_some_and(|route| {
161 route.source.descriptor.source_id() == update.source_id
162 && route.route == &update.route
163 && route.source.active
164 && route.intent.is_active()
165 })
166}
167
168fn reconciled_budget(
176 state: &RoomState,
177 receiver: &ReceiverUpdate,
178) -> Option<ReceiverVideoBudgetDiagnostics> {
179 let mut active_route_count = 0;
180 let mut selected_video_bitrate = Bitrate::zero();
181 let mut planned_routes = receiver.budget_routes.iter().peekable();
182 for route in state
183 .topology
184 .committed_consumer_routes_for_user(&receiver.receiver)
185 .filter(|route| {
186 receiver.connection_id == route.route.consumer_session_key().connection_id()
187 })
188 {
189 let policy = route.source.descriptor.policy();
190 if route.source.descriptor.media_kind() != MediaKind::Video
191 || (policy.adaptation() == SourceAdaptationPolicy::None
192 && policy.video_bitrate_cap().is_none())
193 {
194 continue;
195 }
196 while planned_routes
197 .next_if(|planned| &planned.key < route.key)
198 .is_some()
199 {}
200 let participating = route.source.active && route.intent.is_active();
201 let selected_bitrate = planned_routes
202 .next_if(|planned| &planned.key == route.key)
203 .filter(|planned| {
204 planned.source_id == route.source.descriptor.source_id()
205 && planned.route == *route.route
206 })
207 .and_then(|planned| {
208 if planned.planned == route.allocation {
209 Some(planned.bitrate.planned)
210 } else {
211 (planned.captured == route.allocation).then_some(planned.bitrate.captured)
212 }
213 });
214 let Some(selected_bitrate) = selected_bitrate else {
215 if participating {
216 return None;
217 }
218 continue;
219 };
220 if participating && route.allocation.allows_delivery() {
221 active_route_count += 1;
222 selected_video_bitrate = selected_video_bitrate.saturating_add(selected_bitrate);
223 }
224 }
225 let planned = receiver.allocation.budget;
226 Some(ReceiverVideoBudgetDiagnostics {
227 latest_receiver_bandwidth: planned.latest_receiver_bandwidth,
228 selected_video_budget: planned.selected_video_budget,
229 active_video_route_count: active_route_count,
230 selected_video_bitrate,
231 })
232}
233
234pub(super) fn commit_featured_user_updates(
235 state: &mut RoomState,
236 updates: &[FeaturedUserUpdate],
237) -> Option<MessageFanout> {
238 let mut changed_user_ids = Vec::new();
239 for update in updates {
240 let Some(user) = state.user_mut_for_connection(&update.user_id, update.connection_id)
241 else {
242 continue;
243 };
244 if user.featured() == update.featured {
245 continue;
246 }
247 user.set_featured(update.featured);
248 changed_user_ids.push(update.user_id.clone());
249 }
250 if changed_user_ids.is_empty() {
251 return None;
252 }
253 let snapshot = changed_user_ids
254 .into_iter()
255 .filter_map(|user_id| state.user_info_snapshot(&user_id))
256 .collect();
257 Some(state.fanout_all(RoomEventMessage::UserInfoChanged(snapshot)))
258}
259
260pub(super) fn record_committed_selection_updates(
261 room: &Room,
262 updates: &[ConsumerPacketSelectionUpdate],
263) {
264 for update in updates {
265 if update.packet_gate.is_some() {
266 room.metrics
267 .record_source_selection_update(observability::source_selection_kind(
268 update.allocation.selector(),
269 ));
270 }
271 let Some(transition) = update.transition else {
272 continue;
273 };
274 let (metric_outcome, outcome, reason) = match transition {
275 VideoRouteTransition::Degraded => (BudgetSolverOutcome::Degraded, "degraded", None),
276 VideoRouteTransition::Paused { reason } => {
277 (BudgetSolverOutcome::Paused, "paused", Some(reason))
278 }
279 VideoRouteTransition::Resumed { cleared_reason } => (
280 BudgetSolverOutcome::Resumed,
281 "resumed",
282 Some(cleared_reason),
283 ),
284 };
285 room.metrics.record_budget_solver_outcome(metric_outcome);
286 let consumer = update.route.consumer_session_key();
287 let source = update.route.source_session_key();
288 let selector = update.allocation.selector();
289 info!(
290 event = telemetry_event::SOURCE_POLICY_ROUTE_CHANGED,
291 room_id = room.uuid(),
292 user_id = %consumer.user_id().path_segment(),
293 connection_id = consumer.connection_id().as_u64(),
294 media_worker_id = consumer.media_worker_id().as_usize(),
295 transport_media_id = update.route.consumer_transport_media_id().as_u64(),
296 producer_user_id = %source.user_id().path_segment(),
297 source_transport_media_id = update.route.source_transport_media_id().as_u64(),
298 stream_id = %update.key.stream,
299 outcome,
300 reason = reason.map(policy_pause_reason_name),
301 latest_receiver_bandwidth_estimate_bps = update
302 .budget
303 .latest_receiver_bandwidth
304 .map(Bitrate::as_bps),
305 selected_video_budget_bps = update.budget.selected_video_budget.map(Bitrate::as_bps),
306 planned_active_video_route_count = update.budget.active_video_route_count,
307 planned_selected_video_bitrate_bps = update.budget.selected_video_bitrate.as_bps(),
308 selector = source_selector_name(selector),
309 selected_encoding_id = selector.selected_encoding().map(SourceEncodingId::as_u64),
310 selected_estimated_bitrate_bps = update.selected_estimated_bitrate.map(Bitrate::as_bps),
311 "source policy route changed"
312 );
313 }
314}
315
316const fn source_selector_name(selector: SourceSelector) -> &'static str {
317 match selector {
318 SourceSelector::Open => "open",
319 SourceSelector::Encoding(_) => "encoding",
320 }
321}
322
323const fn policy_pause_reason_name(reason: PolicyPauseReason) -> &'static str {
324 match reason {
325 PolicyPauseReason::BudgetPressure => "budget_pressure",
326 PolicyPauseReason::HiddenTile => "hidden_tile",
327 PolicyPauseReason::OverflowTile => "overflow_tile",
328 PolicyPauseReason::MissingUsableLayer => "missing_usable_layer",
329 PolicyPauseReason::AudioSpeakerLimit => "audio_speaker_limit",
330 PolicyPauseReason::ReceiverDeafened => "receiver_deafened",
331 PolicyPauseReason::VideoDownloadLimit => "video_download_limit",
332 PolicyPauseReason::SourceBitrateLimit => "source_bitrate_limit",
333 }
334}