forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBb0eb8adIvan Molodetskikh3 months ago2857 commits

frame_clock.rs98 lines, 2.9 KiBHistoryRawDownload
1use std::num::NonZeroU64;
2use std::time::Duration;
3
4use crate::utils::get_monotonic_time;
5
6#[derive(Debug)]
7pub struct FrameClock {
8 last_presentation_time: Option<Duration>,
9 refresh_interval_ns: Option<NonZeroU64>,
10 vrr: bool,
11}
12
13impl FrameClock {
14 pub fn new(refresh_interval: Option<Duration>, vrr: bool) -> Self {
15 let refresh_interval_ns = if let Some(interval) = &refresh_interval {
16 assert_eq!(interval.as_secs(), 0);
17 Some(NonZeroU64::new(interval.subsec_nanos().into()).unwrap())
18 } else {
19 None
20 };
21
22 Self {
23 last_presentation_time: None,
24 refresh_interval_ns,
25 vrr,
26 }
27 }
28
29 pub fn refresh_interval(&self) -> Option<Duration> {
30 self.refresh_interval_ns
31 .map(|r| Duration::from_nanos(r.get()))
32 }
33
34 pub fn set_vrr(&mut self, vrr: bool) {
35 if self.vrr == vrr {
36 return;
37 }
38
39 self.vrr = vrr;
40 self.last_presentation_time = None;
41 }
42
43 pub fn vrr(&self) -> bool {
44 self.vrr
45 }
46
47 pub fn presented(&mut self, presentation_time: Duration) {
48 if presentation_time.is_zero() {
49 // Not interested in these.
50 return;
51 }
52
53 self.last_presentation_time = Some(presentation_time);
54 }
55
56 pub fn next_presentation_time(&self) -> Duration {
57 let mut now = get_monotonic_time();
58
59 let Some(refresh_interval_ns) = self.refresh_interval_ns else {
60 return now;
61 };
62 let Some(last_presentation_time) = self.last_presentation_time else {
63 return now;
64 };
65
66 let refresh_interval_ns = refresh_interval_ns.get();
67
68 if now <= last_presentation_time {
69 // Got an early VBlank.
70 let orig_now = now;
71 now += Duration::from_nanos(refresh_interval_ns);
72
73 if now < last_presentation_time {
74 // Not sure when this can happen.
75 error!(
76 now = ?orig_now,
77 ?last_presentation_time,
78 "got a 2+ early VBlank, {:?} until presentation",
79 last_presentation_time - now,
80 );
81 now = last_presentation_time + Duration::from_nanos(refresh_interval_ns);
82 }
83 }
84
85 let since_last = now - last_presentation_time;
86 let since_last_ns =
87 since_last.as_secs() * 1_000_000_000 + u64::from(since_last.subsec_nanos());
88 let to_next_ns = (since_last_ns / refresh_interval_ns + 1) * refresh_interval_ns;
89
90 // If VRR is enabled and more than one frame passed since last presentation, assume that we
91 // can present immediately.
92 if self.vrr && to_next_ns > refresh_interval_ns {
93 now
94 } else {
95 last_presentation_time + Duration::from_nanos(to_next_ns)
96 }
97 }
98}