BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / win_timer.rs

win_timer.rs

win_timer.rs 3.1 KiB Download Raw
1use std::time::{Duration, Instant};
2
3/// High-resolution frame pacer.
4///
5/// On Windows, `std::thread::sleep` is quantized to the 15.6 ms system timer tick,
6/// causing audio underruns at 10 ms and uneven 30 fps screen capture. A high-resolution
7/// waitable timer (`CREATE_WAITABLE_TIMER_HIGH_RESOLUTION`, Windows 10 1803+) wakes
8/// within ~0.5 ms without changing the global multimedia timer period.
9pub struct HighResSleep {
10 #[cfg(windows)]
11 handle: windows::Win32::Foundation::HANDLE,
12}
13
14#[cfg(windows)]
15unsafe impl Send for HighResSleep {}
16
17impl HighResSleep {
18 pub fn new() -> Self {
19 #[cfg(windows)]
20 {
21 use windows::Win32::Foundation::HANDLE;
22 use windows::Win32::System::Threading::{
23 CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, CreateWaitableTimerExW, TIMER_ALL_ACCESS,
24 };
25 let handle = unsafe {
26 CreateWaitableTimerExW(
27 None,
28 None,
29 CREATE_WAITABLE_TIMER_HIGH_RESOLUTION,
30 TIMER_ALL_ACCESS.0,
31 )
32 .or_else(|_| CreateWaitableTimerExW(None, None, 0, TIMER_ALL_ACCESS.0))
33 .unwrap_or_else(|_| HANDLE::default())
34 };
35 HighResSleep { handle }
36 }
37 #[cfg(not(windows))]
38 {
39 HighResSleep {}
40 }
41 }
42
43 pub fn sleep(&self, duration: Duration) {
44 if duration.is_zero() {
45 return;
46 }
47 #[cfg(windows)]
48 {
49 use windows::Win32::System::Threading::{
50 INFINITE, SetWaitableTimer, WaitForSingleObject,
51 };
52 if !self.handle.is_invalid() {
53 // Negative relative due time in 100-nanosecond intervals.
54 let ticks_100ns = (duration.as_nanos() / 100).max(1) as i64;
55 let due_time = -ticks_100ns;
56 let ok = unsafe { SetWaitableTimer(self.handle, &due_time, 0, None, None, false) };
57 if ok.is_ok() {
58 unsafe {
59 let _ = WaitForSingleObject(self.handle, INFINITE);
60 }
61 return;
62 }
63 }
64 }
65 std::thread::sleep(duration);
66 }
67
68 pub fn sleep_until(&self, deadline: Instant) {
69 let now = Instant::now();
70 if deadline > now {
71 self.sleep(deadline - now);
72 }
73 }
74}
75
76impl Default for HighResSleep {
77 fn default() -> Self {
78 Self::new()
79 }
80}
81
82#[cfg(windows)]
83impl Drop for HighResSleep {
84 fn drop(&mut self) {
85 use windows::Win32::Foundation::{CloseHandle, HANDLE};
86 if !self.handle.is_invalid() {
87 unsafe {
88 let _ = CloseHandle(self.handle);
89 }
90 self.handle = HANDLE::default();
91 }
92 }
93}
94
95#[cfg(test)]
96mod tests {
97 use super::*;
98
99 #[test]
100 fn high_res_sleep_waits_for_a_short_interval() {
101 let sleeper = HighResSleep::new();
102 let started = Instant::now();
103 sleeper.sleep(Duration::from_millis(5));
104 assert!(started.elapsed() >= Duration::from_millis(3));
105 }
106}