1use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
12use std::sync::Arc;
13
14pub const DEFAULT_REFRESH_RATE_MILLIHERTZ: u32 = 60_000;
16
17pub const MIN_REFRESH_RATE_MILLIHERTZ: u32 = 1_000;
20
21pub const MAX_REFRESH_RATE_MILLIHERTZ: u32 = 1_000_000;
24
25#[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#[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
47pub trait VsyncPacer: Send {
57 fn set_active(&mut self, active: bool);
59
60 fn is_active(&self) -> bool;
62
63 fn on_tick_received(&self) {}
66
67 fn nominal_interval_us(&self) -> Option<u32> {
69 None
70 }
71
72 fn next_deadline_us(&self, _last_frame_us: Option<u64>, _now_us: u64) -> Option<u64> {
75 None
76 }
77}
78
79#[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 #[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 #[inline]
106 pub const fn refresh_rate_millihertz(&self) -> u32 {
107 self.millihertz
108 }
109
110 #[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 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#[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 #[inline]
193 pub fn is_active(&self) -> bool {
194 self.state.active.load(Ordering::Acquire)
195 }
196
197 #[inline]
199 pub fn active_transitions(&self) -> u64 {
200 self.state.active_transitions.load(Ordering::Acquire)
201 }
202
203 #[inline]
205 pub fn ticks_triggered(&self) -> u64 {
206 self.state.ticks_triggered.load(Ordering::Acquire)
207 }
208
209 #[inline]
211 pub fn ticks_received(&self) -> u64 {
212 self.state.ticks_received.load(Ordering::Acquire)
213 }
214
215 #[inline]
217 pub fn is_tick_pending(&self) -> bool {
218 self.state.tick_pending.load(Ordering::Acquire)
219 }
220
221 #[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 #[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 #[inline]
253 pub fn on_tick_received(&self) {
254 self.state.ack_tick();
255 }
256}
257
258pub 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 pub fn new() -> (Self, ManualVsyncHandle) {
280 Self::with_on_trigger_opt(None)
281 }
282
283 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 #[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 assert_eq!(pacer.next_deadline_us(Some(10_000), 25_000), Some(25_000));
375
376 assert_eq!(pacer.next_deadline_us(Some(999_999), 100_000), Some(108_333));
378 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 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); 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); 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}