frame.rs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. /// Per event kind (origin, vblank, flip and later kinds): the last tick a
  78. /// wait for it ended on.
  79. static LAST: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
  80. fn last(kind: u32) -> &'static AtomicU64 {
  81. &LAST[(kind as usize).min(LAST.len() - 1)]
  82. }
  83. /// The next tick after now and after the last one a wait for `kind` ended
  84. /// on (an event happens once per tick: a wait woken a little early must not
  85. /// let the next one end on the same tick), and how long until it.
  86. fn next_tick(kind: u32) -> (u64, Duration) {
  87. let mut clock = clock();
  88. let c = clock.get_or_insert_with(|| Clock {
  89. start: Instant::now(),
  90. interval: SIXTIETH,
  91. first: 0,
  92. });
  93. let elapsed = c.start.elapsed().as_nanos();
  94. let interval = c.interval.as_nanos().max(1);
  95. let tick =
  96. (c.first + (elapsed / interval + 1) as u64).max(last(kind).load(Ordering::Relaxed) + 1);
  97. let at = u128::from(tick - c.first) * interval;
  98. (
  99. tick,
  100. Duration::from_nanos(at.saturating_sub(elapsed) as u64),
  101. )
  102. }
  103. /// Device method: blocks until the next tick (or the time-out); an origin
  104. /// wait then hands out the new frame's token. Other events keep the token
  105. /// the title passes. Ticks are absolute (start plus whole intervals), so
  106. /// lateness never accumulates.
  107. pub(crate) extern "system" fn wait(
  108. _: This,
  109. kind: u32,
  110. timeout_ms: u32,
  111. _list: *const u8,
  112. flags: u32,
  113. token: *mut u64,
  114. ) -> HRESULT {
  115. let origin = kind == ORIGIN;
  116. let (mut tick, mut wait) = next_tick(kind);
  117. let limit = Duration::from_millis(u64::from(timeout_ms));
  118. // A blocking wait for an event that has happened since the last wait
  119. // for it ended (a frame took longer than a tick) ends at once, on the
  120. // tick that passed: sleeping on to the next one cost 17 ms of every
  121. // 730 ms frame (run 58: "2.0 frame waits sleeping 16.8 ms"). Polls (a
  122. // time-out shorter than a tick) answer as before.
  123. // `VICTORY_LATE_WAITS=1` sleeps to the next tick, as before.
  124. static SLEEP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  125. if !*SLEEP.get_or_init(|| std::env::var_os("VICTORY_LATE_WAITS").is_some_and(|v| v == "1"))
  126. && limit >= wait
  127. && tick > last(kind).load(Ordering::Relaxed) + 1
  128. {
  129. tick -= 1;
  130. wait = Duration::ZERO;
  131. }
  132. let hr = if wait > limit {
  133. std::thread::sleep(limit);
  134. TIMEOUT
  135. } else {
  136. std::thread::sleep(wait);
  137. last(kind).fetch_max(tick, Ordering::Relaxed);
  138. S_OK
  139. };
  140. #[cfg(all(windows, feature = "diagnostics"))]
  141. {
  142. use crate::copystat::{C, add};
  143. add(C::PaceWaits, 1);
  144. add(C::PaceUs, wait.min(limit).as_micros() as u64);
  145. }
  146. // A frame begun on a time-out takes no tick: its flip still does.
  147. if origin && (hr == S_OK || flags & TOKEN_ON_TIMEOUT != 0) {
  148. // Tokens count frames (consecutive), not ticks.
  149. let frame = FRAME.fetch_add(1, Ordering::Relaxed) + 1;
  150. if !token.is_null() {
  151. // SAFETY: checked non-null; the title passes its token.
  152. unsafe { token.write(frame) };
  153. }
  154. }
  155. #[cfg(feature = "diagnostics")]
  156. tracing::debug!(
  157. kind,
  158. timeout_ms,
  159. flags,
  160. hr,
  161. tick,
  162. wait_us = wait.as_micros() as u64,
  163. frame = current(),
  164. "frame wait"
  165. );
  166. hr
  167. }
  168. /// Device method: no statistics are kept, so none are returned.
  169. pub(crate) extern "system" fn statistics(
  170. _: This,
  171. _token: u64,
  172. _kinds: u32,
  173. count: *mut u32,
  174. _out: *mut u8,
  175. ) -> HRESULT {
  176. if !count.is_null() {
  177. // SAFETY: checked non-null.
  178. unsafe { count.write(0) };
  179. }
  180. S_OK
  181. }
  182. #[cfg(test)]
  183. mod tests {
  184. use super::*;
  185. #[test]
  186. fn waits_end_on_ticks_and_count_frames() {
  187. let null = std::ptr::null();
  188. assert_eq!(set_interval(null, null, 2_000, 1, 0), S_OK);
  189. let mut first = 0;
  190. assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut first), S_OK);
  191. let before = Instant::now();
  192. let mut second = 0;
  193. assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut second), S_OK);
  194. assert!(second > first);
  195. assert!(before.elapsed() <= Duration::from_millis(50));
  196. assert_eq!(wait(null, 0, 0, std::ptr::null(), 0, &mut second), TIMEOUT);
  197. // Tokens count frames, a frame started early on a time-out too.
  198. let mut early = 0;
  199. let flags = TOKEN_ON_TIMEOUT;
  200. assert_eq!(
  201. wait(null, 0, 0, std::ptr::null(), flags, &mut early),
  202. TIMEOUT
  203. );
  204. let mut next = 0;
  205. assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut next), S_OK);
  206. assert!(early == second + 1 && next == early + 1);
  207. assert!(LAST[0].load(Ordering::Relaxed) >= 2);
  208. // The title's loop (the clock is global, so in the same test): an
  209. // origin poll that times out (and starts the frame), then a
  210. // blocking flip wait. Each flip takes its own tick.
  211. const FLIP: u32 = 2;
  212. assert_eq!(set_interval(null, null, 5_000, 3, 0), S_OK);
  213. let mut token = 0;
  214. let flips: Vec<u64> = (0..4)
  215. .map(|_| {
  216. let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token);
  217. assert_eq!(
  218. wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token),
  219. S_OK
  220. );
  221. LAST[2].load(Ordering::Relaxed)
  222. })
  223. .collect();
  224. assert!(flips.windows(2).all(|w| w[1] == w[0] + 1), "{flips:?}");
  225. // Even when a flip wait begins on the tick another just ended on.
  226. let (tick, _) = next_tick(FLIP);
  227. assert!(tick > flips[3]);
  228. }
  229. }