Skip to main content

o_sfu_core/engine/director/planner/video/
solver.rs

1//! One receiver's video plan: budget -> plan -> admit -> fit -> dwell -> route plans.
2
3use std::{cmp::Reverse, time::Instant};
4
5use itertools::Itertools;
6use o_sfu_router::MediaKind;
7
8use super::{
9    super::{BudgetBitrate, ReceiverPlan, RoutePlan, VideoRouteTransition},
10    input::ReceiverVideoRouteInput,
11};
12use crate::{
13    Bitrate, VideoAdaptationTuning,
14    engine::{
15        director::allocation::{
16            PendingUpgrade, ReceiverAllocation, ReceiverVideoBudgetDiagnostics, RouteAllocation,
17        },
18        source_model::{
19            PolicyPauseReason, PublishedSourceDescriptor, PublishedSourceId,
20            SourceAdaptationPolicy, SourceEncodingDescriptor, SourceRoomPolicySelector,
21            SourceRoutePriority, SourceSelector,
22        },
23    },
24};
25
26/// ordering key shared by policy refresh and pre-setup receiver admission
27#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
28pub struct VideoAdmissionRank {
29    /// lower values admit more important layout roles first
30    priority: u8,
31    /// active-speaker order, or `usize::MAX` for non-speakers
32    active_speaker_rank: usize,
33    /// deterministic tie-breaker after priority and speaker rank
34    source_id: u64,
35}
36
37impl VideoAdmissionRank {
38    pub const fn new(
39        priority: SourceRoutePriority,
40        active_speaker_rank: Option<usize>,
41        source_id: PublishedSourceId,
42    ) -> Self {
43        Self {
44            priority: match priority {
45                SourceRoutePriority::PinnedOrFeatured => 0,
46                SourceRoutePriority::ReadableDetail => 1,
47                SourceRoutePriority::ActiveSpeaker => 2,
48                SourceRoutePriority::VisibleThumbnail => 3,
49                SourceRoutePriority::HiddenOrOverflow => 4,
50            },
51            active_speaker_rank: match active_speaker_rank {
52                Some(rank) => rank,
53                None => usize::MAX,
54            },
55            source_id: source_id.as_u64(),
56        }
57    }
58}
59
60/// candidate selector and policy pause state before the route plan
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62struct ReceiverRouteSelection {
63    /// packet selector to commit if the route stays deliverable
64    selector: SourceSelector,
65    /// policy reason that keeps receiver intent while blocking delivery
66    policy_pause_reason: Option<PolicyPauseReason>,
67    pending_upgrade: Option<PendingUpgrade>,
68    /// decoder refresh requested after selector changes or delivery resumes
69    request_keyframe: bool,
70}
71
72impl ReceiverRouteSelection {
73    fn interrupts_upgrade(self, current: Option<PendingUpgrade>) -> bool {
74        current.is_some_and(|current| {
75            self.pending_upgrade.map_or_else(
76                || self.policy_pause_reason.is_some() || current.selector != self.selector,
77                |pending| current.selector != pending.selector,
78            )
79        })
80    }
81
82    const fn send(selector: SourceSelector, request_keyframe: bool) -> Self {
83        Self {
84            selector,
85            policy_pause_reason: None,
86            pending_upgrade: None,
87            request_keyframe,
88        }
89    }
90
91    const fn pause(selector: SourceSelector, reason: PolicyPauseReason) -> Self {
92        Self {
93            selector,
94            policy_pause_reason: Some(reason),
95            pending_upgrade: None,
96            request_keyframe: false,
97        }
98    }
99}
100
101/// planned receiver route after admission and budget pressure
102///
103/// `selected_bitrate` and `selection` must change together through
104/// [`Self::apply_resolved_selection`], [`Self::send`] or [`Self::pause`]
105#[derive(Debug, Clone, Copy)]
106struct PlannedReceiverRoute<'a> {
107    /// immutable route facts captured before policy mutation
108    input: &'a ReceiverVideoRouteInput<'a>,
109    /// bitrate counted against receiver budget after this policy step
110    selected_bitrate: Bitrate,
111    /// candidate selector, pause state and exact upgrade target
112    selection: ReceiverRouteSelection,
113}
114
115impl<'a> PlannedReceiverRoute<'a> {
116    fn new(input: &'a ReceiverVideoRouteInput<'a>, selection: ReceiverRouteSelection) -> Self {
117        let selected_bitrate = if selection.policy_pause_reason.is_some() {
118            Bitrate::zero()
119        } else {
120            selector_bitrate(input, selection.selector).unwrap_or_default()
121        };
122        Self {
123            input,
124            selected_bitrate,
125            selection,
126        }
127    }
128
129    fn apply_resolved_selection(&mut self, selection: ReceiverRouteSelection) {
130        *self = Self::new(self.input, selection);
131    }
132
133    fn send(&mut self, selector: SourceSelector, selected_bitrate: Bitrate) {
134        self.selected_bitrate = selected_bitrate;
135        self.selection = ReceiverRouteSelection::send(selector, self.selection.request_keyframe);
136    }
137
138    fn pause(&mut self, reason: PolicyPauseReason) {
139        self.selected_bitrate = Bitrate::zero();
140        self.selection = ReceiverRouteSelection::pause(self.selection.selector, reason);
141    }
142
143    fn to_route_plan(self) -> RoutePlan {
144        let input = self.input;
145        let selection = self.selection;
146        let current = input.current;
147        let request_keyframe = input.source.media_kind() == MediaKind::Video
148            && selection.policy_pause_reason.is_none()
149            && (selection.request_keyframe
150                || selection.selector != current.selector()
151                || !current.allows_delivery());
152        let transition = self.transition();
153        let captured_bitrate = if current.allows_delivery() {
154            selector_bitrate(input, current.selector()).unwrap_or_default()
155        } else {
156            Bitrate::zero()
157        };
158        RoutePlan {
159            allocation: RouteAllocation {
160                selector: selection.selector,
161                pause_reason: selection.policy_pause_reason,
162            },
163            pending_upgrade: selection.pending_upgrade,
164            interrupts_upgrade: selection.interrupts_upgrade(input.pending_upgrade),
165            request_keyframe,
166            transition,
167            selected_estimated_bitrate: transition
168                .and_then(|_| selector_bitrate(input, selection.selector)),
169            budget_bitrate: Some(BudgetBitrate {
170                captured: captured_bitrate,
171                planned: self.selected_bitrate,
172            }),
173        }
174    }
175
176    fn transition(self) -> Option<VideoRouteTransition> {
177        let current = self.input.current;
178        match (self.selection.policy_pause_reason, current.pause_reason()) {
179            (None, Some(cleared_reason)) => Some(VideoRouteTransition::Resumed { cleared_reason }),
180            (Some(reason), None) => Some(VideoRouteTransition::Paused { reason }),
181            (Some(_), Some(_)) => None,
182            (None, None) if self.selection.selector == current.selector() => None,
183            (None, None) => {
184                let current_selector @ SourceSelector::Encoding(_) = current.selector() else {
185                    return None;
186                };
187                let selected_selector @ SourceSelector::Encoding(_) = self.selection.selector
188                else {
189                    return None;
190                };
191                let current_bitrate = selector_bitrate(self.input, current_selector)?;
192                let selected_bitrate = selector_bitrate(self.input, selected_selector)?;
193                (selected_bitrate < current_bitrate).then_some(VideoRouteTransition::Degraded)
194            }
195        }
196    }
197}
198
199/// Fits hard-admitted targets before applying time-based continuity holds.
200///
201/// Eligible downsteps commit immediately. Soft overload may exceed the receiver
202/// budget during its dwell. Admitted BWE demand remains independent of that hold.
203pub(super) fn plan_receiver(
204    receiver_routes: &[ReceiverVideoRouteInput<'_>],
205    max_video_downloads_per_receiver: usize,
206    tuning: VideoAdaptationTuning,
207    current_soft_pause_deadline: Option<Instant>,
208    now: Instant,
209    receiver_plan: &mut ReceiverPlan,
210    route_plans: &mut [RoutePlan],
211) {
212    let Some(first_route) = receiver_routes.first() else {
213        return;
214    };
215    let receiver_bandwidth = first_route.receiver_bandwidth;
216    let video_budget = receiver_bandwidth.map(|bandwidth| {
217        effective_video_budget(bandwidth, tuning, first_route.audio_budget_reserve)
218    });
219    let mut planned_routes = receiver_routes
220        .iter()
221        .map(|route| PlannedReceiverRoute::new(route, route_plan(route, tuning)))
222        .collect::<Vec<_>>();
223    // Apply the hard route count before sharing bandwidth. Rejected routes must
224    // not consume receiver budget or force admitted routes down.
225    apply_video_download_limit(&mut planned_routes, max_video_downloads_per_receiver);
226    // str0m caps probes from the desired target. Use each hard-admitted route's
227    // highest allowed layer so current BWE cannot bound future discovery.
228    let eventual_admitted_video_bitrate = admitted_video_bwe_demand(&planned_routes);
229    if let Some(video_budget) = video_budget {
230        apply_overload_policy(&mut planned_routes, video_budget);
231    }
232    let soft_pause_deadline = resolve_receiver_dwell(
233        &mut planned_routes,
234        current_soft_pause_deadline,
235        tuning,
236        now,
237        receiver_plan,
238    );
239    let budget =
240        receiver_video_budget_diagnostics(&planned_routes, receiver_bandwidth, video_budget);
241    receiver_plan.allocation = ReceiverAllocation {
242        budget,
243        soft_pause_deadline,
244    };
245    // The target includes audio reserve. Add eventual admitted video demand so
246    // str0m can probe while overload pauses routes.
247    receiver_plan.bwe_target = receiver_plan
248        .bwe_target
249        .saturating_add(eventual_admitted_video_bitrate.max(budget.selected_video_bitrate));
250    for planned_route in &planned_routes {
251        if let Some(route_plan) = route_plans.get_mut(planned_route.input.index) {
252            *route_plan = planned_route.to_route_plan();
253        }
254    }
255}
256
257/// Resolves post-fit continuity and returns the receiver's soft-pause deadline.
258/// Records new and retained receiver wakeups on `receiver_plan`.
259fn resolve_receiver_dwell(
260    planned_routes: &mut [PlannedReceiverRoute<'_>],
261    current_soft_pause_deadline: Option<Instant>,
262    tuning: VideoAdaptationTuning,
263    now: Instant,
264    receiver_plan: &mut ReceiverPlan,
265) -> Option<Instant> {
266    let soft_pause_deadline = planned_routes
267        .iter()
268        .any(|route| {
269            route
270                .selection
271                .policy_pause_reason
272                .is_some_and(is_soft_pause)
273        })
274        .then(|| current_soft_pause_deadline.unwrap_or_else(|| now + tuning.soft_pause_dwell));
275    let mut next_deadline = soft_pause_deadline.filter(|deadline| *deadline > now);
276    let mut retained_deadline =
277        next_deadline.filter(|deadline| Some(*deadline) == current_soft_pause_deadline);
278    for route in planned_routes.iter_mut() {
279        let selection = resolve_dwell(route, tuning, soft_pause_deadline, now);
280        if let Some(upgrade) = selection
281            .pending_upgrade
282            .filter(|upgrade| upgrade.deadline > now)
283        {
284            next_deadline = Some(
285                next_deadline.map_or(upgrade.deadline, |deadline| deadline.min(upgrade.deadline)),
286            );
287            if route.input.pending_upgrade == Some(upgrade) {
288                retained_deadline = Some(
289                    retained_deadline
290                        .map_or(upgrade.deadline, |deadline| deadline.min(upgrade.deadline)),
291                );
292            }
293        }
294        route.apply_resolved_selection(selection);
295    }
296    receiver_plan.next_deadline = next_deadline;
297    receiver_plan.retained_deadline = retained_deadline;
298    soft_pause_deadline
299}
300
301fn route_plan(
302    route: &ReceiverVideoRouteInput<'_>,
303    tuning: VideoAdaptationTuning,
304) -> ReceiverRouteSelection {
305    let policy = route.source.policy().adaptation();
306    let source_cap = route.source.policy().video_bitrate_cap();
307    if source_cap.is_some_and(|cap| source_exceeds_bitrate_cap(route, cap)) {
308        return ReceiverRouteSelection::pause(
309            route.current.selector(),
310            PolicyPauseReason::SourceBitrateLimit,
311        );
312    }
313    let selection = match policy {
314        SourceAdaptationPolicy::ReadableDetail
315            if route.source.selectable_encoding_count() < 2 && source_cap.is_none() =>
316        {
317            None
318        }
319        SourceAdaptationPolicy::ReadableDetail | SourceAdaptationPolicy::None => {
320            highest_allowed_plan(route)
321        }
322        SourceAdaptationPolicy::ScalableVideo => scalable_plan(route, tuning),
323    }
324    .unwrap_or_else(|| {
325        if source_cap.is_some() {
326            ReceiverRouteSelection::pause(
327                route.current.selector(),
328                PolicyPauseReason::SourceBitrateLimit,
329            )
330        } else {
331            ReceiverRouteSelection::send(route.current.selector(), false)
332        }
333    });
334    if selection.policy_pause_reason.is_none()
335        && selector_bitrate(route, selection.selector).is_none()
336    {
337        return ReceiverRouteSelection::pause(
338            route.current.selector(),
339            PolicyPauseReason::MissingUsableLayer,
340        );
341    }
342    selection
343}
344
345fn source_exceeds_bitrate_cap(route: &ReceiverVideoRouteInput<'_>, cap: Bitrate) -> bool {
346    if route.source.selectable_encoding_count() > 1 {
347        return false;
348    }
349    // Missing data cannot prove recovery from a cap violation. Keep the route
350    // paused until a measured source rate is at or below the cap.
351    route.source_bitrate.map_or_else(
352        || route.current.pause_reason() == Some(PolicyPauseReason::SourceBitrateLimit),
353        |observed| observed > cap,
354    )
355}
356
357fn selector_bitrate(
358    route: &ReceiverVideoRouteInput<'_>,
359    selector: SourceSelector,
360) -> Option<Bitrate> {
361    let source = route.source;
362    let declared = selector.selected_encoding().map_or_else(
363        || {
364            source
365                .selectable_encodings()
366                .filter_map(SourceEncodingDescriptor::max_bitrate)
367                .max()
368        },
369        |encoding_id| {
370            source
371                .selectable_encodings()
372                .find(|encoding| encoding.encoding_id() == encoding_id)
373                .and_then(SourceEncodingDescriptor::max_bitrate)
374        },
375    );
376    // A per-media observation aggregates every RID. Use it only when policy has
377    // at most one selectable encoding and needs no per-RID estimate.
378    let observed = route
379        .source_bitrate
380        .filter(|_| source.selectable_encoding_count() <= 1);
381    declared.max(observed)
382}
383
384fn highest_allowed_plan(route: &ReceiverVideoRouteInput<'_>) -> Option<ReceiverRouteSelection> {
385    let target_selector = highest_allowed_selector(route)?;
386    Some(ReceiverRouteSelection::send(
387        target_selector,
388        target_selector != route.current.selector(),
389    ))
390}
391
392fn highest_allowed_selector(route: &ReceiverVideoRouteInput<'_>) -> Option<SourceSelector> {
393    let source_cap = route.source.policy().video_bitrate_cap();
394    if route.source.selectable_encoding_count() == 0 {
395        return source_cap
396            .is_none_or(|cap| route.source_bitrate.is_some_and(|rate| rate <= cap))
397            .then_some(SourceSelector::Open);
398    }
399    let target_index = allowed_encoding_indices(route.source, source_cap)
400        .next_back()
401        .or_else(|| {
402            (route.source.selectable_encoding_count() == 1
403                && source_cap
404                    .is_some_and(|cap| route.source_bitrate.is_some_and(|rate| rate <= cap)))
405            .then_some(0)
406        })?;
407    Some(SourceSelector::Encoding(
408        route
409            .source
410            .selectable_encoding_by_rank(target_index)?
411            .encoding_id(),
412    ))
413}
414
415/// Separates configured downlink headroom from audio consumption so receivers
416/// reserve audio only for admitted routes they can hear.
417fn effective_video_budget(
418    receiver_bandwidth: Bitrate,
419    tuning: VideoAdaptationTuning,
420    audio_reserve: Bitrate,
421) -> Bitrate {
422    let usable_percent = 100u64.saturating_sub(u64::from(tuning.receiver_budget_headroom_percent));
423    let after_overhead =
424        Bitrate::from_bps(receiver_bandwidth.as_bps().saturating_mul(usable_percent) / 100);
425    after_overhead.saturating_sub(audio_reserve)
426}
427
428/// Returns the next cheaper allowed encoding and its bitrate.
429///
430/// Routes using featured quality retain an intermediate rung during aggregate fitting.
431/// Their per-route target may still select the floor when the receiver cannot
432/// afford that intermediate quality. Equal bitrate ceilings do not create an
433/// intermediate operating point.
434fn step_down_selector(route: &PlannedReceiverRoute<'_>) -> Option<(SourceSelector, Bitrate)> {
435    let source = route.input.source;
436    let source_cap = source.policy().video_bitrate_cap();
437    let current_index = selector_index(source, route.selection.selector);
438    let mut cheaper_encodings = (0..current_index).rev().filter_map(|index| {
439        let encoding = source.selectable_encoding_by_rank(index)?;
440        let bitrate = encoding.max_bitrate()?;
441        (bitrate < route.selected_bitrate && source_cap.is_none_or(|cap| bitrate <= cap))
442            .then_some((SourceSelector::Encoding(encoding.encoding_id()), bitrate))
443    });
444    let (selector, bitrate) = cheaper_encodings.next()?;
445    if route.input.layout_role.uses_featured_quality()
446        && !cheaper_encodings.any(|(_selector, lower_bitrate)| lower_bitrate < bitrate)
447    {
448        return None;
449    }
450    Some((selector, bitrate))
451}
452
453fn scalable_plan(
454    route: &ReceiverVideoRouteInput<'_>,
455    tuning: VideoAdaptationTuning,
456) -> Option<ReceiverRouteSelection> {
457    let source_cap = route.source.policy().video_bitrate_cap();
458    if route.source.selectable_encoding_count() < 2 && source_cap.is_none() {
459        return None;
460    }
461    let current = route.current;
462    let target_index = desired_encoding_index(route, source_cap, tuning)?;
463    let target_selector = SourceSelector::Encoding(
464        route
465            .source
466            .selectable_encoding_by_rank(target_index)?
467            .encoding_id(),
468    );
469    Some(ReceiverRouteSelection::send(
470        target_selector,
471        target_selector != current.selector(),
472    ))
473}
474
475fn desired_encoding_index(
476    route: &ReceiverVideoRouteInput<'_>,
477    source_cap: Option<Bitrate>,
478    tuning: VideoAdaptationTuning,
479) -> Option<usize> {
480    if route.user_count < tuning.multiparty_scalable_video_threshold {
481        return allowed_encoding_indices(route.source, source_cap).next_back();
482    }
483    let uses_featured_quality = route.layout_role.uses_featured_quality();
484    let Some(receiver_bandwidth) = route.receiver_bandwidth else {
485        return if uses_featured_quality {
486            allowed_encoding_indices(route.source, source_cap).next_back()
487        } else {
488            allowed_encoding_indices(route.source, source_cap).next()
489        };
490    };
491    let receiver_bandwidth =
492        effective_video_budget(receiver_bandwidth, tuning, route.audio_budget_reserve);
493    let budget = if uses_featured_quality || route.visible_scalable_route_count <= 1 {
494        receiver_bandwidth
495    } else {
496        let divisor = u64::try_from(route.visible_scalable_route_count)
497            .unwrap_or(u64::MAX)
498            // Bias secondary routes toward thumbnail quality before aggregate overload handling.
499            .saturating_mul(tuning.thumbnail_budget_divisor);
500        receiver_bandwidth.divided_by(divisor)
501    };
502    highest_affordable_encoding_index(route.source, budget, uses_featured_quality, source_cap)
503}
504
505fn highest_affordable_encoding_index(
506    source: &PublishedSourceDescriptor,
507    budget: Bitrate,
508    uses_featured_quality: bool,
509    source_cap: Option<Bitrate>,
510) -> Option<usize> {
511    if source
512        .selectable_encodings()
513        .all(|encoding| encoding.max_bitrate().is_none())
514    {
515        return source_cap.is_none().then_some(if uses_featured_quality {
516            source.selectable_encoding_count().saturating_sub(1)
517        } else {
518            0
519        });
520    }
521    allowed_encoding_indices(source, source_cap)
522        .rev()
523        .find_or_last(|index| {
524            source
525                .selectable_encoding_by_rank(*index)
526                .and_then(SourceEncodingDescriptor::max_bitrate)
527                .is_some_and(|bitrate| bitrate <= budget)
528        })
529}
530
531fn selector_index(source: &PublishedSourceDescriptor, selector: SourceSelector) -> usize {
532    selector
533        .selected_encoding()
534        .and_then(|encoding_id| {
535            source
536                .selectable_encodings()
537                .position(|encoding| encoding.encoding_id() == encoding_id)
538        })
539        .unwrap_or_else(|| source.selectable_encoding_count().saturating_sub(1))
540}
541
542fn allowed_encoding_indices(
543    source: &PublishedSourceDescriptor,
544    source_cap: Option<Bitrate>,
545) -> impl DoubleEndedIterator<Item = usize> + '_ {
546    (0..source.selectable_encoding_count()).filter(move |index| {
547        source_cap.is_none_or(|source_cap| {
548            source
549                .selectable_encoding_by_rank(*index)
550                .and_then(SourceEncodingDescriptor::max_bitrate)
551                .is_some_and(|bitrate| bitrate <= source_cap)
552        })
553    })
554}
555
556/// enforces receiver download limits by pausing the lowest-ranked routes using top-k selection
557///
558/// ```text
559/// all active routes (N)
560///   [ R0: rank 2, R1: rank 5, R2: rank 1, R3: rank 8, R4: rank 4 ]
561///   limit = 3  ==>  routes_to_pause (K) = 5 - 3 = 2
562///                              |
563///                              v  .k_largest_by_key(K = 2)
564///   +-------------------------------------------------------------+
565///   | min-heap of size K=2:                                       |
566///   | retains only the 2 highest ranks: [ R1: rank 5, R3: rank 8 ]|
567///   +-------------------------------------------------------------+
568///                              |
569///                              v  .rev()
570///   route.pause(VideoDownloadLimit) applied only to [ R3, R1 ]
571/// ```
572fn apply_video_download_limit(
573    routes: &mut [PlannedReceiverRoute<'_>],
574    max_video_downloads_per_receiver: usize,
575) {
576    let routes_to_pause =
577        active_route_count(routes).saturating_sub(max_video_downloads_per_receiver);
578    if routes_to_pause == 0 {
579        return;
580    }
581    for (_rank_key, route) in routes
582        .iter_mut()
583        .filter(|route| route.selection.policy_pause_reason.is_none())
584        .enumerate()
585        .map(|(position, route)| ((video_download_rank(route), position), route))
586        .k_largest_by_key(routes_to_pause, |(rank_key, _route)| *rank_key)
587        .rev()
588    {
589        route.pause(PolicyPauseReason::VideoDownloadLimit);
590    }
591}
592
593fn active_route_count(routes: &[PlannedReceiverRoute<'_>]) -> usize {
594    routes
595        .iter()
596        .filter(|route| route.selection.policy_pause_reason.is_none())
597        .count()
598}
599
600fn video_download_rank(route: &PlannedReceiverRoute<'_>) -> VideoAdmissionRank {
601    let input = route.input;
602    VideoAdmissionRank::new(
603        input.layout_role.priority(),
604        input.active_speaker_rank,
605        input.source.source_id(),
606    )
607}
608
609fn apply_overload_policy(routes: &mut [PlannedReceiverRoute<'_>], video_budget: Bitrate) {
610    let mut total_bitrate = selected_active_video_bitrate(routes);
611    if total_bitrate <= video_budget {
612        return;
613    }
614    // Missing-layer pauses stay limited to secondary routes. Widening encoding
615    // downsteps must not bypass the soft-pause dwell for important fixed video.
616    let mut missing_ladders = routes
617        .iter_mut()
618        .filter(|route| route_needs_missing_layer_pause(route))
619        .map(|route| (video_download_rank(route), route))
620        .collect::<Vec<_>>();
621    missing_ladders.sort_by_key(|(rank, _route)| Reverse(*rank));
622    for (_rank, route) in missing_ladders {
623        if total_bitrate <= video_budget {
624            break;
625        }
626        let selected_bitrate = route.selected_bitrate;
627        route.pause(PolicyPauseReason::MissingUsableLayer);
628        total_bitrate = total_bitrate.saturating_sub(selected_bitrate);
629    }
630    // Step the least important downgradable route down one layer at a time.
631    // Preserve intermediate layers and stop as soon as aggregate demand fits.
632    while total_bitrate > video_budget {
633        let Some((route, selector, bitrate)) = routes
634            .iter_mut()
635            .filter(|route| route_can_downgrade(route))
636            .filter_map(|route| {
637                step_down_selector(route).map(|(selector, bitrate)| (route, selector, bitrate))
638            })
639            .max_by_key(|(route, _selector, _bitrate)| {
640                (video_download_rank(route), route.selected_bitrate)
641            })
642        else {
643            break;
644        };
645        let selected_bitrate = route.selected_bitrate;
646        total_bitrate = total_bitrate
647            .saturating_sub(selected_bitrate)
648            .saturating_add(bitrate);
649        route.send(selector, bitrate);
650    }
651    if total_bitrate <= video_budget {
652        return;
653    }
654    let mut pause_order = Vec::with_capacity(routes.len());
655    for route in routes.iter_mut() {
656        if route.selection.policy_pause_reason.is_some() {
657            continue;
658        }
659        pause_order.push((video_download_rank(route), route));
660    }
661    pause_order.sort_by_key(|(rank, _)| Reverse(*rank));
662    for (_rank, route) in pause_order {
663        if total_bitrate <= video_budget {
664            break;
665        }
666        let selected_bitrate = route.selected_bitrate;
667        let pause_reason = pause_reason_for_route(route);
668        route.pause(pause_reason);
669        total_bitrate = total_bitrate.saturating_sub(selected_bitrate);
670    }
671}
672
673fn receiver_video_budget_diagnostics(
674    routes: &[PlannedReceiverRoute<'_>],
675    receiver_bandwidth: Option<Bitrate>,
676    video_budget: Option<Bitrate>,
677) -> ReceiverVideoBudgetDiagnostics {
678    let selected_video_bitrate = selected_active_video_bitrate(routes);
679    ReceiverVideoBudgetDiagnostics {
680        latest_receiver_bandwidth: receiver_bandwidth,
681        selected_video_budget: video_budget,
682        active_video_route_count: active_route_count(routes),
683        selected_video_bitrate,
684    }
685}
686
687fn selected_active_video_bitrate(routes: &[PlannedReceiverRoute<'_>]) -> Bitrate {
688    routes
689        .iter()
690        .filter(|route| route.selection.policy_pause_reason.is_none())
691        .fold(Bitrate::zero(), |total, route| {
692            total.saturating_add(route.selected_bitrate)
693        })
694}
695
696fn admitted_video_bwe_demand(routes: &[PlannedReceiverRoute<'_>]) -> Bitrate {
697    routes
698        .iter()
699        .filter(|route| route.selection.policy_pause_reason.is_none())
700        .fold(Bitrate::zero(), |total, route| {
701            let route_demand = highest_allowed_selector(route.input)
702                .and_then(|selector| selector_bitrate(route.input, selector))
703                .unwrap_or(route.selected_bitrate);
704            total.saturating_add(route_demand.max(route.selected_bitrate))
705        })
706}
707
708fn route_can_downgrade(route: &PlannedReceiverRoute<'_>) -> bool {
709    route.selection.policy_pause_reason.is_none()
710        && route.input.source.policy().adaptation() == SourceAdaptationPolicy::ScalableVideo
711}
712
713fn route_needs_missing_layer_pause(route: &PlannedReceiverRoute<'_>) -> bool {
714    let input = route.input;
715    let source_cap = input.source.policy().video_bitrate_cap();
716    route_can_downgrade(route)
717        && !input.layout_role.uses_featured_quality()
718        && !input.source.selectable_encodings().any(|encoding| {
719            encoding
720                .max_bitrate()
721                .is_some_and(|bitrate| source_cap.is_none_or(|cap| bitrate <= cap))
722        })
723}
724
725fn pause_reason_for_route(route: &PlannedReceiverRoute<'_>) -> PolicyPauseReason {
726    let role = route.input.layout_role;
727    match role.priority() {
728        SourceRoutePriority::HiddenOrOverflow => match role {
729            SourceRoomPolicySelector::Hidden => PolicyPauseReason::HiddenTile,
730            SourceRoomPolicySelector::Overflow => PolicyPauseReason::OverflowTile,
731            _ => PolicyPauseReason::BudgetPressure,
732        },
733        _ => PolicyPauseReason::BudgetPressure,
734    }
735}
736
737const fn is_soft_pause(reason: PolicyPauseReason) -> bool {
738    matches!(
739        reason,
740        PolicyPauseReason::BudgetPressure
741            | PolicyPauseReason::HiddenTile
742            | PolicyPauseReason::OverflowTile
743    )
744}
745
746fn resolve_dwell(
747    route: &PlannedReceiverRoute<'_>,
748    tuning: VideoAdaptationTuning,
749    soft_pause_deadline: Option<Instant>,
750    now: Instant,
751) -> ReceiverRouteSelection {
752    let current = route.input.current;
753    let mut selection = route.selection;
754    if let Some(reason) = selection.policy_pause_reason {
755        if !is_soft_pause(reason)
756            || current.pause_reason().is_some()
757            || soft_pause_deadline.is_some_and(|deadline| deadline <= now)
758        {
759            return selection;
760        }
761        // Preserve a fitted downstep during grace. Rebuilding from `current`
762        // used to retain the expensive RID until the whole route paused.
763        if selection.selector != current.selector()
764            && selector_index(route.input.source, selection.selector)
765                > selector_index(route.input.source, current.selector())
766        {
767            selection.selector = current.selector();
768        }
769        selection.policy_pause_reason = None;
770        return selection;
771    }
772    let immediate = current.pause_reason() == Some(PolicyPauseReason::VideoDownloadLimit)
773        || (current.pause_reason().is_none()
774            && (selection.selector == current.selector()
775                || current.selector() == SourceSelector::Open
776                || selector_index(route.input.source, selection.selector)
777                    <= selector_index(route.input.source, current.selector())));
778    if immediate {
779        return selection;
780    }
781    // Resolve one exact target after aggregate fitting. A pre-fit upgrade that
782    // fitting reverses must not keep restarting its own eligibility deadline.
783    let pending = route
784        .input
785        .pending_upgrade
786        .filter(|pending| pending.selector == selection.selector)
787        .unwrap_or_else(|| PendingUpgrade {
788            selector: selection.selector,
789            deadline: now + tuning.upgrade_dwell,
790        });
791    if pending.deadline <= now {
792        selection.request_keyframe = true;
793        return selection;
794    }
795    ReceiverRouteSelection {
796        selector: current.selector(),
797        policy_pause_reason: current.pause_reason(),
798        pending_upgrade: Some(pending),
799        request_keyframe: false,
800    }
801}
802
803#[cfg(test)]
804#[path = "TESTS/solver.rs"]
805mod tests;