Skip to main content

cranpose_app_shell/
fps_monitor.rs

1use std::collections::VecDeque;
2
3use cranpose_ui_graphics::shared_sort;
4use web_time::Instant;
5
6const FRAME_HISTORY_SIZE: usize = 60;
7const EVENT_DRIVEN_IDLE_GAP_MS: f32 = 50.0;
8
9fn recomposition_diag_enabled() -> bool {
10    cranpose_core::DIAGNOSTICS.recomp_diag.is_set()
11}
12
13fn recomposition_diagnostic_line(rate: u64, frames_per_second: f32, total: u64) -> String {
14    format!("[recomp] {rate}/s frames={frames_per_second:.1}/s total={total}")
15}
16
17#[derive(Debug)]
18pub(crate) struct FpsMonitor {
19    tracker: FpsTracker,
20    recomposition_count: u64,
21    recomposition_reset_baseline: u64,
22}
23
24impl FpsMonitor {
25    pub(crate) fn new() -> Self {
26        Self {
27            tracker: FpsTracker::new(),
28            recomposition_count: 0,
29            recomposition_reset_baseline: 0,
30        }
31    }
32
33    #[cfg(test)]
34    pub(crate) fn record_frame(&mut self) {
35        self.tracker.record_frame(self.recomposition_count);
36    }
37
38    pub(crate) fn record_frame_work(
39        &mut self,
40        frame_started_at: Instant,
41        frame_finished_at: Instant,
42    ) {
43        self.tracker.record_frame_work(
44            frame_started_at,
45            frame_finished_at,
46            self.recomposition_count,
47        );
48    }
49
50    pub(crate) fn record_recomposition(&mut self) {
51        self.recomposition_count = self.recomposition_count.saturating_add(1);
52    }
53
54    pub(crate) fn reset_stats(&mut self) {
55        self.tracker.reset(self.recomposition_count);
56        self.recomposition_reset_baseline = self.recomposition_count;
57    }
58
59    pub(crate) fn current_fps(&self) -> f32 {
60        self.tracker.fps()
61    }
62
63    pub(crate) fn stats(&self) -> FpsStats {
64        self.tracker.stats(
65            self.recomposition_count
66                .saturating_sub(self.recomposition_reset_baseline),
67        )
68    }
69}
70
71impl Default for FpsMonitor {
72    fn default() -> Self {
73        Self::new()
74    }
75}
76
77#[derive(Debug)]
78struct FpsTracker {
79    frame_times: VecDeque<Instant>,
80    frame_intervals_ms: VecDeque<f32>,
81    frame_work_ms: VecDeque<f32>,
82    frame_count: u64,
83    last_recomp_count: u64,
84    recomps_per_second: u64,
85    last_recomp_calc: Instant,
86}
87
88impl FpsTracker {
89    fn new() -> Self {
90        Self {
91            frame_times: VecDeque::with_capacity(FRAME_HISTORY_SIZE + 1),
92            frame_intervals_ms: VecDeque::with_capacity(FRAME_HISTORY_SIZE),
93            frame_work_ms: VecDeque::with_capacity(FRAME_HISTORY_SIZE),
94            frame_count: 0,
95            last_recomp_count: 0,
96            recomps_per_second: 0,
97            last_recomp_calc: Instant::now(),
98        }
99    }
100
101    #[cfg(test)]
102    fn record_frame(&mut self, recomposition_count: u64) {
103        let now = Instant::now();
104        self.record_frame_work(now, now, recomposition_count);
105    }
106
107    #[cfg(test)]
108    fn record_frame_at(&mut self, now: Instant, recomposition_count: u64) {
109        self.record_frame_work(now, now, recomposition_count);
110    }
111
112    fn reset(&mut self, recomposition_count: u64) {
113        self.frame_times.clear();
114        self.frame_intervals_ms.clear();
115        self.frame_work_ms.clear();
116        self.frame_count = 0;
117        self.last_recomp_count = recomposition_count;
118        self.recomps_per_second = 0;
119        self.last_recomp_calc = Instant::now();
120    }
121
122    fn record_frame_work(
123        &mut self,
124        frame_started_at: Instant,
125        frame_finished_at: Instant,
126        recomposition_count: u64,
127    ) {
128        if let Some(previous) = self.frame_times.back() {
129            let interval_ms = frame_started_at.duration_since(*previous).as_secs_f32() * 1000.0;
130            if interval_ms <= EVENT_DRIVEN_IDLE_GAP_MS {
131                self.frame_intervals_ms.push_back(interval_ms);
132                while self.frame_intervals_ms.len() > FRAME_HISTORY_SIZE {
133                    self.frame_intervals_ms.pop_front();
134                }
135            }
136        }
137
138        let work_ms = frame_finished_at
139            .duration_since(frame_started_at)
140            .as_secs_f32()
141            * 1000.0;
142        self.frame_work_ms.push_back(work_ms);
143        while self.frame_work_ms.len() > FRAME_HISTORY_SIZE {
144            self.frame_work_ms.pop_front();
145        }
146
147        self.frame_times.push_back(frame_started_at);
148        self.frame_count += 1;
149
150        while self.frame_times.len() > FRAME_HISTORY_SIZE + 1 {
151            self.frame_times.pop_front();
152        }
153
154        let elapsed = frame_finished_at
155            .duration_since(self.last_recomp_calc)
156            .as_secs_f32();
157        if elapsed >= 1.0 {
158            self.recomps_per_second = recomposition_count.saturating_sub(self.last_recomp_count);
159            self.last_recomp_count = recomposition_count;
160            self.last_recomp_calc = frame_finished_at;
161            if recomposition_diag_enabled() {
162                log::info!(
163                    target: "cranpose::recomposition",
164                    "{}",
165                    recomposition_diagnostic_line(
166                        self.recomps_per_second,
167                        self.fps(),
168                        recomposition_count,
169                    )
170                );
171            }
172        }
173    }
174
175    // Frames a second over the intervals in the history.
176    fn fps(&self) -> f32 {
177        let count = self.frame_intervals_ms.len();
178        if count == 0 {
179            return 0.0;
180        }
181        let sum = self
182            .frame_intervals_ms
183            .iter()
184            .fold(0.0f32, |sum, &ms| sum + ms);
185        fps_from_avg_ms(sum / count as f32)
186    }
187
188    // The statistics of the history, worked out when read rather than at
189    // each frame.
190    fn stats(&self, recomposition_count: u64) -> FpsStats {
191        let intervals = FrameIntervalStats::from_samples(&self.frame_intervals_ms);
192        let work = FrameIntervalStats::from_samples(&self.frame_work_ms);
193        FpsStats {
194            fps: fps_from_avg_ms(intervals.avg_ms),
195            avg_ms: intervals.avg_ms,
196            latest_ms: intervals.latest_ms,
197            min_ms: intervals.min_ms,
198            max_ms: intervals.max_ms,
199            p95_ms: intervals.p95_ms,
200            p99_ms: intervals.p99_ms,
201            work_fps: fps_from_avg_ms(work.avg_ms),
202            work_avg_ms: work.avg_ms,
203            work_p95_ms: work.p95_ms,
204            work_max_ms: work.max_ms,
205            work_missed_120hz_budget: work.missed_120hz_budget,
206            work_missed_60hz_budget: work.missed_60hz_budget,
207            work_stalled_50ms_frames: work.stalled_50ms_frames,
208            interval_count: intervals.count,
209            missed_120hz_budget: intervals.missed_120hz_budget,
210            missed_60hz_budget: intervals.missed_60hz_budget,
211            stalled_50ms_frames: intervals.stalled_50ms_frames,
212            frame_count: self.frame_count,
213            recompositions: recomposition_count,
214            recomps_per_second: self.recomps_per_second,
215        }
216    }
217}
218
219#[derive(Clone, Copy, Debug, Default)]
220struct FrameIntervalStats {
221    count: u32,
222    latest_ms: f32,
223    avg_ms: f32,
224    min_ms: f32,
225    max_ms: f32,
226    p95_ms: f32,
227    p99_ms: f32,
228    missed_120hz_budget: u32,
229    missed_60hz_budget: u32,
230    stalled_50ms_frames: u32,
231}
232
233impl FrameIntervalStats {
234    const FRAME_120HZ_MS: f32 = 1000.0 / 120.0;
235    const FRAME_60HZ_MS: f32 = 1000.0 / 60.0;
236    const STALL_MS: f32 = 50.0;
237
238    fn from_samples(samples: &VecDeque<f32>) -> Self {
239        let count = samples.len();
240        if count == 0 {
241            return Self::default();
242        }
243
244        let mut sorted = [0.0f32; FRAME_HISTORY_SIZE];
245        let mut sum = 0.0f32;
246        let mut min_ms = f32::INFINITY;
247        let mut max_ms = 0.0f32;
248        let mut missed_120hz_budget = 0u32;
249        let mut missed_60hz_budget = 0u32;
250        let mut stalled_50ms_frames = 0u32;
251
252        for (index, interval_ms) in samples.iter().copied().enumerate() {
253            sorted[index] = interval_ms;
254            sum += interval_ms;
255            min_ms = min_ms.min(interval_ms);
256            max_ms = max_ms.max(interval_ms);
257            if interval_ms > Self::FRAME_120HZ_MS {
258                missed_120hz_budget = missed_120hz_budget.saturating_add(1);
259            }
260            if interval_ms > Self::FRAME_60HZ_MS {
261                missed_60hz_budget = missed_60hz_budget.saturating_add(1);
262            }
263            if interval_ms > Self::STALL_MS {
264                stalled_50ms_frames = stalled_50ms_frames.saturating_add(1);
265            }
266        }
267
268        let sorted = &mut sorted[..count];
269        shared_sort::sort_by(sorted, f32::total_cmp);
270
271        Self {
272            count: count as u32,
273            latest_ms: samples.back().copied().unwrap_or_default(),
274            avg_ms: sum / count as f32,
275            min_ms,
276            max_ms,
277            p95_ms: nearest_rank_percentile(sorted, 95),
278            p99_ms: nearest_rank_percentile(sorted, 99),
279            missed_120hz_budget,
280            missed_60hz_budget,
281            stalled_50ms_frames,
282        }
283    }
284}
285
286fn fps_from_avg_ms(avg_ms: f32) -> f32 {
287    if avg_ms > 0.0 { 1000.0 / avg_ms } else { 0.0 }
288}
289
290fn nearest_rank_percentile(sorted_samples: &[f32], percentile: usize) -> f32 {
291    if sorted_samples.is_empty() {
292        return 0.0;
293    }
294    let rank = sorted_samples
295        .len()
296        .saturating_mul(percentile)
297        .div_ceil(100)
298        .saturating_sub(1);
299    sorted_samples[rank.min(sorted_samples.len() - 1)]
300}
301
302/// Frame statistics snapshot.
303#[derive(Clone, Copy, Debug, Default)]
304pub struct FpsStats {
305    /// Current presented-frame cadence in frames per second.
306    pub fps: f32,
307    /// Average presented-frame interval in milliseconds.
308    pub avg_ms: f32,
309    /// Last recorded frame interval in milliseconds.
310    pub latest_ms: f32,
311    /// Minimum frame interval in the rolling history.
312    pub min_ms: f32,
313    /// Maximum frame interval in the rolling history.
314    pub max_ms: f32,
315    /// 95th percentile frame interval in the rolling history.
316    pub p95_ms: f32,
317    /// 99th percentile frame interval in the rolling history.
318    pub p99_ms: f32,
319    /// AppShell work capacity in frames per second.
320    pub work_fps: f32,
321    /// Average measured AppShell frame work in milliseconds.
322    pub work_avg_ms: f32,
323    /// 95th percentile measured AppShell frame work in milliseconds.
324    pub work_p95_ms: f32,
325    /// Maximum measured AppShell frame work in milliseconds.
326    pub work_max_ms: f32,
327    /// Rolling count of measured AppShell work samples above the 120 Hz frame budget.
328    pub work_missed_120hz_budget: u32,
329    /// Rolling count of measured AppShell work samples above the 60 Hz frame budget.
330    pub work_missed_60hz_budget: u32,
331    /// Rolling count of measured AppShell work samples above 50 ms.
332    pub work_stalled_50ms_frames: u32,
333    /// Number of frame intervals in the rolling history.
334    pub interval_count: u32,
335    /// Rolling count of intervals above the 120 Hz frame budget.
336    pub missed_120hz_budget: u32,
337    /// Rolling count of intervals above the 60 Hz frame budget.
338    pub missed_60hz_budget: u32,
339    /// Rolling count of intervals above 50 ms.
340    pub stalled_50ms_frames: u32,
341    /// Total frame count since monitor creation.
342    pub frame_count: u64,
343    /// Recomposition count since the last stats reset.
344    pub recompositions: u64,
345    /// Recompositions in the last second.
346    pub recomps_per_second: u64,
347}
348
349#[cfg(test)]
350#[path = "tests/fps_monitor_tests.rs"]
351mod tests;