Skip to main content

tilo_presentation/
clock.rs

1//! The platform's own clock readings, kept apart from relative `Instant` offsets.
2#[derive(Clone, Copy, Debug, PartialEq)]
3pub struct HostClockBracket {
4    pub lo_s: f64,
5    pub hi_s: f64,
6}
7
8pub const SUPPORTS_WAYLAND_TIMING: bool = cfg!(target_os = "linux");
9
10/// Whether this target's compositor can report presentation through Metal's
11/// observer (a build that also links that observer measures it).
12pub const SUPPORTS_METAL_TIMING: bool = cfg!(target_os = "macos");
13
14pub const CLOCK_NAME: &str = if cfg!(target_os = "macos") {
15    "mach_absolute_seconds"
16} else if cfg!(target_os = "linux") {
17    "clock_monotonic_seconds"
18} else {
19    "unavailable"
20};
21
22/// Called only under an explicit native diagnostic observer, not normal
23/// unprofiled input.
24pub fn sample<T>(instant: impl FnOnce() -> T) -> (T, Option<HostClockBracket>) {
25    sample_with(host_seconds, instant)
26}
27
28fn sample_with<T>(
29    mut host: impl FnMut() -> Option<f64>,
30    instant: impl FnOnce() -> T,
31) -> (T, Option<HostClockBracket>) {
32    let lo_s = host();
33    let instant = instant();
34    let hi_s = host();
35    (
36        instant,
37        lo_s.zip(hi_s)
38            .map(|(lo_s, hi_s)| HostClockBracket { lo_s, hi_s }),
39    )
40}
41
42#[allow(
43    clippy::unnecessary_wraps,
44    reason = "macOS and Linux both answer, so the Option is never empty here; \
45              the arm for a host this build cannot time is why it is one"
46)]
47fn host_seconds() -> Option<f64> {
48    #[cfg(target_os = "macos")]
49    {
50        Some(mach_seconds())
51    }
52    #[cfg(target_os = "linux")]
53    {
54        monotonic_seconds()
55    }
56    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
57    {
58        None
59    }
60}
61
62#[cfg(target_os = "linux")]
63fn monotonic_seconds() -> Option<f64> {
64    let mut time = libc::timespec {
65        tv_sec: 0,
66        tv_nsec: 0,
67    };
68    // SAFETY: the writable timespec outlives this parameterless clock read.
69    if unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &raw mut time) } != 0 {
70        return None;
71    }
72    let secs = u64::try_from(time.tv_sec).ok()?;
73    let nanos = u32::try_from(time.tv_nsec).ok()?;
74    if nanos >= 1_000_000_000 {
75        return None;
76    }
77    Some(std::time::Duration::new(secs, nanos).as_secs_f64())
78}
79
80#[cfg(target_os = "macos")]
81fn mach_seconds() -> f64 {
82    #[link(name = "QuartzCore", kind = "framework")]
83    unsafe extern "C" {
84        fn CACurrentMediaTime() -> f64;
85    }
86    // SAFETY: Apple's parameterless Core Animation clock API has no ownership
87    // or thread-affinity preconditions and returns CFTimeInterval (double).
88    unsafe { CACurrentMediaTime() }
89}
90
91#[cfg(test)]
92mod tests {
93    use super::*;
94    use std::cell::RefCell;
95
96    #[test]
97    fn host_clock_reads_bracket_in_order_and_report_invalid_or_unavailable() {
98        {
99            let calls = RefCell::new(Vec::new());
100            let expected = tilo_clock::now();
101            let mut times = [120.125, 120.25].into_iter();
102            let (instant, bracket) = sample_with(
103                || {
104                    calls.borrow_mut().push("host");
105                    Some(times.next().unwrap())
106                },
107                || {
108                    calls.borrow_mut().push("instant");
109                    expected
110                },
111            );
112            assert_eq!(*calls.borrow(), ["host", "instant", "host"]);
113            assert_eq!(instant, expected);
114            assert_eq!(
115                bracket.expect("clock readings"),
116                HostClockBracket {
117                    lo_s: 120.125,
118                    hi_s: 120.25
119                }
120            );
121            assert_eq!(times.next(), None);
122        }
123
124        {
125            for (lo, hi) in [(5.0, 4.0), (f64::INFINITY, 8.0), (0.0, 0.0)] {
126                let mut times = [lo, hi].into_iter();
127                let (stamp, bracket) = sample_with(|| Some(times.next().unwrap()), || 123);
128                assert_eq!(stamp, 123);
129                assert_eq!(
130                    bracket.expect("clock readings").lo_s.to_bits(),
131                    lo.to_bits()
132                );
133                assert_eq!(
134                    bracket.expect("clock readings").hi_s.to_bits(),
135                    hi.to_bits()
136                );
137            }
138        }
139
140        {
141            let before = tilo_clock::now();
142            let (instant, bracket) = sample(tilo_clock::now);
143            let after = tilo_clock::now();
144            assert!(before <= instant && instant <= after);
145            #[cfg(target_os = "macos")]
146            {
147                assert_eq!(CLOCK_NAME, "mach_absolute_seconds");
148                let bracket = bracket.expect("macOS provides the Metal host clock");
149                assert!(bracket.lo_s.is_finite() && bracket.lo_s > 0.0);
150                assert!(bracket.hi_s.is_finite() && bracket.hi_s >= bracket.lo_s);
151            }
152            #[cfg(target_os = "linux")]
153            {
154                assert_eq!(CLOCK_NAME, "clock_monotonic_seconds");
155                const { assert!(SUPPORTS_WAYLAND_TIMING) };
156                let bracket = bracket.expect("Linux CLOCK_MONOTONIC must be available");
157                assert!(bracket.lo_s.is_finite() && bracket.lo_s > 0.0);
158                assert!(bracket.hi_s.is_finite() && bracket.hi_s >= bracket.lo_s);
159            }
160            #[cfg(not(any(target_os = "macos", target_os = "linux")))]
161            {
162                assert_eq!(CLOCK_NAME, "unavailable");
163                assert!(bracket.is_none());
164            }
165        }
166    }
167}