Skip to main content

nativeview_engine/ext/
vsync.rs

1//! Pluggable vsync pacing seam ([`VsyncPacer`]) and zero-allocation portable pacers
2//! ([`TimerVsyncPacer`], [`ManualVsyncPacer`]).
3//!
4//! All timestamps and intervals use `u64` / `u32` microseconds so this module compiles cleanly on
5//! `wasm32-unknown-unknown` without `std::time::Instant`.
6//!
7//! Production consumers implementing [`VsyncPacer`] (`[INV:extension-point-has-consumers]`):
8//! - `packages/backends/skia-desktop` (`CADisplayLink`/`CVDisplayLink`, `DwmFlush`, Wayland `winit`, timer fallback)
9//! - `packages/backends/web-runtime` (`RafVsyncPacer` over `window.requestAnimationFrame`)
10
11use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
12use std::sync::Arc;
13
14/// Fallback display refresh rate when the OS/monitor does not report one (60 Hz = 60,000 mHz).
15pub const DEFAULT_REFRESH_RATE_MILLIHERTZ: u32 = 60_000;
16
17/// Minimum accepted refresh rate in millihertz (1 Hz); lower values clamp to
18/// [`DEFAULT_REFRESH_RATE_MILLIHERTZ`].
19pub const MIN_REFRESH_RATE_MILLIHERTZ: u32 = 1_000;
20
21/// Maximum accepted refresh rate in millihertz (1000 Hz); higher values clamp here so
22/// [`interval_us_from_millihertz`] is strictly `>= 1` microsecond.
23pub const MAX_REFRESH_RATE_MILLIHERTZ: u32 = 1_000_000;
24
25/// Clamps `millihertz` into a valid refresh rate (`< 1_000` -> `60_000`, `> 1_000_000` -> `1_000_000`).
26#[inline]
27pub const fn sanitize_refresh_rate_millihertz(millihertz: u32) -> u32 {
28    if millihertz < MIN_REFRESH_RATE_MILLIHERTZ {
29        DEFAULT_REFRESH_RATE_MILLIHERTZ
30    } else if millihertz > MAX_REFRESH_RATE_MILLIHERTZ {
31        MAX_REFRESH_RATE_MILLIHERTZ
32    } else {
33        millihertz
34    }
35}
36
37/// Converts a refresh rate in millihertz (e.g. `60_000` for 60 Hz, `120_000` for 120 Hz) into a
38/// nominal frame interval in microseconds (`16_666` us for 60 Hz, `8_333` us for 120 Hz),
39/// guaranteed strictly `>= 1`.
40#[inline]
41pub const fn interval_us_from_millihertz(millihertz: u32) -> u32 {
42    let mhz = sanitize_refresh_rate_millihertz(millihertz);
43    let us = (1_000_000_000u64 / (mhz as u64)) as u32;
44    if us == 0 { 1 } else { us }
45}
46
47/// Platform-pluggable vsync / frame pacing strategy.
48///
49/// Push-driven native pacers (`CADisplayLink`, `CVDisplayLink`, `DwmFlush`, browser
50/// `requestAnimationFrame`) return `None` from [`Self::next_deadline_us`] and deliver ticks via
51/// their platform event loop / wake callback while [`Self::is_active`] is `true`.
52///
53/// Timer / poll pacers (such as [`TimerVsyncPacer`]) return `Some(deadline_us)` from
54/// [`Self::next_deadline_us`] while active so the event loop can sleep until the next frame
55/// boundary (`ControlFlow::WaitUntil`) with 0% idle CPU.
56pub trait VsyncPacer: Send {
57    /// Starts (`true`) or pauses (`false`) frame delivery. Idle pacers MUST consume 0% CPU.
58    fn set_active(&mut self, active: bool);
59
60    /// Returns `true` while frame delivery is active.
61    fn is_active(&self) -> bool;
62
63    /// Acknowledges receipt of a delivered vsync tick so push-driven pacers can clear their
64    /// coalescing latch and emit the next frame tick.
65    fn on_tick_received(&self) {}
66
67    /// Nominal frame interval in microseconds if known (e.g. `8_333` for 120 Hz ProMotion).
68    fn nominal_interval_us(&self) -> Option<u32> {
69        None
70    }
71
72    /// Optional next wake deadline in microseconds (`now_us` clock) for timer/poll pacers.
73    /// Push-driven native pacers (`CADisplayLink`, `DwmFlush`, `rAF`) return `None`.
74    fn next_deadline_us(&self, _last_frame_us: Option<u64>, _now_us: u64) -> Option<u64> {
75        None
76    }
77}
78
79/// Portable, zero-allocation refresh-rate timer pacer computing `next_deadline_us` in
80/// microseconds for event loops that sleep via `WaitUntil`.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct TimerVsyncPacer {
83    millihertz: u32,
84    active: bool,
85}
86
87impl Default for TimerVsyncPacer {
88    #[inline]
89    fn default() -> Self {
90        Self::new(DEFAULT_REFRESH_RATE_MILLIHERTZ)
91    }
92}
93
94impl TimerVsyncPacer {
95    /// Creates a stopped timer pacer configured for `millihertz` (clamping `< 1_000` to `60_000`).
96    #[inline]
97    pub const fn new(millihertz: u32) -> Self {
98        Self {
99            millihertz: sanitize_refresh_rate_millihertz(millihertz),
100            active: false,
101        }
102    }
103
104    /// Returns the active refresh rate in millihertz.
105    #[inline]
106    pub const fn refresh_rate_millihertz(&self) -> u32 {
107        self.millihertz
108    }
109
110    /// Updates the configured refresh rate in millihertz (clamping `< 1_000` to `60_000`).
111    #[inline]
112    pub fn set_refresh_rate_millihertz(&mut self, millihertz: u32) {
113        self.millihertz = sanitize_refresh_rate_millihertz(millihertz);
114    }
115}
116
117impl VsyncPacer for TimerVsyncPacer {
118    #[inline]
119    fn set_active(&mut self, active: bool) {
120        self.active = active;
121    }
122
123    #[inline]
124    fn is_active(&self) -> bool {
125        self.active
126    }
127
128    #[inline]
129    fn nominal_interval_us(&self) -> Option<u32> {
130        Some(interval_us_from_millihertz(self.millihertz))
131    }
132
133    #[inline]
134    fn next_deadline_us(&self, last_frame_us: Option<u64>, now_us: u64) -> Option<u64> {
135        if !self.active {
136            return None;
137        }
138        let interval = u64::from(interval_us_from_millihertz(self.millihertz));
139        let target = match last_frame_us {
140            Some(prev) => {
141                // Clamp skewed/future `prev > now_us` back to `now_us` to avoid multi-second stalls.
142                let anchor = if prev > now_us { now_us } else { prev };
143                let next = anchor.saturating_add(interval);
144                if next > now_us { next } else { now_us }
145            }
146            None => now_us.saturating_add(interval),
147        };
148        Some(target)
149    }
150}
151
152struct ManualVsyncState {
153    active: AtomicBool,
154    tick_pending: AtomicBool,
155    active_transitions: AtomicU64,
156    ticks_triggered: AtomicU64,
157    ticks_received: AtomicU64,
158    nominal_interval_us: AtomicU32,
159    on_trigger: Option<Arc<dyn Fn() + Send + Sync>>,
160}
161
162impl ManualVsyncState {
163    #[inline]
164    fn ack_tick(&self) {
165        self.tick_pending.store(false, Ordering::Release);
166        self.ticks_received.fetch_add(1, Ordering::AcqRel);
167    }
168}
169
170/// Shared atomic control handle paired with [`ManualVsyncPacer`] for deterministic tests.
171///
172/// All steady-state operations are strictly atomic (`CountingAlloc == 0`).
173#[derive(Clone)]
174pub struct ManualVsyncHandle {
175    state: Arc<ManualVsyncState>,
176}
177
178impl std::fmt::Debug for ManualVsyncHandle {
179    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180        f.debug_struct("ManualVsyncHandle")
181            .field("active", &self.is_active())
182            .field("active_transitions", &self.active_transitions())
183            .field("ticks_triggered", &self.ticks_triggered())
184            .field("ticks_received", &self.ticks_received())
185            .field("tick_pending", &self.is_tick_pending())
186            .finish()
187    }
188}
189
190impl ManualVsyncHandle {
191    /// Returns whether the pacer is currently active.
192    #[inline]
193    pub fn is_active(&self) -> bool {
194        self.state.active.load(Ordering::Acquire)
195    }
196
197    /// Returns the number of `active` state transitions observed (`false -> true` or `true -> false`).
198    #[inline]
199    pub fn active_transitions(&self) -> u64 {
200        self.state.active_transitions.load(Ordering::Acquire)
201    }
202
203    /// Returns how many coalesced ticks have been triggered via [`Self::trigger_tick`].
204    #[inline]
205    pub fn ticks_triggered(&self) -> u64 {
206        self.state.ticks_triggered.load(Ordering::Acquire)
207    }
208
209    /// Returns how many ticks have been acknowledged via `on_tick_received`.
210    #[inline]
211    pub fn ticks_received(&self) -> u64 {
212        self.state.ticks_received.load(Ordering::Acquire)
213    }
214
215    /// Returns `true` when a triggered tick has not yet been acknowledged via `on_tick_received`.
216    #[inline]
217    pub fn is_tick_pending(&self) -> bool {
218        self.state.tick_pending.load(Ordering::Acquire)
219    }
220
221    /// Triggers one coalesced tick if the pacer is active and no tick is already in flight.
222    /// Returns `true` when a new tick was emitted.
223    #[inline]
224    pub fn trigger_tick(&self) -> bool {
225        if !self.state.active.load(Ordering::Acquire) {
226            return false;
227        }
228        if self
229            .state
230            .tick_pending
231            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
232            .is_err()
233        {
234            return false;
235        }
236        self.state.ticks_triggered.fetch_add(1, Ordering::AcqRel);
237        if let Some(cb) = &self.state.on_trigger {
238            cb();
239        }
240        true
241    }
242
243    /// Updates the reported nominal frame interval in microseconds (`None` or `Some(0)` clears it).
244    #[inline]
245    pub fn set_nominal_interval_us(&self, interval_us: Option<u32>) {
246        self.state
247            .nominal_interval_us
248            .store(interval_us.unwrap_or(0), Ordering::Release);
249    }
250
251    /// Acknowledges receipt of a tick directly through the handle (mirrors [`VsyncPacer::on_tick_received`]).
252    #[inline]
253    pub fn on_tick_received(&self) {
254        self.state.ack_tick();
255    }
256}
257
258/// Deterministic, zero-allocation push-driven [`VsyncPacer`] for unit and integration tests.
259pub struct ManualVsyncPacer {
260    state: Arc<ManualVsyncState>,
261}
262
263impl std::fmt::Debug for ManualVsyncPacer {
264    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
265        f.debug_struct("ManualVsyncPacer")
266            .field("active", &self.is_active())
267            .finish()
268    }
269}
270
271impl Default for ManualVsyncPacer {
272    fn default() -> Self {
273        Self::new().0
274    }
275}
276
277impl ManualVsyncPacer {
278    /// Creates a new inactive [`ManualVsyncPacer`] and its shared [`ManualVsyncHandle`].
279    pub fn new() -> (Self, ManualVsyncHandle) {
280        Self::with_on_trigger_opt(None)
281    }
282
283    /// Creates a new inactive [`ManualVsyncPacer`] whose [`ManualVsyncHandle::trigger_tick`]
284    /// invokes `on_trigger` whenever a coalesced tick is emitted.
285    pub fn with_on_trigger(on_trigger: Arc<dyn Fn() + Send + Sync>) -> (Self, ManualVsyncHandle) {
286        Self::with_on_trigger_opt(Some(on_trigger))
287    }
288
289    fn with_on_trigger_opt(
290        on_trigger: Option<Arc<dyn Fn() + Send + Sync>>,
291    ) -> (Self, ManualVsyncHandle) {
292        let state = Arc::new(ManualVsyncState {
293            active: AtomicBool::new(false),
294            tick_pending: AtomicBool::new(false),
295            active_transitions: AtomicU64::new(0),
296            ticks_triggered: AtomicU64::new(0),
297            ticks_received: AtomicU64::new(0),
298            nominal_interval_us: AtomicU32::new(0),
299            on_trigger,
300        });
301        (
302            Self {
303                state: Arc::clone(&state),
304            },
305            ManualVsyncHandle { state },
306        )
307    }
308
309    /// Clones a [`ManualVsyncHandle`] sharing this pacer's atomic state.
310    #[inline]
311    pub fn handle(&self) -> ManualVsyncHandle {
312        ManualVsyncHandle {
313            state: Arc::clone(&self.state),
314        }
315    }
316}
317
318impl VsyncPacer for ManualVsyncPacer {
319    #[inline]
320    fn set_active(&mut self, active: bool) {
321        let prev = self.state.active.swap(active, Ordering::AcqRel);
322        if prev != active {
323            self.state.active_transitions.fetch_add(1, Ordering::AcqRel);
324            self.state.tick_pending.store(false, Ordering::Release);
325        }
326    }
327
328    #[inline]
329    fn is_active(&self) -> bool {
330        self.state.active.load(Ordering::Acquire)
331    }
332
333    #[inline]
334    fn on_tick_received(&self) {
335        self.state.ack_tick();
336    }
337
338    #[inline]
339    fn nominal_interval_us(&self) -> Option<u32> {
340        let v = self.state.nominal_interval_us.load(Ordering::Acquire);
341        (v != 0).then_some(v)
342    }
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348
349    #[test]
350    fn timer_pacer_sanitizes_millihertz_and_clamps_overdue_deadlines() {
351        let mut pacer = TimerVsyncPacer::default();
352        assert_eq!(pacer.refresh_rate_millihertz(), 60_000);
353        assert_eq!(pacer.nominal_interval_us(), Some(16_666));
354        assert!(!pacer.is_active());
355        assert_eq!(pacer.next_deadline_us(None, 1_000), None);
356
357        pacer.set_refresh_rate_millihertz(0);
358        assert_eq!(pacer.refresh_rate_millihertz(), 60_000);
359        pacer.set_refresh_rate_millihertz(u32::MAX);
360        assert_eq!(pacer.refresh_rate_millihertz(), MAX_REFRESH_RATE_MILLIHERTZ);
361        assert!(interval_us_from_millihertz(u32::MAX) >= 1);
362        assert_eq!(pacer.nominal_interval_us(), Some(1_000));
363        pacer.set_refresh_rate_millihertz(999);
364        assert_eq!(pacer.refresh_rate_millihertz(), 60_000);
365        pacer.set_refresh_rate_millihertz(120_000);
366        assert_eq!(pacer.refresh_rate_millihertz(), 120_000);
367        assert_eq!(pacer.nominal_interval_us(), Some(8_333));
368
369        pacer.set_active(true);
370        assert!(pacer.is_active());
371        assert_eq!(pacer.next_deadline_us(None, 10_000), Some(18_333));
372        assert_eq!(pacer.next_deadline_us(Some(10_000), 12_000), Some(18_333));
373        // Overdue frame clamps to `now_us`.
374        assert_eq!(pacer.next_deadline_us(Some(10_000), 25_000), Some(25_000));
375
376        // Backward / skewed `last_frame_us > now_us` anchors to `now_us` cleanly.
377        assert_eq!(pacer.next_deadline_us(Some(999_999), 100_000), Some(108_333));
378        // Saturated `now_us == u64::MAX` never overflows or panics.
379        assert_eq!(pacer.next_deadline_us(None, u64::MAX), Some(u64::MAX));
380        assert_eq!(pacer.next_deadline_us(Some(u64::MAX), u64::MAX), Some(u64::MAX));
381
382        pacer.set_active(false);
383        assert_eq!(pacer.next_deadline_us(Some(10_000), 12_000), None);
384    }
385
386    #[test]
387    fn manual_pacer_set_active_clears_stale_tick_pending_on_both_transitions() {
388        let (mut pacer, handle) = ManualVsyncPacer::new();
389        pacer.set_active(true);
390        assert!(handle.trigger_tick());
391        assert!(handle.is_tick_pending());
392        pacer.set_active(false);
393        assert!(!handle.is_tick_pending());
394        // Simulate a stale pending latch before re-activating -> `set_active(true)` clears it.
395        pacer.state.tick_pending.store(true, Ordering::Release);
396        pacer.set_active(true);
397        assert!(!handle.is_tick_pending());
398        assert!(handle.trigger_tick());
399    }
400
401    #[test]
402    fn manual_pacer_coalesces_tracks_transitions_and_is_zero_alloc() {
403        let trigger_hits = Arc::new(AtomicU64::new(0));
404        let hits = Arc::clone(&trigger_hits);
405        let (mut pacer, handle) = ManualVsyncPacer::with_on_trigger(Arc::new(move || {
406            hits.fetch_add(1, Ordering::Relaxed);
407        }));
408
409        assert!(!pacer.is_active());
410        assert!(!handle.is_active());
411        assert_eq!(handle.active_transitions(), 0);
412        assert_eq!(pacer.nominal_interval_us(), None);
413        assert_eq!(pacer.next_deadline_us(None, 1_000), None);
414        assert!(!handle.trigger_tick(), "inactive pacer must not emit ticks");
415
416        handle.set_nominal_interval_us(Some(8_333));
417        assert_eq!(pacer.nominal_interval_us(), Some(8_333));
418
419        let (_, allocs) = nativeview_test_support::count_allocs(|| {
420            pacer.set_active(true);
421            pacer.set_active(true); // duplicate no-op
422            assert!(handle.is_active());
423            assert_eq!(handle.active_transitions(), 1);
424
425            assert!(handle.trigger_tick());
426            assert!(!handle.trigger_tick(), "in-flight tick must coalesce");
427            assert!(handle.is_tick_pending());
428            assert_eq!(handle.ticks_triggered(), 1);
429
430            pacer.on_tick_received();
431            assert!(!handle.is_tick_pending());
432            assert_eq!(handle.ticks_received(), 1);
433
434            assert!(handle.trigger_tick());
435            handle.on_tick_received();
436            assert_eq!(handle.ticks_triggered(), 2);
437            assert_eq!(handle.ticks_received(), 2);
438
439            pacer.set_active(false);
440            pacer.set_active(false); // duplicate no-op
441            assert!(!handle.is_active());
442            assert_eq!(handle.active_transitions(), 2);
443            assert!(!handle.trigger_tick());
444            handle.set_nominal_interval_us(None);
445            assert_eq!(pacer.nominal_interval_us(), None);
446        });
447
448        assert_eq!(allocs, 0, "ManualVsyncPacer steady-state ops must be 0-alloc");
449        assert_eq!(trigger_hits.load(Ordering::Relaxed), 2);
450    }
451}