popwatch.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. //! Diagnostics: textures that pop. `VICTORY_POP_WATCH=<from>-<to>[,<from>-<to>..]`
  2. //! (seconds since the start): every presented frame in those times is read
  3. //! back, made small on a thread of its own and compared with its neighbours,
  4. //! block by block. Counted and logged:
  5. //! - blips: blocks that one frame shows otherwise than the frames before and
  6. //! after it, which agree (a texture black, grey or another one for a frame);
  7. //! - steps: blocks that change from one frame to the next and stay so, while
  8. //! most of the picture does not move.
  9. //!
  10. //! `VICTORY_POP_FOLDER=<folder>`: the three pictures around a frame with
  11. //! blips (at most 200 times) are saved there, 640 wide; with
  12. //! `VICTORY_POP_ALL=1` every frame's is.
  13. use std::collections::VecDeque;
  14. use std::path::PathBuf;
  15. use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
  16. use std::sync::{Mutex, OnceLock, mpsc};
  17. use windows::Win32::Graphics::Direct3D12::*;
  18. /// A small picture: so many pixels wide and high.
  19. const WIDE: usize = 640;
  20. const HIGH: usize = 360;
  21. /// Pixels per side of a block.
  22. const BLOCK: usize = 16;
  23. /// A block changed: so much in the mean of its pixels' largest channel change.
  24. const CHANGED: f32 = 10.0;
  25. /// A block stayed.
  26. const STAYED: f32 = 4.0;
  27. /// `10-20,30-40` as seconds.
  28. fn parse(text: &str) -> Vec<(f64, f64)> {
  29. text.split(',')
  30. .filter_map(|part| {
  31. let (from, to) = part.trim().split_once('-')?;
  32. Some((from.trim().parse().ok()?, to.trim().parse().ok()?))
  33. })
  34. .collect()
  35. }
  36. fn asked() -> &'static [(f64, f64)] {
  37. static ASKED: OnceLock<Vec<(f64, f64)>> = OnceLock::new();
  38. ASKED.get_or_init(|| std::env::var("VICTORY_POP_WATCH").map(|v| parse(&v)).unwrap_or_default())
  39. }
  40. /// Whether frames are watched now.
  41. pub(crate) fn on() -> bool {
  42. let asked = asked();
  43. if asked.is_empty() {
  44. return false;
  45. }
  46. let now = crate::host::now_ms() as f64 / 1e3;
  47. asked.iter().any(|&(from, to)| now >= from && now < to)
  48. }
  49. /// A frame on its way back.
  50. pub(crate) struct Taken {
  51. buffer: ID3D12Resource,
  52. footprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
  53. }
  54. struct Job {
  55. frame: u64,
  56. taken: Taken,
  57. /// The submission that copies it.
  58. flown: u64,
  59. ms: u64,
  60. causes: [u64; 4],
  61. phase: Option<bool>,
  62. }
  63. /// Read-back buffers not in use.
  64. static FREE: Mutex<Vec<Taken>> = Mutex::new(Vec::new());
  65. /// Frames on their way.
  66. static WAITING: AtomicU64 = AtomicU64::new(0);
  67. /// Records the read-back of `texture` (in the copy-source state).
  68. pub(crate) fn take(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, texture: &ID3D12Resource) -> Option<Taken> {
  69. if !on() || WAITING.load(Relaxed) > 8 {
  70. return None;
  71. }
  72. let free = FREE.lock().unwrap_or_else(|e| e.into_inner()).pop();
  73. let Some(taken) = free else {
  74. let (buffer, footprint) = crate::capture::read_back(device, list, texture)?;
  75. return Some(Taken { buffer, footprint });
  76. };
  77. let to = D3D12_TEXTURE_COPY_LOCATION {
  78. // SAFETY: a borrowed pointer the location never releases.
  79. pResource: unsafe { std::mem::transmute_copy(&taken.buffer) },
  80. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  81. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: taken.footprint },
  82. };
  83. let from = D3D12_TEXTURE_COPY_LOCATION {
  84. // SAFETY: as above.
  85. pResource: unsafe { std::mem::transmute_copy(texture) },
  86. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  87. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
  88. };
  89. // SAFETY: an open list, live resources.
  90. unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
  91. Some(taken)
  92. }
  93. /// The list with `taken` went to the card as submission `flown` (0: it has
  94. /// run). `frame`: the frame it shows.
  95. pub(crate) fn sent(taken: Taken, flown: u64, frame: u64) {
  96. static THREAD: OnceLock<Option<mpsc::Sender<Job>>> = OnceLock::new();
  97. let Some(to) = THREAD.get_or_init(|| {
  98. let (to, from) = mpsc::channel::<Job>();
  99. std::thread::Builder::new().name("pop watch".into()).spawn(move || watch(&from)).ok().map(|_| to)
  100. }) else {
  101. return;
  102. };
  103. WAITING.fetch_add(1, Relaxed);
  104. let job = Job {
  105. frame,
  106. taken,
  107. flown,
  108. ms: crate::host::now_ms(),
  109. causes: crate::descriptor::host::pop_causes(),
  110. phase: crate::ab::pick("VICTORY_KEEP_SHOWN"),
  111. };
  112. let _ = to.send(job);
  113. }
  114. /// What was seen of the frames so far.
  115. #[derive(Default)]
  116. struct Seen {
  117. frames: u64,
  118. blips: u64,
  119. blip_frames: u64,
  120. steps: u64,
  121. still: u64,
  122. }
  123. struct Picture {
  124. frame: u64,
  125. ms: u64,
  126. causes: [u64; 4],
  127. phase: Option<bool>,
  128. rgb: Vec<u8>,
  129. /// Per block: how much it differs from the frame before.
  130. changed: Vec<f32>,
  131. saved: bool,
  132. }
  133. /// Per block, the mean of the pixels' largest channel change.
  134. fn differ(a: &[u8], b: &[u8]) -> Vec<f32> {
  135. let (across, down) = (WIDE / BLOCK, HIGH / BLOCK);
  136. let mut out = vec![0.0; across * down];
  137. for (n, sum) in out.iter_mut().enumerate() {
  138. let (bx, by) = (n % across * BLOCK, n / across * BLOCK);
  139. let mut total = 0u32;
  140. for y in by..by + BLOCK {
  141. let at = (y * WIDE + bx) * 3;
  142. let (ra, rb) = (&a[at..at + BLOCK * 3], &b[at..at + BLOCK * 3]);
  143. total += ra
  144. .chunks_exact(3)
  145. .zip(rb.chunks_exact(3))
  146. .map(|(p, q)| p.iter().zip(q).map(|(x, y)| u32::from(x.abs_diff(*y))).max().unwrap_or(0))
  147. .sum::<u32>();
  148. }
  149. *sum = total as f32 / (BLOCK * BLOCK) as f32;
  150. }
  151. out
  152. }
  153. /// The blips of `now` between `before` and `after`, and its steps (the frame
  154. /// before `before` had `quiet` changes): numbers of blocks. `None` for the
  155. /// steps if the picture moves.
  156. fn judge(before: &[u8], now: &[u8], after: &[u8], quiet: &[f32]) -> (usize, Option<usize>) {
  157. let (one, two, across) = (differ(before, now), differ(now, after), differ(before, after));
  158. let blips = (0..one.len())
  159. .filter(|&n| one[n] > CHANGED && two[n] > CHANGED && across[n] < STAYED && across[n] * 3.0 < one[n])
  160. .count();
  161. let still = one.iter().filter(|&&d| d < 3.0).count() * 10 >= one.len() * 7;
  162. let steps = still.then(|| {
  163. (0..one.len()).filter(|&n| one[n] > CHANGED && two[n] < STAYED && quiet.get(n).is_some_and(|&d| d < STAYED)).count()
  164. });
  165. (blips, steps)
  166. }
  167. /// `width * height` 8-bit RGBA (or BGRA) pixels made small.
  168. fn small(rows: &[u8], width: usize, height: usize, pitch: usize, bgra: bool) -> Vec<u8> {
  169. let mut out = Vec::with_capacity(WIDE * HIGH * 3);
  170. for y in 0..HIGH {
  171. for x in 0..WIDE {
  172. let mut sum = [0u32; 3];
  173. for sy in 0..3 {
  174. for sx in 0..3 {
  175. let px = ((x * 3 + sx) * 2 + 1) * width / (WIDE * 6);
  176. let py = ((y * 3 + sy) * 2 + 1) * height / (HIGH * 6);
  177. let p = &rows[py.min(height - 1) * pitch + px.min(width - 1) * 4..][..3];
  178. for (s, v) in sum.iter_mut().zip(p) {
  179. *s += u32::from(*v);
  180. }
  181. }
  182. }
  183. let c = sum.map(|s| (s / 9) as u8);
  184. out.extend(if bgra { [c[2], c[1], c[0]] } else { c });
  185. }
  186. }
  187. out
  188. }
  189. fn folder() -> Option<&'static PathBuf> {
  190. static FOLDER: OnceLock<Option<PathBuf>> = OnceLock::new();
  191. FOLDER
  192. .get_or_init(|| {
  193. let folder = PathBuf::from(std::env::var_os("VICTORY_POP_FOLDER")?);
  194. std::fs::create_dir_all(&folder).ok()?;
  195. Some(folder)
  196. })
  197. .as_ref()
  198. }
  199. fn save(p: &mut Picture) {
  200. if p.saved {
  201. return;
  202. }
  203. p.saved = true;
  204. if let Some(folder) = folder() {
  205. let png = crate::capture::png(WIDE as u32, HIGH as u32, &p.rgb);
  206. let _ = std::fs::write(folder.join(format!("{:07}-f{}.png", p.ms, p.frame)), png);
  207. }
  208. }
  209. fn watch(from: &mpsc::Receiver<Job>) {
  210. let all = std::env::var_os("VICTORY_POP_ALL").is_some_and(|v| v == "1");
  211. let mut last: VecDeque<Picture> = VecDeque::new();
  212. let mut seen: [Seen; 2] = Default::default();
  213. let mut told = crate::host::now_ms();
  214. let mut sets = 0;
  215. while let Ok(job) = from.recv() {
  216. while crate::host::submissions().1 < job.flown {
  217. std::thread::sleep(std::time::Duration::from_millis(1));
  218. }
  219. let f = job.taken.footprint.Footprint;
  220. let (rgba, bgra) = (matches!(f.Format.0, 27..=29), matches!(f.Format.0, 87 | 90 | 91));
  221. let mut data = std::ptr::null_mut();
  222. // SAFETY: the copy has run; the mapping spans the footprint's rows.
  223. let rgb = unsafe {
  224. if !(rgba || bgra) || job.taken.buffer.Map(0, None, Some(&mut data)).is_err() {
  225. WAITING.fetch_sub(1, Relaxed);
  226. continue;
  227. }
  228. let rows = std::slice::from_raw_parts(data.cast::<u8>(), f.RowPitch as usize * f.Height as usize);
  229. let rgb = small(rows, f.Width as usize, f.Height as usize, f.RowPitch as usize, bgra);
  230. job.taken.buffer.Unmap(0, None);
  231. rgb
  232. };
  233. FREE.lock().unwrap_or_else(|e| e.into_inner()).push(job.taken);
  234. WAITING.fetch_sub(1, Relaxed);
  235. // Frames that follow each other only.
  236. if last.back().is_some_and(|p| p.frame + 1 != job.frame) {
  237. last.clear();
  238. }
  239. let changed = last.back().map(|p| differ(&p.rgb, &rgb)).unwrap_or_default();
  240. let (frame, ms, causes, phase) = (job.frame, job.ms, job.causes, job.phase);
  241. last.push_back(Picture { frame, ms, causes, phase, rgb, changed, saved: false });
  242. if all && let Some(p) = last.back_mut() {
  243. save(p);
  244. }
  245. if last.len() > 4 {
  246. last.pop_front();
  247. }
  248. if let [first, before, now, after] = last.make_contiguous() {
  249. let (blips, steps) = judge(&before.rgb, &now.rgb, &after.rgb, &before.changed);
  250. let side = &mut seen[usize::from(now.phase.unwrap_or(false))];
  251. side.frames += 1;
  252. side.blips += blips as u64;
  253. side.blip_frames += u64::from(blips > 0);
  254. side.still += u64::from(steps.is_some());
  255. side.steps += steps.unwrap_or(0) as u64;
  256. if blips > 0 || steps.is_some_and(|s| s > 0) {
  257. let since: Vec<u64> = now.causes.iter().zip(&first.causes).map(|(a, b)| a.saturating_sub(*b)).collect();
  258. tracing::info!(
  259. "pop watch: frame {} at {:.2} s: {blips} blips, {steps:?} steps; in the two frames before it [made null for another texture, kept, neutral, stale] {since:?}",
  260. now.frame,
  261. now.ms as f64 / 1e3
  262. );
  263. }
  264. if (blips > 0 || steps.is_some_and(|s| s > 2)) && sets < 200 {
  265. sets += 1;
  266. save(before);
  267. save(now);
  268. save(after);
  269. }
  270. }
  271. if crate::host::now_ms().saturating_sub(told) > 5000 {
  272. told = crate::host::now_ms();
  273. for (n, s) in seen.iter().enumerate().filter(|(_, s)| s.frames > 0) {
  274. tracing::info!(
  275. "pop watch, since the start, VICTORY_KEEP_SHOWN {} in its A/B phases: {} frames, blips in {} of them ({} blocks of 16x16), {} frames whose picture stood still with {} blocks stepped",
  276. n,
  277. s.frames,
  278. s.blip_frames,
  279. s.blips,
  280. s.still,
  281. s.steps
  282. );
  283. }
  284. }
  285. }
  286. }
  287. #[cfg(test)]
  288. mod tests {
  289. use super::*;
  290. fn picture(color: u8) -> Vec<u8> {
  291. vec![color; WIDE * HIGH * 3]
  292. }
  293. fn patch(p: &mut [u8], bx: usize, by: usize, color: u8) {
  294. for y in by * BLOCK..(by + 1) * BLOCK {
  295. let at = (y * WIDE + bx * BLOCK) * 3;
  296. p[at..at + BLOCK * 3].fill(color);
  297. }
  298. }
  299. #[test]
  300. fn one_frame_otherwise_is_a_blip_and_a_lasting_change_a_step() {
  301. let (a, mut b) = (picture(100), picture(100));
  302. patch(&mut b, 3, 4, 0);
  303. let quiet = vec![0.0; (WIDE / BLOCK) * (HIGH / BLOCK)];
  304. assert_eq!(judge(&a, &b, &a, &quiet), (1, Some(0)));
  305. assert_eq!(judge(&a, &b, &b, &quiet), (0, Some(1)));
  306. assert_eq!(judge(&a, &a, &a, &quiet), (0, Some(0)));
  307. // All of it changes: a cut, no step.
  308. assert_eq!(judge(&a, &picture(0), &picture(0), &quiet), (0, None));
  309. // What moved just before is no step either.
  310. assert_eq!(judge(&a, &b, &b, &vec![9.0; quiet.len()]), (0, Some(0)));
  311. }
  312. #[test]
  313. fn times_are_read_and_pictures_made_small() {
  314. assert_eq!(parse("10-20, 30.5-40"), vec![(10.0, 20.0), (30.5, 40.0)]);
  315. assert!(parse("x").is_empty());
  316. let rows: Vec<u8> = [1u8, 2, 3, 255].repeat(1280 * 720);
  317. let out = small(&rows, 1280, 720, 1280 * 4, true);
  318. assert_eq!((out.len(), &out[..3]), (WIDE * HIGH * 3, &[3u8, 2, 1][..]));
  319. }
  320. }