Skip to main content

o_sfu_core/engine/source_model/
policy.rs

1use o_sfu_model::VideoLayoutIntent;
2use o_sfu_transport::SourceSyncPolicy;
3
4use crate::Bitrate;
5
6/// room policy applied to one published source
7///
8/// [`SourcePolicy`] is the source contract between application publish intent
9/// and core room policy
10/// it tells core what it may do with a source after
11/// publish, but it does not name the product feature that created the stream
12/// and it does not limit how many streams a user may publish
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct SourcePolicy {
15    layout: Option<SourceLayoutPolicy>,
16    adaptation: SourceAdaptationPolicy,
17    active_speaker: Option<ActiveSpeakerPolicy>,
18    video_bitrate_cap: Option<Bitrate>,
19    sync: SourceSyncPolicy,
20}
21
22impl SourcePolicy {
23    #[must_use]
24    pub const fn new(
25        layout: Option<SourceLayoutPolicy>,
26        adaptation: SourceAdaptationPolicy,
27        active_speaker: Option<ActiveSpeakerPolicy>,
28    ) -> Self {
29        Self {
30            layout,
31            adaptation,
32            active_speaker,
33            video_bitrate_cap: None,
34            sync: SourceSyncPolicy::Independent,
35        }
36    }
37
38    #[must_use]
39    pub const fn with_video_bitrate_cap(self, max_bitrate: Bitrate) -> Self {
40        Self {
41            video_bitrate_cap: Some(max_bitrate),
42            ..self
43        }
44    }
45
46    /// Sets SDP grouping for newly declared consumers.
47    #[must_use]
48    pub const fn with_sync(self, sync: SourceSyncPolicy) -> Self {
49        Self { sync, ..self }
50    }
51
52    #[must_use]
53    pub const fn sync(self) -> SourceSyncPolicy {
54        self.sync
55    }
56
57    #[must_use]
58    pub const fn hidden() -> Self {
59        Self::new(None, SourceAdaptationPolicy::None, None)
60    }
61
62    #[must_use]
63    pub const fn layout(self) -> Option<SourceLayoutPolicy> {
64        self.layout
65    }
66
67    #[must_use]
68    pub const fn adaptation(self) -> SourceAdaptationPolicy {
69        self.adaptation
70    }
71
72    #[must_use]
73    pub const fn active_speaker(self) -> Option<ActiveSpeakerPolicy> {
74        self.active_speaker
75    }
76
77    #[must_use]
78    pub const fn video_bitrate_cap(self) -> Option<Bitrate> {
79        self.video_bitrate_cap
80    }
81}
82
83/// default receiver-layout role for one source
84///
85/// core combines publish intent, receiver layout preference and active-speaker
86/// state to choose one [`SourceRoomPolicySelector`] per receiver/source route
87/// sources without layout policy stay out of video budget planning
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub struct SourceLayoutPolicy {
90    visible_selector: SourceRoomPolicySelector,
91    active_speaker_selector: Option<SourceRoomPolicySelector>,
92}
93
94impl SourceLayoutPolicy {
95    #[must_use]
96    pub const fn new(
97        visible_selector: SourceRoomPolicySelector,
98        active_speaker_selector: Option<SourceRoomPolicySelector>,
99    ) -> Self {
100        Self {
101            visible_selector,
102            active_speaker_selector,
103        }
104    }
105
106    /// Resolves a receiver-specific layout role.
107    ///
108    /// Explicit [`VideoLayoutIntent`] wins so active-speaker observations cannot
109    /// override that receiver's layout. Without explicit intent, an active speaker
110    /// uses `active_speaker_selector` when configured. If neither explicit intent
111    /// nor active-speaker selection applies, `visible_selector` is used.
112    /// A missing preference resolves as [`VideoLayoutIntent::Default`].
113    #[must_use]
114    pub fn resolve(
115        self,
116        preference: Option<VideoLayoutIntent>,
117        active_speaker: bool,
118    ) -> SourceRoomPolicySelector {
119        match preference.unwrap_or(VideoLayoutIntent::Default) {
120            VideoLayoutIntent::Pinned => SourceRoomPolicySelector::Pinned,
121            VideoLayoutIntent::Featured => SourceRoomPolicySelector::Featured,
122            VideoLayoutIntent::Hidden => SourceRoomPolicySelector::Hidden,
123            VideoLayoutIntent::Overflow => SourceRoomPolicySelector::Overflow,
124            VideoLayoutIntent::VisibleThumbnail => self.visible_selector,
125            VideoLayoutIntent::Default => self
126                .active_speaker_selector
127                .filter(|_| active_speaker)
128                .unwrap_or(self.visible_selector),
129        }
130    }
131}
132
133/// receiver bandwidth behavior for one published source
134///
135/// set by [`SourcePublishIntent`](crate::prelude::SourcePublishIntent) to decide
136/// whether the source participates in receiver-video layer selection, route
137/// pausing and over-budget diagnostics
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub enum SourceAdaptationPolicy {
140    /// keep this source out of receiver-video BWE control
141    ///
142    /// useful for audio or metadata-like sources that can route through normal
143    /// subscriptions without spending visible-video budget
144    None,
145    /// let the receiver-video planner budget the source and choose an encoding
146    ///
147    /// useful for sources where thumbnail routes may downswitch or pause under
148    /// receiver budget pressure
149    ScalableVideo,
150    /// keep readable detail ahead of normal thumbnail adaptation
151    ///
152    /// useful for text-heavy visual sources that stay on the highest advertised
153    /// encoding until lower-priority routes are exhausted then pause if needed
154    ReadableDetail,
155}
156
157/// active-speaker relationship declared for one source
158///
159/// publish intent decides which sources participate in transport-observed
160/// speech relationships
161#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162pub struct ActiveSpeakerPolicy {
163    group: ActiveSpeakerGroup,
164    role: ActiveSpeakerSourceRole,
165}
166
167impl ActiveSpeakerPolicy {
168    #[must_use]
169    pub const fn new(group: ActiveSpeakerGroup, role: ActiveSpeakerSourceRole) -> Self {
170        Self { group, role }
171    }
172
173    #[must_use]
174    pub const fn group(self) -> ActiveSpeakerGroup {
175        self.group
176    }
177
178    #[must_use]
179    pub const fn role(self) -> ActiveSpeakerSourceRole {
180        self.role
181    }
182}
183
184/// active-speaker group id used to separate speech relationships
185///
186/// groups keep unrelated speech domains separate without teaching core about
187/// application stream names
188#[derive(Debug, Clone, Copy, PartialEq, Eq)]
189pub struct ActiveSpeakerGroup(u16);
190
191impl ActiveSpeakerGroup {
192    pub const MAIN: Self = Self(0);
193}
194
195/// role one source plays inside an active-speaker group
196#[derive(Debug, Clone, Copy, PartialEq, Eq)]
197pub enum ActiveSpeakerSourceRole {
198    /// transport observations from this source can mark its owner active
199    ///
200    /// detectors are usually audio-like and do not receive video layout
201    /// treatment by themselves
202    Detector,
203    /// this source can receive active-speaker video treatment for its owner
204    ///
205    /// core promotes it only when a detector in the same group marks the same
206    /// owner as active
207    Promotable,
208}
209
210/// receiver-specific layout role before a concrete encoding is chosen
211///
212/// the budget planner reads this role to decide quality targets and pause order
213/// transport code only sees the final packet gate after the role resolves
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215pub enum SourceRoomPolicySelector {
216    /// the receiver explicitly pinned this source
217    ///
218    /// pinned routes use featured quality and share the highest budget priority
219    /// with featured routes
220    Pinned,
221    /// the receiver explicitly requested featured treatment for this source
222    ///
223    /// featured routes use featured quality and share the highest budget
224    /// priority with pinned routes
225    Featured,
226    /// source policy says readable detail matters for this route
227    ///
228    /// explicit pinned or featured receiver intent outranks this role
229    ReadableDetail,
230    /// active-speaker policy promoted this source for the current receiver
231    ///
232    /// explicit receiver intent and readable detail outrank this role
233    ActiveSpeaker,
234    /// the source is visible as a secondary tile
235    ///
236    /// visible thumbnails downswitch and pause before higher-priority routes
237    VisibleThumbnail,
238    /// the receiver is subscribed but the source is not visible right now
239    ///
240    /// hidden routes skip visible-video budget and are first candidates for
241    /// overload pause
242    Hidden,
243    /// the source is outside the receiver's visible tile set
244    ///
245    /// overflow routes behave like hidden routes but keep a distinct pause
246    /// reason for diagnostics
247    Overflow,
248}
249
250impl SourceRoomPolicySelector {
251    #[must_use]
252    pub const fn priority(self) -> SourceRoutePriority {
253        match self {
254            Self::Pinned | Self::Featured => SourceRoutePriority::PinnedOrFeatured,
255            Self::ReadableDetail => SourceRoutePriority::ReadableDetail,
256            Self::ActiveSpeaker => SourceRoutePriority::ActiveSpeaker,
257            Self::VisibleThumbnail => SourceRoutePriority::VisibleThumbnail,
258            Self::Hidden | Self::Overflow => SourceRoutePriority::HiddenOrOverflow,
259        }
260    }
261
262    #[must_use]
263    pub const fn uses_featured_quality(self) -> bool {
264        matches!(
265            self,
266            Self::Pinned | Self::Featured | Self::ReadableDetail | Self::ActiveSpeaker
267        )
268    }
269
270    #[must_use]
271    pub const fn counts_toward_visible_budget(self) -> bool {
272        !matches!(self, Self::Hidden | Self::Overflow)
273    }
274}
275
276/// overload priority derived from a route's room-policy selector
277///
278/// Each downgrade or pause pass visits lower priorities first. All eligible
279/// encoding downsteps precede whole-route pauses.
280#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
281pub enum SourceRoutePriority {
282    /// explicit receiver intent
283    ///
284    /// pinned and featured routes outrank every other route and pause last
285    PinnedOrFeatured,
286    /// detail-preserving source policy
287    ///
288    /// readable-detail routes outrank active-speaker routes but stay below
289    /// explicit pinned or featured receiver intent
290    ReadableDetail,
291    /// server-promoted active-speaker route
292    ///
293    /// explicit receiver intent and readable-detail source policy outrank this
294    /// role
295    ActiveSpeaker,
296    /// visible secondary route
297    ///
298    /// visible thumbnails downswitch and then pause before higher-priority routes
299    VisibleThumbnail,
300    /// route that is not currently visible
301    ///
302    /// hidden and overflow routes are first to pause under receiver budget
303    /// pressure
304    HiddenOrOverflow,
305}
306
307/// reason why room policy withholds media for a subscribed route
308///
309/// subscription state can remain active while the packet gate is closed for
310/// budget, layout or activation-cap reasons
311#[derive(Debug, Clone, Copy, PartialEq, Eq)]
312pub enum PolicyPauseReason {
313    /// the receiver budget cannot fit this route after cheaper layers were tried
314    BudgetPressure,
315    /// the receiver layout explicitly hides this source
316    HiddenTile,
317    /// the receiver layout puts this source outside the visible tile set
318    OverflowTile,
319    /// no negotiated encoding can be forwarded usefully
320    MissingUsableLayer,
321    /// the active-audio-speaker cap withheld this route
322    AudioSpeakerLimit,
323    /// the receiver deafened itself so no audio is delivered to it
324    ReceiverDeafened,
325    /// the per-receiver live-video cap withheld this route
326    VideoDownloadLimit,
327    /// the source bitrate cap withheld this route
328    SourceBitrateLimit,
329}
330
331/// server-defined role for one published source encoding
332///
333/// the role lets the budget planner choose an encoding without reading
334/// application stream names
335#[derive(Debug, Clone, Copy, PartialEq, Eq)]
336pub enum UploadLayerPolicyRole {
337    /// highest useful quality for high-priority or detail-focused routes
338    ///
339    /// the planner avoids this as the first cheap fallback when a lower-cost
340    /// encoding exists
341    Featured,
342    /// normal quality target for visible secondary video
343    ///
344    /// expected low-cost encoding before the planner considers pausing the route
345    Thumbnail,
346    /// lower-cost thumbnail rung below the normal thumbnail target
347    ///
348    /// reserved for upload ladders with more than two useful video encodings
349    DegradedThumbnail,
350}
351
352impl UploadLayerPolicyRole {
353    #[must_use]
354    pub const fn as_wire_value(self) -> &'static str {
355        match self {
356            Self::Featured => "featured",
357            Self::Thumbnail => "thumbnail",
358            Self::DegradedThumbnail => "degradedThumbnail",
359        }
360    }
361}