capture.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. //! Presented frames written to PNG files, to see what reaches the screen:
  2. //! with `VICTORY_CAPTURE=<folder>`, every frame whose number is a power of
  3. //! two (the frames the log reports) is saved as `frame-<n>.png`, at half
  4. //! size. Only in builds with diagnostics.
  5. use std::path::PathBuf;
  6. use windows::Win32::Graphics::Direct3D12::*;
  7. use windows::Win32::Graphics::Dxgi::Common::*;
  8. /// The folder frames go to, if capturing.
  9. pub(crate) fn folder() -> Option<&'static PathBuf> {
  10. static FOLDER: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new();
  11. FOLDER
  12. .get_or_init(|| std::env::var_os("VICTORY_CAPTURE").map(PathBuf::from))
  13. .as_ref()
  14. }
  15. /// Frames listed in `VICTORY_CAPTURE_FRAMES` (comma-separated): saved
  16. /// too, and their draws traced at debug level.
  17. pub(crate) fn listed(n: u64) -> bool {
  18. static LIST: std::sync::OnceLock<Vec<u64>> = std::sync::OnceLock::new();
  19. LIST.get_or_init(|| {
  20. let list = std::env::var("VICTORY_CAPTURE_FRAMES").unwrap_or_default();
  21. list.split(',')
  22. .filter_map(|f| f.trim().parse().ok())
  23. .collect()
  24. })
  25. .contains(&n)
  26. }
  27. /// Whether frame `n` is saved.
  28. pub(crate) fn wanted(n: u64) -> bool {
  29. folder().is_some() && (n.is_power_of_two() || listed(n))
  30. }
  31. /// Saves 8-bit RGBA or BGRA rows (`pitch` bytes apart) as frame `n`.
  32. pub(crate) fn save(n: u64, width: u32, height: u32, pitch: usize, bgra: bool, rows: &[u8]) {
  33. save_as(&format!("frame-{n}"), width, height, pitch, bgra, rows);
  34. }
  35. /// Saves 8-bit RGBA or BGRA rows as `<name>.png`, at half size.
  36. fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows: &[u8]) {
  37. let Some(folder) = folder() else { return };
  38. let (w, h) = ((width / 2).max(1), (height / 2).max(1));
  39. // Filter byte 0 per row, then RGB of every other pixel of every other row.
  40. let mut raw = Vec::with_capacity((w as usize * 3 + 1) * h as usize);
  41. for y in 0..h as usize {
  42. raw.push(0);
  43. let row = &rows[(2 * y).min(height as usize - 1) * pitch..];
  44. for x in 0..w as usize {
  45. let p = &row[(2 * x).min(width as usize - 1) * 4..][..3];
  46. if bgra {
  47. raw.extend([p[2], p[1], p[0]]);
  48. } else {
  49. raw.extend_from_slice(p);
  50. }
  51. }
  52. }
  53. let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
  54. let mut header = Vec::new();
  55. header.extend(w.to_be_bytes());
  56. header.extend(h.to_be_bytes());
  57. header.extend([8, 2, 0, 0, 0]); // 8-bit RGB
  58. chunk(&mut png, b"IHDR", &header);
  59. chunk(
  60. &mut png,
  61. b"IDAT",
  62. &miniz_oxide::deflate::compress_to_vec_zlib(&raw, 3),
  63. );
  64. chunk(&mut png, b"IEND", &[]);
  65. let path = folder.join(format!("{name}.png"));
  66. match std::fs::write(&path, png) {
  67. Ok(()) => tracing::info!(path = %path.display(), "frame saved"),
  68. Err(e) => tracing::warn!(error = %e, path = %path.display(), "frame not saved"),
  69. }
  70. }
  71. fn chunk(png: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
  72. png.extend((data.len() as u32).to_be_bytes());
  73. let start = png.len();
  74. png.extend(kind);
  75. png.extend(data);
  76. let crc = crc32(&png[start..]);
  77. png.extend(crc.to_be_bytes());
  78. }
  79. fn crc32(bytes: &[u8]) -> u32 {
  80. let mut crc = !0u32;
  81. for &b in bytes {
  82. crc ^= u32::from(b);
  83. for _ in 0..8 {
  84. crc = (crc >> 1) ^ (0xedb8_8320 & (crc & 1).wrapping_neg());
  85. }
  86. }
  87. !crc
  88. }
  89. /// Records a copy of `texture` (in the copy-source state) into a
  90. /// readback buffer.
  91. pub(crate) fn read_back(
  92. device: &ID3D12Device,
  93. list: &ID3D12GraphicsCommandList,
  94. texture: &ID3D12Resource,
  95. ) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> {
  96. let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
  97. let mut total = 0;
  98. // SAFETY: a live texture; outputs for one subresource.
  99. unsafe {
  100. let desc = texture.GetDesc();
  101. device.GetCopyableFootprints(
  102. &desc,
  103. 0,
  104. 1,
  105. 0,
  106. Some(&mut footprint),
  107. None,
  108. None,
  109. Some(&mut total),
  110. );
  111. }
  112. let heap = D3D12_HEAP_PROPERTIES {
  113. Type: D3D12_HEAP_TYPE_READBACK,
  114. ..Default::default()
  115. };
  116. let desc = D3D12_RESOURCE_DESC {
  117. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  118. Width: total,
  119. Height: 1,
  120. DepthOrArraySize: 1,
  121. MipLevels: 1,
  122. SampleDesc: DXGI_SAMPLE_DESC {
  123. Count: 1,
  124. Quality: 0,
  125. },
  126. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  127. ..Default::default()
  128. };
  129. let mut buffer: Option<ID3D12Resource> = None;
  130. // SAFETY: plain creation; an open list; locations naming live resources.
  131. unsafe {
  132. device
  133. .CreateCommittedResource(
  134. &heap,
  135. D3D12_HEAP_FLAG_NONE,
  136. &desc,
  137. D3D12_RESOURCE_STATE_COPY_DEST,
  138. None,
  139. &mut buffer,
  140. )
  141. .ok()?;
  142. let buffer = buffer?;
  143. let to = D3D12_TEXTURE_COPY_LOCATION {
  144. pResource: std::mem::transmute_copy(&buffer),
  145. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  146. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  147. PlacedFootprint: footprint,
  148. },
  149. };
  150. let from = D3D12_TEXTURE_COPY_LOCATION {
  151. pResource: std::mem::transmute_copy(texture),
  152. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  153. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  154. SubresourceIndex: 0,
  155. },
  156. };
  157. list.CopyTextureRegion(&to, 0, 0, 0, &from, None);
  158. Some((buffer, footprint))
  159. }
  160. }
  161. /// Saves a frame read back by [`read_back`] (8-bit color only).
  162. pub(crate) fn save_read_back(
  163. frame: u64,
  164. buffer: &ID3D12Resource,
  165. footprint: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
  166. ) {
  167. let f = footprint.Footprint;
  168. let bgra = match f.Format {
  169. DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => false,
  170. DXGI_FORMAT_B8G8R8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM_SRGB => true,
  171. other => {
  172. tracing::warn!(format = other.0, "frame not saved: not 8-bit color");
  173. return;
  174. }
  175. };
  176. let mut data = std::ptr::null_mut();
  177. // SAFETY: the copy finished (every submission is waited for); the
  178. // mapping spans the footprint's rows.
  179. unsafe {
  180. if buffer.Map(0, None, Some(&mut data)).is_err() {
  181. return;
  182. }
  183. let len = f.RowPitch as usize * f.Height as usize;
  184. let rows = std::slice::from_raw_parts(data.cast::<u8>(), len);
  185. save(frame, f.Width, f.Height, f.RowPitch as usize, bgra, rows);
  186. buffer.Unmap(0, None);
  187. }
  188. }
  189. /// With `VICTORY_DUMP_TARGETS` set: title textures the frames listed in
  190. /// `VICTORY_CAPTURE_FRAMES` render to or write, in first-use order, saved
  191. /// at that frame's present as `frame-<n>-<i>-<resource>-<w>x<h>-f<format>.png`
  192. /// (what each holds at the end of the frame; formats normalized to show
  193. /// structure: floats scaled by their largest value, depth by its range).
  194. static TARGETS: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
  195. fn dump_on() -> bool {
  196. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  197. *ON.get_or_init(|| folder().is_some() && std::env::var_os("VICTORY_DUMP_TARGETS").is_some())
  198. }
  199. /// Notes a title texture the frame being built renders to or writes.
  200. pub(crate) fn note_target(resource: crate::object::This) {
  201. if resource.is_null() || !dump_on() || !listed(crate::queue::presented() + 1) {
  202. return;
  203. }
  204. let mut targets = TARGETS.lock().unwrap_or_else(|e| e.into_inner());
  205. if !targets.contains(&(resource as usize)) {
  206. targets.push(resource as usize);
  207. }
  208. }
  209. /// At the present of frame `frame`: saves the noted targets.
  210. pub(crate) fn dump_targets(frame: u64) {
  211. let targets = std::mem::take(&mut *TARGETS.lock().unwrap_or_else(|e| e.into_inner()));
  212. let Some(host) = crate::host::host() else { return };
  213. for (i, &resource) in targets.iter().enumerate() {
  214. let resource = resource as crate::object::This;
  215. let Some(texture) = crate::resource::host_resource(resource) else {
  216. continue;
  217. };
  218. // SAFETY: a live resource.
  219. let d = unsafe { texture.GetDesc() };
  220. if d.SampleDesc.Count > 1 || d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D {
  221. continue;
  222. }
  223. const COPY_SOURCE: u32 = 0x800;
  224. let Some(before) = crate::resource::host_transition(resource, COPY_SOURCE).map(|(_, b)| b)
  225. else {
  226. dump_one(host, texture, COPY_SOURCE, frame, i, resource, &d);
  227. continue;
  228. };
  229. dump_one(host, texture, before, frame, i, resource, &d);
  230. crate::resource::host_transition(resource, before);
  231. }
  232. }
  233. fn dump_one(
  234. host: &crate::host::Host,
  235. texture: &ID3D12Resource,
  236. state: u32,
  237. frame: u64,
  238. i: usize,
  239. resource: crate::object::This,
  240. d: &D3D12_RESOURCE_DESC,
  241. ) {
  242. let Ok(list) = host.new_list() else { return };
  243. let state = D3D12_RESOURCE_STATES(crate::host::legal_state(texture, state) as i32);
  244. let copy = D3D12_RESOURCE_STATE_COPY_SOURCE;
  245. // SAFETY: an open list of ours and a live texture.
  246. let read = unsafe {
  247. if state != copy {
  248. list.list
  249. .ResourceBarrier(&[crate::host::transition(texture, state, copy)]);
  250. }
  251. let read = read_back(&host.device, &list.list, texture);
  252. if state != copy {
  253. list.list
  254. .ResourceBarrier(&[crate::host::transition(texture, copy, state)]);
  255. }
  256. read
  257. };
  258. list.close();
  259. host.execute(&[&list]);
  260. let Some((buffer, footprint)) = read else { return };
  261. let f = footprint.Footprint;
  262. let mut data = std::ptr::null_mut();
  263. // SAFETY: the copy finished; the mapping spans the footprint's rows.
  264. unsafe {
  265. if buffer.Map(0, None, Some(&mut data)).is_err() {
  266. return;
  267. }
  268. let pitch = f.RowPitch as usize;
  269. let rows = std::slice::from_raw_parts(data.cast::<u8>(), pitch * f.Height as usize);
  270. if let Some(rgba) = to_rgba(f.Format.0 as u32, f.Width as usize, f.Height as usize, pitch, rows) {
  271. let name = format!(
  272. "frame-{frame}-{i:02}-{resource:?}-{}x{}-f{}",
  273. d.Width, d.Height, d.Format.0
  274. );
  275. save_as(&name, f.Width, f.Height, f.Width as usize * 4, false, &rgba);
  276. } else {
  277. tracing::info!(format = f.Format.0, ?resource, "target not dumped: format");
  278. }
  279. buffer.Unmap(0, None);
  280. }
  281. }
  282. fn half(h: u16) -> f32 {
  283. let (sign, exp, man) = ((h >> 15) as u32, ((h >> 10) & 0x1f) as i32, (h & 0x3ff) as f32);
  284. let v = match exp {
  285. 0 => man * 2f32.powi(-24),
  286. 31 => f32::INFINITY,
  287. e => (1.0 + man / 1024.0) * 2f32.powi(e - 15),
  288. };
  289. if sign == 1 { -v } else { v }
  290. }
  291. /// A float packed in `bits` with a 5-bit exponent and `man` mantissa bits
  292. /// (the 11- and 10-bit floats of R11G11B10).
  293. fn small_float(bits: u32, man: u32) -> f32 {
  294. let (exp, m) = ((bits >> man) & 0x1f, (bits & ((1 << man) - 1)) as f32);
  295. match exp {
  296. 0 => m / (1 << man) as f32 * 2f32.powi(-14),
  297. 31 => f32::INFINITY,
  298. e => (1.0 + m / (1 << man) as f32) * 2f32.powi(e as i32 - 15),
  299. }
  300. }
  301. /// Rows of a host format as 8-bit RGBA: 8-bit color as is, everything else
  302. /// as channel values scaled so the largest finite one is white (single
  303. /// channels: lowest black, highest white, as grey). `None` for formats not
  304. /// handled.
  305. fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option<Vec<u8>> {
  306. let mut out = Vec::with_capacity(w * h * 4);
  307. let px = |x: usize, y: usize, n: usize| &rows[y * pitch + x * n..][..n];
  308. let u16_at = |b: &[u8], i: usize| u16::from_le_bytes([b[2 * i], b[2 * i + 1]]);
  309. let u32_at = |b: &[u8], i: usize| u32::from_le_bytes(b[4 * i..4 * i + 4].try_into().unwrap_or([0; 4]));
  310. // Channel values as floats, then scaled.
  311. type Decode = Box<dyn Fn(&[u8]) -> [f32; 3]>;
  312. let (n, decode): (usize, Decode) = match format {
  313. 27..=32 => {
  314. for y in 0..h {
  315. for x in 0..w {
  316. let p = px(x, y, 4);
  317. out.extend([p[0], p[1], p[2], 255]);
  318. }
  319. }
  320. return Some(out);
  321. }
  322. 87..=93 => {
  323. for y in 0..h {
  324. for x in 0..w {
  325. let p = px(x, y, 4);
  326. out.extend([p[2], p[1], p[0], 255]);
  327. }
  328. }
  329. return Some(out);
  330. }
  331. 23..=25 => (4, Box::new(move |b| {
  332. let v = u32_at(b, 0);
  333. [(v & 0x3ff) as f32, (v >> 10 & 0x3ff) as f32, (v >> 20 & 0x3ff) as f32]
  334. })),
  335. 26 => (4, Box::new(move |b| {
  336. let v = u32_at(b, 0);
  337. [small_float(v & 0x7ff, 6), small_float(v >> 11 & 0x7ff, 6), small_float(v >> 22, 5)]
  338. })),
  339. 9..=11 => (8, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))])),
  340. 33..=34 => (4, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), 0.0])),
  341. 1..=2 => (16, Box::new(move |b| {
  342. [0, 1, 2].map(|i| f32::from_bits(u32_at(b, i)))
  343. })),
  344. 15..=16 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)), f32::from_bits(u32_at(b, 1)), 0.0])),
  345. 35..=38 => (4, Box::new(move |b| [f32::from(u16_at(b, 0)), f32::from(u16_at(b, 1)), 0.0])),
  346. 48..=52 => (2, Box::new(move |b| [f32::from(b[0]), f32::from(b[1]), 0.0])),
  347. // Single channels: shown as grey.
  348. 39..=43 => (4, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])),
  349. 53..=54 => (2, Box::new(move |b| [half(u16_at(b, 0)); 3])),
  350. 55..=59 => (2, Box::new(move |b| [f32::from(u16_at(b, 0)); 3])),
  351. 60..=65 => (1, Box::new(move |b| [f32::from(b[0]); 3])),
  352. _ => return None,
  353. };
  354. let values: Vec<[f32; 3]> = (0..h)
  355. .flat_map(|y| (0..w).map(move |x| (x, y)))
  356. .map(|(x, y)| decode(px(x, y, n)))
  357. .collect();
  358. let grey = matches!(format, 39..=43 | 53..=65);
  359. let finite = values.iter().flatten().copied().filter(|v| v.is_finite());
  360. let (low, high) = if grey {
  361. finite.fold((f32::MAX, f32::MIN), |(l, h), v| (l.min(v), h.max(v)))
  362. } else {
  363. (0.0, finite.fold(0.0f32, f32::max))
  364. };
  365. let range = (high - low).max(1e-20);
  366. tracing::info!(format, low, high, "target values");
  367. for v in values {
  368. let c = v.map(|c| (((c - low) / range).clamp(0.0, 1.0) * 255.0) as u8);
  369. out.extend([c[0], c[1], c[2], 255]);
  370. }
  371. Some(out)
  372. }
  373. /// Pixels per side of the grid [`probe`] reads.
  374. const GRID: u32 = 4;
  375. /// Bytes between the grid's pixels in the readback buffer (placement
  376. /// alignment).
  377. const SLOT: u64 = 512;
  378. /// Records copies of a grid of pixels of `texture` (8-bit color, in the
  379. /// copy-source state) into a readback buffer, to tell black frames.
  380. pub(crate) fn probe(
  381. device: &ID3D12Device,
  382. list: &ID3D12GraphicsCommandList,
  383. texture: &ID3D12Resource,
  384. ) -> Option<ID3D12Resource> {
  385. // SAFETY: a live resource.
  386. let d = unsafe { texture.GetDesc() };
  387. if !matches!(d.Format.0, 27..=29 | 87 | 90 | 91) {
  388. return None;
  389. }
  390. let desc = D3D12_RESOURCE_DESC {
  391. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  392. Width: SLOT * u64::from(GRID * GRID),
  393. Height: 1,
  394. DepthOrArraySize: 1,
  395. MipLevels: 1,
  396. SampleDesc: DXGI_SAMPLE_DESC {
  397. Count: 1,
  398. Quality: 0,
  399. },
  400. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  401. ..Default::default()
  402. };
  403. let heap = D3D12_HEAP_PROPERTIES {
  404. Type: D3D12_HEAP_TYPE_READBACK,
  405. ..Default::default()
  406. };
  407. let mut buffer: Option<ID3D12Resource> = None;
  408. // SAFETY: plain creation; an open list; locations naming live resources.
  409. unsafe {
  410. device
  411. .CreateCommittedResource(
  412. &heap,
  413. D3D12_HEAP_FLAG_NONE,
  414. &desc,
  415. D3D12_RESOURCE_STATE_COPY_DEST,
  416. None,
  417. &mut buffer,
  418. )
  419. .ok()?;
  420. let buffer = buffer?;
  421. for i in 0..GRID * GRID {
  422. let (x, y) = (
  423. (2 * (i % GRID) + 1) * d.Width as u32 / (2 * GRID),
  424. (2 * (i / GRID) + 1) * d.Height / (2 * GRID),
  425. );
  426. let to = D3D12_TEXTURE_COPY_LOCATION {
  427. pResource: std::mem::transmute_copy(&buffer),
  428. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  429. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  430. PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
  431. Offset: SLOT * u64::from(i),
  432. Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
  433. Format: d.Format,
  434. Width: 1,
  435. Height: 1,
  436. Depth: 1,
  437. RowPitch: 256,
  438. },
  439. },
  440. },
  441. };
  442. let from = D3D12_TEXTURE_COPY_LOCATION {
  443. pResource: std::mem::transmute_copy(texture),
  444. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  445. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  446. SubresourceIndex: 0,
  447. },
  448. };
  449. let pixel = D3D12_BOX {
  450. left: x,
  451. top: y,
  452. front: 0,
  453. right: x + 1,
  454. bottom: y + 1,
  455. back: 1,
  456. };
  457. list.CopyTextureRegion(&to, 0, 0, 0, &from, Some(&pixel));
  458. }
  459. Some(buffer)
  460. }
  461. }
  462. /// Whether every pixel [`probe`] read is (near) black.
  463. pub(crate) fn black(buffer: &ID3D12Resource) -> bool {
  464. let mut data = std::ptr::null_mut();
  465. // SAFETY: the copies finished (every submission is waited for).
  466. unsafe {
  467. if buffer.Map(0, None, Some(&mut data)).is_err() {
  468. return false;
  469. }
  470. let bytes =
  471. std::slice::from_raw_parts(data.cast::<u8>(), (SLOT * u64::from(GRID * GRID)) as usize);
  472. let level = bytes
  473. .chunks(SLOT as usize)
  474. .flat_map(|pixel| pixel[..3].iter().copied())
  475. .max()
  476. .unwrap_or(0);
  477. buffer.Unmap(0, None);
  478. let mut levels = LEVELS.lock().unwrap_or_else(|e| e.into_inner());
  479. if levels.len() == 12 {
  480. levels.pop_front();
  481. }
  482. levels.push_back(level);
  483. level < 8
  484. }
  485. }
  486. /// The brightest probed channel of the last frames, oldest first: a fade
  487. /// darkens over several, a glitch drops at once.
  488. static LEVELS: std::sync::Mutex<std::collections::VecDeque<u8>> =
  489. std::sync::Mutex::new(std::collections::VecDeque::new());
  490. pub(crate) fn recent_levels() -> Vec<u8> {
  491. let levels = LEVELS.lock().unwrap_or_else(|e| e.into_inner());
  492. levels.iter().copied().collect()
  493. }
  494. #[cfg(test)]
  495. mod tests {
  496. #[test]
  497. fn crc_matches_the_png_check_value() {
  498. assert_eq!(super::crc32(b"IEND"), 0xae42_6082);
  499. }
  500. }