Skip to main content

o_sfu_core/engine/director/
action.rs

1//! Records turn execution derives from a plan. Each carries the room identity
2//! that its commit checks again after the transport await.
3
4use std::time::Instant;
5
6use o_sfu_model::UserId;
7use o_sfu_transport::{
8    ConsumerActivity, ConsumerRouteControl, SourcePacketGate, TransportConsumerRoute,
9};
10
11use super::{
12    allocation::{
13        PendingUpgrade, ReceiverAllocation, ReceiverVideoBudgetDiagnostics, RouteAllocation,
14    },
15    planner::{BudgetBitrate, RoutePlan, VideoRouteTransition},
16};
17use crate::{
18    Bitrate, ConnectionId,
19    engine::{
20        room::{ConsumerRouteView, SubscriptionKey},
21        source_model::{PublishedSourceDescriptor, PublishedSourceId, SourceSelector},
22    },
23};
24
25/// Budgeted video consumer of a receiver whose controls changed. Partial
26/// transport acceptance reconciles the receiver budget from these.
27#[derive(Debug)]
28pub(super) struct VideoRouteAllocation {
29    pub(super) key: SubscriptionKey,
30    pub(super) source_id: PublishedSourceId,
31    pub(super) route: TransportConsumerRoute,
32    pub(super) interrupts_upgrade: bool,
33    pub(super) captured: RouteAllocation,
34    pub(super) planned: RouteAllocation,
35    pub(super) bitrate: BudgetBitrate,
36}
37
38impl VideoRouteAllocation {
39    pub(super) fn new(
40        view: &ConsumerRouteView<'_>,
41        plan: &RoutePlan,
42        bitrate: BudgetBitrate,
43    ) -> Self {
44        Self {
45            key: view.key.clone(),
46            source_id: view.source.descriptor.source_id(),
47            route: view.route.clone(),
48            interrupts_upgrade: plan.interrupts_upgrade,
49            captured: view.allocation,
50            planned: plan.allocation,
51            bitrate,
52        }
53    }
54}
55
56/// Receiver allocation a turn commits once its controls settle.
57#[derive(Debug)]
58pub(super) struct ReceiverUpdate {
59    pub(super) receiver: UserId,
60    pub(super) connection_id: ConnectionId,
61    pub(super) allocation: ReceiverAllocation,
62    pub(super) next_deadline: Option<Instant>,
63    /// Existing eligible wakeups survive rejection of an unrelated control.
64    pub(super) retained_deadline: Option<Instant>,
65    /// Ordered by [`SubscriptionKey`] for linear reconciliation. Empty unless
66    /// a control of one of the receiver's budgeted consumers changed.
67    pub(super) budget_routes: Vec<VideoRouteAllocation>,
68}
69
70/// Only changed upgrade state requires validation and a topology write.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub(super) enum UpgradeChange {
73    Unchanged,
74    Set(Option<PendingUpgrade>),
75}
76
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub(in crate::engine) struct ConsumerPacketSelectionUpdate {
79    pub(super) key: SubscriptionKey,
80    pub(super) source_id: PublishedSourceId,
81    pub(in crate::engine) route: TransportConsumerRoute,
82    pub(super) allocation: RouteAllocation,
83    /// Planned budget of the receiver, reported with a transition.
84    pub(super) budget: ReceiverVideoBudgetDiagnostics,
85    pub(super) transition: Option<VideoRouteTransition>,
86    pub(super) selected_estimated_bitrate: Option<Bitrate>,
87    pub(super) upgrade: UpgradeChange,
88    pub(super) interrupts_upgrade: bool,
89    pub(super) packet_gate: Option<SourcePacketGate>,
90    pub(super) route_activity_changed: bool,
91    pub(super) request_keyframe: bool,
92}
93
94impl ConsumerPacketSelectionUpdate {
95    /// Returns `None` when the planned encoding has no negotiated RID.
96    pub(super) fn new(
97        view: &ConsumerRouteView<'_>,
98        plan: &RoutePlan,
99        budget: ReceiverVideoBudgetDiagnostics,
100    ) -> Option<Self> {
101        let captured = view.allocation;
102        let packet_gate = if plan.allocation.selector() == captured.selector() {
103            None
104        } else {
105            Some(packet_gate(
106                &view.source.descriptor,
107                plan.allocation.selector(),
108            )?)
109        };
110        Some(Self {
111            key: view.key.clone(),
112            source_id: view.source.descriptor.source_id(),
113            route: view.route.clone(),
114            allocation: plan.allocation,
115            budget,
116            transition: plan.transition,
117            selected_estimated_bitrate: plan.selected_estimated_bitrate,
118            upgrade: if plan.pending_upgrade == view.pending_upgrade {
119                UpgradeChange::Unchanged
120            } else {
121                UpgradeChange::Set(plan.pending_upgrade)
122            },
123            interrupts_upgrade: plan.interrupts_upgrade,
124            packet_gate,
125            route_activity_changed: plan.allocation.pause_reason() != captured.pause_reason(),
126            request_keyframe: plan.request_keyframe,
127        })
128    }
129
130    pub(super) const fn requires_media_transport_effect(&self) -> bool {
131        self.packet_gate.is_some() || self.route_activity_changed || self.request_keyframe
132    }
133
134    pub(in crate::engine) fn route_control(&self) -> ConsumerRouteControl {
135        let mut control =
136            ConsumerRouteControl::new(self.route.clone()).request_keyframe(self.request_keyframe);
137        if self.route_activity_changed {
138            control = control.activity(ConsumerActivity::from_active(self.route_active()));
139        }
140        if let Some(packet_gate) = &self.packet_gate {
141            control = control.packet_gate(packet_gate.clone());
142        }
143        control
144    }
145
146    pub(in crate::engine) const fn route_active(&self) -> bool {
147        self.allocation.allows_delivery()
148    }
149}
150
151#[derive(Debug, Clone, PartialEq, Eq)]
152pub(super) struct FeaturedUserUpdate {
153    pub(super) user_id: UserId,
154    pub(super) connection_id: ConnectionId,
155    pub(super) featured: Option<bool>,
156}
157
158/// Projects a selector into a source-worker packet gate.
159///
160/// Returns `None` when the selected encoding is unknown or has no negotiated RID.
161fn packet_gate(
162    source: &PublishedSourceDescriptor,
163    selector: SourceSelector,
164) -> Option<SourcePacketGate> {
165    match selector {
166        SourceSelector::Open => Some(SourcePacketGate::Open),
167        SourceSelector::Encoding(encoding_id) => {
168            // Never fall back to `Open`: it would forward every encoding while
169            // room state records one selected encoding.
170            let rid = source.encoding(encoding_id)?.rid()?;
171            Some(SourcePacketGate::Rid(rid.as_str().to_owned()))
172        }
173    }
174}