forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9d8f4f8Ivan Molodetskikh1 month ago2997 commits

vblank_throttle.rs71 lines, 2.2 KiBHistoryRawDownload
1//! VBlank throttling.
2//!
3//! Some buggy drivers deliver VBlanks way earlier than necessary. This helper throttles the VBlank
4//! in such cases to avoid tearing and to get more consistent timings.
5
6use std::time::Duration;
7
8use calloop::timer::{TimeoutAction, Timer};
9use calloop::{LoopHandle, RegistrationToken};
10
11use crate::niri::State;
12
13#[derive(Debug)]
14pub struct VBlankThrottle {
15 event_loop: LoopHandle<'static, State>,
16 last_vblank_timestamp: Option<Duration>,
17 throttle_timer_token: Option<RegistrationToken>,
18 printed_warning: bool,
19 output_name: String,
20}
21
22impl VBlankThrottle {
23 pub fn new(event_loop: LoopHandle<'static, State>, output_name: String) -> Self {
24 Self {
25 event_loop,
26 last_vblank_timestamp: None,
27 throttle_timer_token: None,
28 printed_warning: false,
29 output_name,
30 }
31 }
32
33 pub fn throttle(
34 &mut self,
35 refresh_interval: Option<Duration>,
36 timestamp: Duration,
37 mut call_vblank: impl FnMut(&mut State) + 'static,
38 ) -> bool {
39 if let Some(token) = self.throttle_timer_token.take() {
40 self.event_loop.remove(token);
41 }
42
43 if let Some((last, refresh)) = Option::zip(self.last_vblank_timestamp, refresh_interval) {
44 let passed = timestamp.saturating_sub(last);
45 if passed < refresh / 2 {
46 if !self.printed_warning {
47 self.printed_warning = true;
48 warn!(
49 "output {} running faster than expected, throttling vblanks: \
50 expected refresh {refresh:?}, got vblank after {passed:?}",
51 self.output_name
52 );
53 }
54
55 let remaining = refresh - passed;
56 let token = self
57 .event_loop
58 .insert_source(Timer::from_duration(remaining), move |_, _, state| {
59 call_vblank(state);
60 TimeoutAction::Drop
61 })
62 .unwrap();
63 self.throttle_timer_token = Some(token);
64 return true;
65 }
66 }
67
68 self.last_vblank_timestamp = Some(timestamp);
69 false
70 }
71}