frame.rs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. //! Frame pacing: the title sets a frame interval and waits for each frame
  2. //! to begin. Ours is a clock started by the first interval set, ticking
  3. //! once per interval; the token is the frame number. Each event kind
  4. //! (origin, vblank, flip) happens once per tick, so two waits for the same
  5. //! kind never end on the same tick: the title polls the origin
  6. //! with "token on time-out" (starting its next frame at once) and is paced
  7. //! by a blocking wait for the flip before each present.
  8. //!
  9. //! shortcut: event offsets are ignored (every event is at the tick); tie
  10. //! the clock to presentation if a title paces by them.
  11. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  12. use std::sync::Mutex;
  13. use std::sync::atomic::{AtomicU64, Ordering};
  14. use std::time::{Duration, Instant};
  15. use crate::object::{HRESULT, S_FALSE, S_OK, This};
  16. /// What a wait returns when its time is up first.
  17. const TIMEOUT: HRESULT = S_FALSE;
  18. /// The frame-origin event: the one that starts frames and makes tokens.
  19. const ORIGIN: u32 = 0;
  20. /// Make the frame's token even if the wait times out (the title starts the
  21. /// frame early).
  22. const TOKEN_ON_TIMEOUT: u32 = 2;
  23. const SIXTIETH: Duration = Duration::from_micros(16_667);
  24. struct Clock {
  25. start: Instant,
  26. interval: Duration,
  27. /// The tick number at `start` (ticks go on across interval changes).
  28. first: u64,
  29. }
  30. static CLOCK: Mutex<Option<Clock>> = Mutex::new(None);
  31. static FRAME: AtomicU64 = AtomicU64::new(0);
  32. fn clock() -> std::sync::MutexGuard<'static, Option<Clock>> {
  33. CLOCK.lock().unwrap_or_else(|e| e.into_inner())
  34. }
  35. /// Device method: a frame every `length` microseconds. The period is how
  36. /// many intervals a frame may take to reach the display (pipeline depth),
  37. /// not part of the rate.
  38. pub(crate) extern "system" fn set_interval(
  39. _: This,
  40. _output: This,
  41. length: u32,
  42. _period: u32,
  43. _flags: u32,
  44. ) -> HRESULT {
  45. let interval = match length {
  46. 0 => SIXTIETH,
  47. us => Duration::from_micros(u64::from(us)),
  48. };
  49. tracing::info!(?interval, "frame interval");
  50. // A new interval starts from now, after the last tick handed out.
  51. let first = LAST
  52. .iter()
  53. .map(|t| t.load(Ordering::Relaxed))
  54. .max()
  55. .unwrap_or(0);
  56. *clock() = Some(Clock {
  57. start: Instant::now(),
  58. interval,
  59. first,
  60. });
  61. S_OK
  62. }
  63. /// Device method: events are scheduled at every tick.
  64. pub(crate) extern "system" fn schedule(
  65. _: This,
  66. _kind: u32,
  67. _offset: u32,
  68. _list: *const u8,
  69. _flags: u32,
  70. ) -> HRESULT {
  71. S_OK
  72. }
  73. /// Frames begun so far (frame waits that ended).
  74. pub(crate) fn current() -> u64 {
  75. FRAME.load(Ordering::Relaxed)
  76. }
  77. /// For tests of what is done once a frame.
  78. #[cfg(test)]
  79. pub(crate) fn test_advance() {
  80. FRAME.fetch_add(1, Ordering::Relaxed);
  81. }
  82. /// Per event kind (origin, vblank, flip and later kinds): the last tick a
  83. /// wait for it ended on.
  84. static LAST: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
  85. fn last(kind: u32) -> &'static AtomicU64 {
  86. &LAST[(kind as usize).min(LAST.len() - 1)]
  87. }
  88. /// The next tick after now and after the last one a wait for `kind` ended
  89. /// on (an event happens once per tick: a wait woken a little early must not
  90. /// let the next one end on the same tick), and how long until it.
  91. fn next_tick(kind: u32) -> (u64, Duration) {
  92. let mut clock = clock();
  93. let c = clock.get_or_insert_with(|| Clock {
  94. start: Instant::now(),
  95. interval: SIXTIETH,
  96. first: 0,
  97. });
  98. let elapsed = c.start.elapsed().as_nanos();
  99. let interval = c.interval.as_nanos().max(1);
  100. let tick =
  101. (c.first + (elapsed / interval + 1) as u64).max(last(kind).load(Ordering::Relaxed) + 1);
  102. let at = u128::from(tick - c.first) * interval;
  103. (
  104. tick,
  105. Duration::from_nanos(at.saturating_sub(elapsed) as u64),
  106. )
  107. }
  108. /// Device method: blocks until the next tick (or the time-out); an origin
  109. /// wait then hands out the new frame's token. Other events keep the token
  110. /// the title passes. Ticks are absolute (start plus whole intervals), so
  111. /// lateness never accumulates.
  112. pub(crate) extern "system" fn wait(
  113. _: This,
  114. kind: u32,
  115. timeout_ms: u32,
  116. _list: *const u8,
  117. flags: u32,
  118. token: *mut u64,
  119. ) -> HRESULT {
  120. let origin = kind == ORIGIN;
  121. let (mut tick, mut wait) = next_tick(kind);
  122. let limit = Duration::from_millis(u64::from(timeout_ms));
  123. // A blocking wait for an event that has happened since the last wait
  124. // for it ended (a frame took longer than a tick) ends at once, on the
  125. // tick that passed: sleeping on to the next one cost 17 ms of every
  126. // 730 ms frame (run 58: "2.0 frame waits sleeping 16.8 ms"). Polls (a
  127. // time-out shorter than a tick) answer as before.
  128. // `VICTORY_LATE_WAITS=1` sleeps to the next tick, as before.
  129. static SLEEP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  130. if !*SLEEP.get_or_init(|| std::env::var_os("VICTORY_LATE_WAITS").is_some_and(|v| v == "1"))
  131. && limit >= wait
  132. && tick > last(kind).load(Ordering::Relaxed) + 1
  133. {
  134. tick -= 1;
  135. wait = Duration::ZERO;
  136. }
  137. let hr = if wait > limit {
  138. std::thread::sleep(limit);
  139. TIMEOUT
  140. } else {
  141. std::thread::sleep(wait);
  142. last(kind).fetch_max(tick, Ordering::Relaxed);
  143. S_OK
  144. };
  145. #[cfg(all(windows, feature = "diagnostics"))]
  146. {
  147. use crate::copystat::{C, add};
  148. add(C::PaceWaits, 1);
  149. add(C::PaceUs, wait.min(limit).as_micros() as u64);
  150. }
  151. // A frame begun on a time-out takes no tick: its flip still does.
  152. if origin && (hr == S_OK || flags & TOKEN_ON_TIMEOUT != 0) {
  153. // Tokens count frames (consecutive), not ticks.
  154. let frame = FRAME.fetch_add(1, Ordering::Relaxed) + 1;
  155. if !token.is_null() {
  156. // SAFETY: checked non-null; the title passes its token.
  157. unsafe { token.write(frame) };
  158. }
  159. }
  160. #[cfg(feature = "diagnostics")]
  161. tracing::debug!(
  162. kind,
  163. timeout_ms,
  164. flags,
  165. hr,
  166. tick,
  167. wait_us = wait.as_micros() as u64,
  168. frame = current(),
  169. "frame wait"
  170. );
  171. hr
  172. }
  173. /// Device method: no statistics are kept, so none are returned.
  174. pub(crate) extern "system" fn statistics(
  175. _: This,
  176. _token: u64,
  177. _kinds: u32,
  178. count: *mut u32,
  179. _out: *mut u8,
  180. ) -> HRESULT {
  181. if !count.is_null() {
  182. // SAFETY: checked non-null.
  183. unsafe { count.write(0) };
  184. }
  185. S_OK
  186. }
  187. #[cfg(test)]
  188. mod tests {
  189. use super::*;
  190. #[test]
  191. fn waits_end_on_ticks_and_count_frames() {
  192. let null = std::ptr::null();
  193. assert_eq!(set_interval(null, null, 2_000, 1, 0), S_OK);
  194. let mut first = 0;
  195. assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut first), S_OK);
  196. let before = Instant::now();
  197. let mut second = 0;
  198. assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut second), S_OK);
  199. assert!(second > first);
  200. // At the tick, not at the time-out (a busy PC may wake it late).
  201. assert!(before.elapsed() <= Duration::from_millis(500));
  202. assert_eq!(wait(null, 0, 0, std::ptr::null(), 0, &mut second), TIMEOUT);
  203. // Tokens count frames, a frame started early on a time-out too.
  204. let mut early = 0;
  205. let flags = TOKEN_ON_TIMEOUT;
  206. assert_eq!(
  207. wait(null, 0, 0, std::ptr::null(), flags, &mut early),
  208. TIMEOUT
  209. );
  210. let mut next = 0;
  211. assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut next), S_OK);
  212. assert!(early == second + 1 && next == early + 1);
  213. assert!(LAST[0].load(Ordering::Relaxed) >= 2);
  214. // The title's loop (the clock is global, so in the same test): an
  215. // origin poll that times out (and starts the frame), then a
  216. // blocking flip wait. Each flip takes its own tick.
  217. const FLIP: u32 = 2;
  218. // (The ticks are far apart, and it may take a few tries: a busy PC
  219. // wakes a wait tens of milliseconds late at times.)
  220. assert_eq!(set_interval(null, null, 60_000, 3, 0), S_OK);
  221. let mut token = 0;
  222. let mut four = || -> Vec<u64> {
  223. (0..4)
  224. .map(|_| {
  225. let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token);
  226. assert_eq!(
  227. wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token),
  228. S_OK
  229. );
  230. LAST[2].load(Ordering::Relaxed)
  231. })
  232. .collect()
  233. };
  234. let mut flips = four();
  235. for _ in 0..10 {
  236. if flips.windows(2).all(|w| w[1] == w[0] + 1) {
  237. break;
  238. }
  239. flips = four();
  240. }
  241. assert!(flips.windows(2).all(|w| w[1] == w[0] + 1), "{flips:?}");
  242. // Even when a flip wait begins on the tick another just ended on.
  243. let (tick, _) = next_tick(FLIP);
  244. assert!(tick > flips[3]);
  245. }
  246. }