Skip to main content

alpha2_host_core/export/
budget.rs

1//! The byte budget of decoded source frames, which the host may lower while work runs, as an app
2//! does when the system warns it of memory pressure.
3
4use std::sync::Arc;
5use std::sync::atomic::{AtomicU64, Ordering};
6
7use alpha2_os::MemoryCapacity;
8
9/// Fewest bytes a budget halves to. A cache following the budget keeps at least its last frame's
10/// working set on top of this ([`super::SourceFrameCache::follow`]), so the floor only bounds
11/// how much a run of memory warnings can take, not what a frame of any size needs.
12pub const MIN_FRAME_BYTES: u64 = 32 << 20;
13
14/// A shared byte budget for one export, still run or preview. Clones see the same budget; the
15/// work reads it before every frame and evicts to fit.
16#[derive(Clone, Debug)]
17pub struct FrameBudget(Arc<AtomicU64>);
18
19impl FrameBudget {
20    /// A budget of `bytes`, never below [`MIN_FRAME_BYTES`].
21    #[must_use]
22    pub fn new(bytes: u64) -> Self {
23        Self(Arc::new(AtomicU64::new(bytes.max(MIN_FRAME_BYTES))))
24    }
25
26    /// A quarter of the memory `capacity` leaves this process, at most `ceiling`. Without a
27    /// figure for it, `ceiling`.
28    #[must_use]
29    pub fn of_memory(capacity: &MemoryCapacity, ceiling: u64) -> Self {
30        Self::new(
31            capacity
32                .headroom()
33                .map_or(ceiling, |free| (free / 4).min(ceiling)),
34        )
35    }
36
37    /// The budget now.
38    #[must_use]
39    pub fn bytes(&self) -> u64 {
40        self.0.load(Ordering::Acquire)
41    }
42
43    /// Halves the budget, down to [`MIN_FRAME_BYTES`].
44    pub fn halve(&self) {
45        let _ = self
46            .0
47            .try_update(Ordering::AcqRel, Ordering::Acquire, |bytes| {
48                Some((bytes / 2).max(MIN_FRAME_BYTES))
49            });
50    }
51
52    /// Whether work other than this handle still holds the budget.
53    #[must_use]
54    pub fn is_shared(&self) -> bool {
55        Arc::strong_count(&self.0) > 1
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    use super::{FrameBudget, MIN_FRAME_BYTES};
62    use alpha2_os::MemoryCapacity;
63
64    #[test]
65    fn a_budget_takes_a_quarter_of_the_headroom_up_to_its_ceiling_and_halves_to_the_floor() {
66        let capacity = MemoryCapacity {
67            available_bytes: Some(1 << 30),
68            ..MemoryCapacity::default()
69        };
70        assert_eq!(
71            FrameBudget::of_memory(&capacity, 1 << 30).bytes(),
72            256 << 20
73        );
74        assert_eq!(
75            FrameBudget::of_memory(&capacity, 64 << 20).bytes(),
76            64 << 20
77        );
78        let unknown = FrameBudget::of_memory(&MemoryCapacity::default(), 512 << 20);
79        assert_eq!(unknown.bytes(), 512 << 20);
80        let shared = unknown.clone();
81        assert!(unknown.is_shared());
82        for _ in 0..8 {
83            shared.halve();
84        }
85        assert_eq!(unknown.bytes(), MIN_FRAME_BYTES);
86        drop(shared);
87        assert!(!unknown.is_shared());
88        assert_eq!(FrameBudget::new(0).bytes(), MIN_FRAME_BYTES);
89    }
90}