frame.rs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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: Grand Theft Auto VI 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 (tick, wait) = next_tick(kind);
  117. let limit = Duration::from_millis(u64::from(timeout_ms));
  118. let hr = if wait > limit {
  119. std::thread::sleep(limit);
  120. TIMEOUT
  121. } else {
  122. std::thread::sleep(wait);
  123. last(kind).fetch_max(tick, Ordering::Relaxed);
  124. S_OK
  125. };
  126. // A frame begun on a time-out takes no tick: its flip still does.
  127. if origin && (hr == S_OK || flags & TOKEN_ON_TIMEOUT != 0) {
  128. // Tokens count frames (consecutive), not ticks.
  129. let frame = FRAME.fetch_add(1, Ordering::Relaxed) + 1;
  130. if !token.is_null() {
  131. // SAFETY: checked non-null; the title passes its token.
  132. unsafe { token.write(frame) };
  133. }
  134. }
  135. #[cfg(feature = "diagnostics")]
  136. tracing::debug!(
  137. kind,
  138. timeout_ms,
  139. flags,
  140. hr,
  141. tick,
  142. wait_us = wait.as_micros() as u64,
  143. frame = current(),
  144. "frame wait"
  145. );
  146. hr
  147. }
  148. /// Device method: no statistics are kept, so none are returned.
  149. pub(crate) extern "system" fn statistics(
  150. _: This,
  151. _token: u64,
  152. _kinds: u32,
  153. count: *mut u32,
  154. _out: *mut u8,
  155. ) -> HRESULT {
  156. if !count.is_null() {
  157. // SAFETY: checked non-null.
  158. unsafe { count.write(0) };
  159. }
  160. S_OK
  161. }
  162. #[cfg(test)]
  163. mod tests {
  164. use super::*;
  165. #[test]
  166. fn waits_end_on_ticks_and_count_frames() {
  167. let null = std::ptr::null();
  168. assert_eq!(set_interval(null, null, 2_000, 1, 0), S_OK);
  169. let mut first = 0;
  170. assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut first), S_OK);
  171. let before = Instant::now();
  172. let mut second = 0;
  173. assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut second), S_OK);
  174. assert!(second > first);
  175. assert!(before.elapsed() <= Duration::from_millis(50));
  176. assert_eq!(wait(null, 0, 0, std::ptr::null(), 0, &mut second), TIMEOUT);
  177. // Tokens count frames, a frame started early on a time-out too.
  178. let mut early = 0;
  179. let flags = TOKEN_ON_TIMEOUT;
  180. assert_eq!(
  181. wait(null, 0, 0, std::ptr::null(), flags, &mut early),
  182. TIMEOUT
  183. );
  184. let mut next = 0;
  185. assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut next), S_OK);
  186. assert!(early == second + 1 && next == early + 1);
  187. assert!(LAST[0].load(Ordering::Relaxed) >= 2);
  188. // The title's loop (the clock is global, so in the same test): an
  189. // origin poll that times out (and starts the frame), then a
  190. // blocking flip wait. Each flip takes its own tick.
  191. const FLIP: u32 = 2;
  192. assert_eq!(set_interval(null, null, 5_000, 3, 0), S_OK);
  193. let mut token = 0;
  194. let flips: Vec<u64> = (0..4)
  195. .map(|_| {
  196. let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token);
  197. assert_eq!(
  198. wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token),
  199. S_OK
  200. );
  201. LAST[2].load(Ordering::Relaxed)
  202. })
  203. .collect();
  204. assert!(flips.windows(2).all(|w| w[1] == w[0] + 1), "{flips:?}");
  205. // Even when a flip wait begins on the tick another just ended on.
  206. let (tick, _) = next_tick(FLIP);
  207. assert!(tick > flips[3]);
  208. }
  209. }