Skip to main content

o_sfu_core/engine/director/planner/
audio.rs

1use o_sfu_router::MediaKind;
2
3use super::{PolicyFacts, RouteFacts, RoutePlan, speakers::SpeakerPlan};
4use crate::{Bitrate, engine::source_model::PolicyPauseReason};
5
6const AUDIO_PAUSE_REASONS: [PolicyPauseReason; 2] = [
7    PolicyPauseReason::AudioSpeakerLimit,
8    PolicyPauseReason::ReceiverDeafened,
9];
10
11/// Plans the activity of every considered audio consumer.
12///
13/// The policy computes one room-wide admitted active-speaker set and applies it
14/// to every considered receiver route.
15///
16/// # Policy Invariants
17///
18/// 1. **Deafness Dominance**: If a receiver is deafened, each considered audio route is paused
19///    with [`PolicyPauseReason::ReceiverDeafened`]. When undeafened, routes are not blindly
20///    resumed; they are re-evaluated against the current active speaker quota.
21/// 2. **Low-Latency Voice Onset**: For a receiver that is not deafened, sources outside the
22///    room-wide active-source set remain unpaused by audio route policy. Worker-local VAD gating
23///    is separate and opens before destination planning on a VAD-true packet, so that packet does
24///    not wait for a policy turn.
25/// 3. **Active Speaker Admission**: When the room has more active speakers than
26///    `max_active_audio_speakers`, screen-sharers are admitted first. Sources otherwise retain
27///    room ranking by newest observation, audio level and source id. Sources beyond the limit are
28///    paused with [`PolicyPauseReason::AudioSpeakerLimit`].
29/// 4. **Pause Reason Ownership**: Audio policy sets only reasons in [`AUDIO_PAUSE_REASONS`].
30///    It clears a pause only when the current reason belongs to that set.
31///
32/// ```text
33///                     Incoming Audio Route (Receiver, Source)
34///                                         |
35///                                         v
36///                         +-------------------------------+
37///                         |   Is Receiver Deafened?       | -- yes --> [ Pause: ReceiverDeafened ]
38///                         +-------------------------------+
39///                                         | no
40///                                         v
41///                         +-------------------------------+
42///                         |   Is Source in Room Active    | -- no  --> [ No Audio-Owned Pause ]
43///                         |   Set?                        |             (VAD gate is separate)
44///                         +-------------------------------+
45///                                         | yes
46///                                         v
47///                         +-------------------------------+
48///                         |   Within Active Speaker Cap?  | -- yes --> [ No Audio-Owned Pause ]
49///                         |  (Screen-sharers prioritized) |
50///                         +-------------------------------+
51///                                         | no
52///                                         v
53///                             [ Pause: AudioSpeakerLimit ]
54/// ```
55pub(super) fn plan(facts: &PolicyFacts<'_>, speakers: &SpeakerPlan, plans: &mut [RoutePlan]) {
56    for (route, plan) in facts.routes.iter().zip(plans) {
57        if route.source.media_kind() != MediaKind::Audio {
58            continue;
59        }
60        let next_reason = pause_reason(facts, speakers, route);
61        // Clear only pause reasons owned by audio policy. A refresh must not
62        // resume a route still withheld by another policy.
63        if next_reason.is_none() && !owns_pause_reason(route.allocation.pause_reason()) {
64            continue;
65        }
66        plan.allocation.pause_reason = next_reason;
67    }
68}
69
70/// Bandwidth each receiver reserves for admitted audio before video budgeting.
71///
72/// Each receiver reserves `audio_reserve_per_speaker` for every admitted audio
73/// route it consumes, so a receiver that disabled audio, deafened itself or
74/// consumes nothing reserves nothing and keeps its full video budget. The
75/// reserve is fixed per route, so it does not depend on policy-turn cadence.
76/// A zero per-speaker rate, the default, disables the reservation.
77pub(super) fn reserve_by_receiver(facts: &PolicyFacts<'_>, speakers: &SpeakerPlan) -> Vec<Bitrate> {
78    let per_speaker = facts.tuning.audio_reserve_per_speaker;
79    let mut reserves = vec![Bitrate::zero(); facts.receivers.len()];
80    if per_speaker.as_bps() == 0 || speakers.admitted_audio.is_empty() {
81        return reserves;
82    }
83    for route in &facts.routes {
84        if route.source.media_kind() != MediaKind::Audio
85            || !speakers.admitted_audio.contains(&route.source.source_id())
86            || receiver_deaf(facts, route)
87        {
88            continue;
89        }
90        if let Some(reserve) = reserves.get_mut(route.receiver) {
91            *reserve = reserve.saturating_add(per_speaker);
92        }
93    }
94    reserves
95}
96
97fn pause_reason(
98    facts: &PolicyFacts<'_>,
99    speakers: &SpeakerPlan,
100    route: &RouteFacts<'_>,
101) -> Option<PolicyPauseReason> {
102    // Deafness dominates speaker admission. Undeafening recomputes the cap
103    // instead of blindly resuming every audio route.
104    if receiver_deaf(facts, route) {
105        return Some(PolicyPauseReason::ReceiverDeafened);
106    }
107    speakers
108        .limited_audio
109        .contains(&route.source.source_id())
110        .then_some(PolicyPauseReason::AudioSpeakerLimit)
111}
112
113fn receiver_deaf(facts: &PolicyFacts<'_>, route: &RouteFacts<'_>) -> bool {
114    facts
115        .receivers
116        .get(route.receiver)
117        .is_some_and(|receiver| receiver.deaf)
118}
119
120fn owns_pause_reason(current_reason: Option<PolicyPauseReason>) -> bool {
121    current_reason.is_some_and(|reason| AUDIO_PAUSE_REASONS.contains(&reason))
122}