1use std::{
2 fs::{self, File},
3 io::{BufReader, BufWriter},
4 path::{Path, PathBuf},
5};
6
7use sui_avif::{
8 Encoder as AvifEncoder, HdrEncodingOptions, RgbaF32Image, RgbaU8Image, SdrEncodingOptions,
9};
10use sui_core::{Color, Error, Rect, Result};
11use sui_render_wgpu::{DebugCaptureArtifact, HdrRgbaImage, RgbaImage};
12
13use crate::snapshot::WindowSnapshot;
14
15const SCREENSHOT_CHANNEL_TOLERANCE: u8 = 1;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct Screenshot {
19 width: u32,
20 height: u32,
21 pixels: Vec<u8>,
22}
23
24#[derive(Debug, Clone, PartialEq)]
25pub struct ArtifactBundle {
26 pub snapshot: WindowSnapshot,
27 pub screenshot: Option<Screenshot>,
28 pub semantics_overlay: Option<Screenshot>,
29 pub widget_overlay: Option<Screenshot>,
30}
31
32pub fn write_hdr_exr(image: &HdrRgbaImage, path: impl AsRef<Path>) -> Result<()> {
33 use exr::prelude::write_rgba_file;
34
35 let path = path.as_ref();
36 if let Some(parent) = path.parent() {
37 fs::create_dir_all(parent).map_err(io_error)?;
38 }
39
40 write_rgba_file(
41 path,
42 image.width() as usize,
43 image.height() as usize,
44 |x, y| {
45 let offset = (y * image.width() as usize + x) * 4;
46 let pixels = image.pixels();
47 (
48 pixels[offset],
49 pixels[offset + 1],
50 pixels[offset + 2],
51 pixels[offset + 3],
52 )
53 },
54 )
55 .map_err(exr_error)
56}
57
58pub fn write_hdr_avif(
59 image: &HdrRgbaImage,
60 path: impl AsRef<Path>,
61 sdr_white_level: f32,
62) -> Result<()> {
63 let hdr_image =
64 RgbaF32Image::new(image.width(), image.height(), image.pixels()).map_err(avif_error)?;
65 let options = HdrEncodingOptions {
66 source_white_level: if sdr_white_level.is_finite() && sdr_white_level > 0.0 {
67 sdr_white_level
68 } else {
69 1.0
70 },
71 ..HdrEncodingOptions::default()
72 };
73 let encoded = AvifEncoder::new()
74 .with_quality(100.0)
75 .with_alpha_quality(80.0)
76 .with_speed(4)
77 .encode_hdr_rgba_f32(&hdr_image, &options)
78 .map_err(avif_error)?;
79 let path = path.as_ref();
80 if let Some(parent) = path.parent() {
81 fs::create_dir_all(parent).map_err(io_error)?;
82 }
83 fs::write(path, encoded.avif_file).map_err(io_error)
84}
85
86pub fn hdr_luminance_heatmap(image: &HdrRgbaImage) -> Result<Screenshot> {
87 let mut pixels = Vec::with_capacity((image.width() * image.height() * 4) as usize);
88 for rgba in image.pixels().chunks_exact(4) {
89 let luminance = (rgba[0] * 0.2126 + rgba[1] * 0.7152 + rgba[2] * 0.0722).max(0.0);
90 let normalized = (luminance / (1.0 + luminance)).clamp(0.0, 1.0);
91 let value = (normalized * 255.0).round() as u8;
92 pixels.extend_from_slice(&[value, value, value, 255]);
93 }
94 Screenshot::new(image.width(), image.height(), pixels)
95}
96
97pub fn hdr_headroom_heatmap(image: &HdrRgbaImage, sdr_white_level: f32) -> Result<Screenshot> {
98 let reference_white = if sdr_white_level.is_finite() && sdr_white_level > 0.0 {
99 sdr_white_level
100 } else {
101 1.0
102 };
103 let mut pixels = Vec::with_capacity((image.width() * image.height() * 4) as usize);
104 for rgba in image.pixels().chunks_exact(4) {
105 let headroom = (rgba[0].max(rgba[1]).max(rgba[2]) / reference_white).max(0.0);
106 let normalized = (headroom / (1.0 + headroom)).clamp(0.0, 1.0);
107 let red = (normalized * 255.0).round() as u8;
108 let blue = ((1.0 - normalized) * 96.0).round() as u8;
109 pixels.extend_from_slice(&[red, 32, blue, 255]);
110 }
111 Screenshot::new(image.width(), image.height(), pixels)
112}
113
114pub fn hdr_clip_mask(image: &HdrRgbaImage, threshold: f32) -> Result<Screenshot> {
115 let clip_threshold = if threshold.is_finite() && threshold > 0.0 {
116 threshold
117 } else {
118 1.0
119 };
120 let mut pixels = Vec::with_capacity((image.width() * image.height() * 4) as usize);
121 for rgba in image.pixels().chunks_exact(4) {
122 let clipped = rgba[0].max(rgba[1]).max(rgba[2]) > clip_threshold;
123 if clipped {
124 pixels.extend_from_slice(&[255, 64, 64, 255]);
125 } else {
126 pixels.extend_from_slice(&[0, 0, 0, 255]);
127 }
128 }
129 Screenshot::new(image.width(), image.height(), pixels)
130}
131
132impl Screenshot {
133 pub fn new(width: u32, height: u32, pixels: Vec<u8>) -> Result<Self> {
134 let expected_len = width as usize * height as usize * 4;
135 if pixels.len() != expected_len {
136 return Err(Error::new(format!(
137 "screenshot pixel buffer length {} does not match {}x{} image size",
138 pixels.len(),
139 width,
140 height
141 )));
142 }
143
144 Ok(Self {
145 width,
146 height,
147 pixels,
148 })
149 }
150
151 pub(crate) fn from_rgba_image(image: RgbaImage) -> Self {
152 Self {
153 width: image.width(),
154 height: image.height(),
155 pixels: image.into_pixels(),
156 }
157 }
158
159 pub(crate) fn from_debug_capture_artifact(artifact: DebugCaptureArtifact) -> Result<Self> {
160 match artifact {
161 DebugCaptureArtifact::SdrRgba8(image) => Ok(Self::from_rgba_image(image)),
162 DebugCaptureArtifact::HdrLinearRgbaF32(image) => Self::from_hdr_linear_image(&image),
163 }
164 }
165
166 pub(crate) fn from_hdr_linear_image(image: &HdrRgbaImage) -> Result<Self> {
167 let mut pixels = Vec::with_capacity((image.width() * image.height() * 4) as usize);
168 for rgba in image.pixels().chunks_exact(4) {
169 pixels.extend_from_slice(&[
170 linear_to_srgb_u8(rgba[0]),
171 linear_to_srgb_u8(rgba[1]),
172 linear_to_srgb_u8(rgba[2]),
173 linear_alpha_to_u8(rgba[3]),
174 ]);
175 }
176 Self::new(image.width(), image.height(), pixels)
177 }
178
179 pub fn width(&self) -> u32 {
180 self.width
181 }
182
183 pub fn height(&self) -> u32 {
184 self.height
185 }
186
187 pub fn pixels(&self) -> &[u8] {
188 &self.pixels
189 }
190
191 pub fn write_png(&self, path: impl AsRef<Path>) -> Result<()> {
192 let path = path.as_ref();
193 if let Some(parent) = path.parent() {
194 fs::create_dir_all(parent).map_err(io_error)?;
195 }
196
197 let file = File::create(path).map_err(io_error)?;
198 let writer = BufWriter::new(file);
199 let mut encoder = png::Encoder::new(writer, self.width, self.height);
200 encoder.set_color(png::ColorType::Rgba);
201 encoder.set_depth(png::BitDepth::Eight);
202 let mut writer = encoder.write_header().map_err(png_error)?;
203 writer.write_image_data(&self.pixels).map_err(png_error)
204 }
205
206 pub fn write_avif(&self, path: impl AsRef<Path>) -> Result<()> {
207 let image = RgbaU8Image::new(self.width, self.height, &self.pixels).map_err(avif_error)?;
208 let encoded = AvifEncoder::new()
209 .with_quality(100.0)
210 .with_alpha_quality(80.0)
211 .with_speed(4)
212 .encode_sdr_rgba8(&image, &SdrEncodingOptions::default())
213 .map_err(avif_error)?;
214 let path = path.as_ref();
215 if let Some(parent) = path.parent() {
216 fs::create_dir_all(parent).map_err(io_error)?;
217 }
218 fs::write(path, encoded.avif_file).map_err(io_error)
219 }
220
221 pub fn crop(&self, bounds: Rect) -> Result<Self> {
222 let left = bounds.x().floor().max(0.0) as u32;
223 let top = bounds.y().floor().max(0.0) as u32;
224 let right = bounds.max_x().ceil().max(0.0) as u32;
225 let bottom = bounds.max_y().ceil().max(0.0) as u32;
226 let clamped_right = right.min(self.width);
227 let clamped_bottom = bottom.min(self.height);
228
229 if left >= clamped_right || top >= clamped_bottom {
230 return Err(Error::new(
231 "cannot capture screenshot for an empty or out-of-bounds region",
232 ));
233 }
234
235 let width = clamped_right - left;
236 let height = clamped_bottom - top;
237 let mut pixels = Vec::with_capacity((width * height * 4) as usize);
238 for y in top..clamped_bottom {
239 let row_start = ((y * self.width + left) * 4) as usize;
240 let row_end = row_start + (width * 4) as usize;
241 pixels.extend_from_slice(&self.pixels[row_start..row_end]);
242 }
243
244 Ok(Self {
245 width,
246 height,
247 pixels,
248 })
249 }
250}
251
252fn linear_to_srgb_u8(channel: f32) -> u8 {
253 let value = channel.clamp(0.0, 1.0);
254 let encoded = if value <= 0.003_130_8 {
255 value * 12.92
256 } else {
257 (1.055 * value.powf(1.0 / 2.4)) - 0.055
258 };
259 (encoded.clamp(0.0, 1.0) * 255.0).round() as u8
260}
261
262fn linear_alpha_to_u8(alpha: f32) -> u8 {
263 (alpha.clamp(0.0, 1.0) * 255.0).round() as u8
264}
265
266impl ArtifactBundle {
267 pub fn write_to_dir(&self, dir: impl AsRef<Path>) -> Result<()> {
268 let dir = dir.as_ref();
269 fs::create_dir_all(dir).map_err(io_error)?;
270
271 fs::write(dir.join("summary.txt"), format_summary(&self.snapshot)).map_err(io_error)?;
272 fs::write(dir.join("semantics.txt"), format_semantics(&self.snapshot)).map_err(io_error)?;
273 fs::write(
274 dir.join("widget-graph.txt"),
275 format_widget_graph(&self.snapshot),
276 )
277 .map_err(io_error)?;
278
279 if let Some(scene) = &self.snapshot.scene_summary {
280 fs::write(dir.join("scene.txt"), format_scene(scene)).map_err(io_error)?;
281 }
282 if let Some(screenshot) = &self.screenshot {
283 screenshot.write_png(dir.join("screenshot.png"))?;
284 }
285 if let Some(overlay) = &self.semantics_overlay {
286 overlay.write_png(dir.join("semantics-overlay.png"))?;
287 }
288 if let Some(overlay) = &self.widget_overlay {
289 overlay.write_png(dir.join("widget-overlay.png"))?;
290 }
291
292 Ok(())
293 }
294}
295
296pub(crate) fn read_png(path: &Path) -> Result<Screenshot> {
297 let file = File::open(path).map_err(io_error)?;
298 let decoder = png::Decoder::new(BufReader::new(file));
299 let mut reader = decoder.read_info().map_err(png_error)?;
300 let output_size = reader
301 .output_buffer_size()
302 .ok_or_else(|| Error::new("PNG screenshot exceeds the decoder output size limit"))?;
303 let mut buffer = vec![0; output_size];
304 let info = reader.next_frame(&mut buffer).map_err(png_error)?;
305 if info.color_type != png::ColorType::Rgba || info.bit_depth != png::BitDepth::Eight {
306 return Err(Error::new("expected an RGBA8 PNG screenshot baseline"));
307 }
308
309 Ok(Screenshot {
310 width: info.width,
311 height: info.height,
312 pixels: buffer[..info.buffer_size()].to_vec(),
313 })
314}
315
316pub(crate) fn diff_screenshot(expected: &Screenshot, actual: &Screenshot) -> Result<Screenshot> {
317 let width = expected.width.max(actual.width);
318 let height = expected.height.max(actual.height);
319 let mut pixels = vec![0; (width * height * 4) as usize];
320
321 for y in 0..height {
322 for x in 0..width {
323 let expected_px = pixel_at(expected, x, y).unwrap_or([0, 0, 0, 0]);
324 let actual_px = pixel_at(actual, x, y).unwrap_or([0, 0, 0, 0]);
325 let offset = ((y * width + x) * 4) as usize;
326 let rgba = if rgba_channels_match(expected_px, actual_px) {
327 [actual_px[0] / 2, actual_px[1] / 2, actual_px[2] / 2, 255]
328 } else {
329 [255, actual_px[1] / 3, actual_px[2] / 3, 255]
330 };
331 pixels[offset..offset + 4].copy_from_slice(&rgba);
332 }
333 }
334
335 Ok(Screenshot {
336 width,
337 height,
338 pixels,
339 })
340}
341
342pub(crate) fn screenshots_match(expected: &Screenshot, actual: &Screenshot) -> bool {
343 expected.width == actual.width
344 && expected.height == actual.height
345 && expected
346 .pixels
347 .chunks_exact(4)
348 .zip(actual.pixels.chunks_exact(4))
349 .all(|(expected, actual)| {
350 rgba_channels_match(
351 [expected[0], expected[1], expected[2], expected[3]],
352 [actual[0], actual[1], actual[2], actual[3]],
353 )
354 })
355}
356
357fn rgba_channels_match(expected: [u8; 4], actual: [u8; 4]) -> bool {
358 expected
359 .into_iter()
360 .zip(actual)
361 .all(|(expected, actual)| expected.abs_diff(actual) <= SCREENSHOT_CHANNEL_TOLERANCE)
362}
363
364pub(crate) fn screenshot_mismatch_paths(path: &Path) -> (PathBuf, PathBuf) {
365 let parent = path.parent().unwrap_or_else(|| Path::new("."));
366 let stem = path
367 .file_stem()
368 .and_then(|stem| stem.to_str())
369 .unwrap_or("screenshot");
370 let actual = parent.join(format!("{stem}.actual.png"));
371 let diff = parent.join(format!("{stem}.diff.png"));
372 (actual, diff)
373}
374
375pub(crate) fn semantics_overlay(base: &Screenshot, snapshot: &WindowSnapshot) -> Screenshot {
376 let mut overlay = base.clone();
377 for node in &snapshot.accessibility.nodes {
378 let color = if node.state.focused {
379 Color::rgba(1.0, 0.2, 0.2, 1.0)
380 } else {
381 Color::rgba(0.2, 1.0, 0.3, 1.0)
382 };
383 draw_rect_outline(&mut overlay, node.bounds, color);
384 }
385 overlay
386}
387
388pub(crate) fn widget_overlay(base: &Screenshot, snapshot: &WindowSnapshot) -> Screenshot {
389 let mut overlay = base.clone();
390 for node in &snapshot.widget_graph.nodes {
391 let color = if node.focused {
392 Color::rgba(1.0, 0.6, 0.1, 1.0)
393 } else {
394 Color::rgba(0.2, 0.6, 1.0, 1.0)
395 };
396 draw_rect_outline(&mut overlay, node.bounds, color);
397 }
398 overlay
399}
400
401fn format_summary(snapshot: &WindowSnapshot) -> String {
402 let mut lines = vec![
403 format!("window: {} ({})", snapshot.title, snapshot.window_id.get()),
404 format!(
405 "focus: {:?}",
406 snapshot.focus_state.focused_widget.map(|id| id.get())
407 ),
408 format!("semantics nodes: {}", snapshot.accessibility.nodes.len()),
409 format!("widget graph nodes: {}", snapshot.widget_graph.nodes.len()),
410 ];
411
412 if let Some(scene) = &snapshot.scene_summary {
413 lines.push(format!(
414 "scene: viewport=({}, {}), dirty_regions={}, commands={}",
415 scene.viewport.width,
416 scene.viewport.height,
417 scene.dirty_regions.len(),
418 scene.command_count
419 ));
420 }
421
422 lines.join("\n")
423}
424
425fn format_semantics(snapshot: &WindowSnapshot) -> String {
426 snapshot
427 .accessibility
428 .nodes
429 .iter()
430 .map(|node| {
431 format!(
432 "id={} parent={:?} role={:?} name={:?} description={:?} value={:?} bounds=({}, {}, {}, {}) focused={} hidden={}",
433 node.id.get(),
434 node.parent.map(|id| id.get()),
435 node.role,
436 node.name,
437 node.description,
438 node.value,
439 node.bounds.x(),
440 node.bounds.y(),
441 node.bounds.width(),
442 node.bounds.height(),
443 node.state.focused,
444 node.state.hidden,
445 )
446 })
447 .collect::<Vec<_>>()
448 .join("\n")
449}
450
451fn format_widget_graph(snapshot: &WindowSnapshot) -> String {
452 snapshot
453 .widget_graph
454 .nodes
455 .iter()
456 .map(|node| {
457 format!(
458 "id={} parent={:?} children={:?} bounds=({}, {}, {}, {}) focusable={} focused={}",
459 node.id.get(),
460 node.parent.map(|id| id.get()),
461 node.children.iter().map(|id| id.get()).collect::<Vec<_>>(),
462 node.bounds.x(),
463 node.bounds.y(),
464 node.bounds.width(),
465 node.bounds.height(),
466 node.accepts_focus,
467 node.focused,
468 )
469 })
470 .collect::<Vec<_>>()
471 .join("\n")
472}
473
474fn format_scene(scene: &crate::snapshot::SceneSummary) -> String {
475 format!(
476 "viewport=({}, {})\ndirty_regions={:?}\ncommand_count={}\ncommand_breakdown={:?}\n",
477 scene.viewport.width,
478 scene.viewport.height,
479 scene.dirty_regions,
480 scene.command_count,
481 scene.command_breakdown,
482 )
483}
484
485fn draw_rect_outline(image: &mut Screenshot, bounds: Rect, color: Color) {
486 let left = bounds.x().floor().max(0.0) as i32;
487 let top = bounds.y().floor().max(0.0) as i32;
488 let right = bounds.max_x().ceil().min(image.width as f32) as i32 - 1;
489 let bottom = bounds.max_y().ceil().min(image.height as f32) as i32 - 1;
490
491 if left > right || top > bottom {
492 return;
493 }
494
495 for x in left..=right {
496 blend_pixel(image, x, top, color);
497 blend_pixel(image, x, bottom, color);
498 }
499 for y in top..=bottom {
500 blend_pixel(image, left, y, color);
501 blend_pixel(image, right, y, color);
502 }
503}
504
505fn blend_pixel(image: &mut Screenshot, x: i32, y: i32, color: Color) {
506 if x < 0 || y < 0 || x >= image.width as i32 || y >= image.height as i32 {
507 return;
508 }
509
510 let offset = ((y as u32 * image.width + x as u32) * 4) as usize;
511 let overlay = [
512 (color.red * 255.0) as u8,
513 (color.green * 255.0) as u8,
514 (color.blue * 255.0) as u8,
515 (color.alpha * 255.0) as u8,
516 ];
517 let alpha = overlay[3] as f32 / 255.0;
518
519 for (channel, &over) in overlay.iter().take(3).enumerate() {
520 let base = image.pixels[offset + channel] as f32;
521 image.pixels[offset + channel] = ((base * (1.0 - alpha)) + (f32::from(over) * alpha)) as u8;
522 }
523 image.pixels[offset + 3] = 255;
524}
525
526fn pixel_at(image: &Screenshot, x: u32, y: u32) -> Option<[u8; 4]> {
527 if x >= image.width || y >= image.height {
528 return None;
529 }
530
531 let offset = ((y * image.width + x) * 4) as usize;
532 Some([
533 image.pixels[offset],
534 image.pixels[offset + 1],
535 image.pixels[offset + 2],
536 image.pixels[offset + 3],
537 ])
538}
539
540fn io_error(error: std::io::Error) -> Error {
541 Error::new(format!("I/O error: {error}"))
542}
543
544fn png_error<E>(error: E) -> Error
545where
546 E: std::fmt::Display,
547{
548 Error::new(format!("PNG error: {error}"))
549}
550
551fn avif_error<E>(error: E) -> Error
552where
553 E: std::fmt::Display,
554{
555 Error::new(format!("AVIF error: {error}"))
556}
557
558fn exr_error<E>(error: E) -> Error
559where
560 E: std::fmt::Display,
561{
562 Error::new(format!("EXR error: {error}"))
563}
564
565#[cfg(test)]
566mod tests {
567 use std::{
568 fs,
569 path::PathBuf,
570 time::{SystemTime, UNIX_EPOCH},
571 };
572
573 use super::{
574 HdrRgbaImage, Screenshot, diff_screenshot, hdr_clip_mask, hdr_headroom_heatmap,
575 hdr_luminance_heatmap, screenshots_match, write_hdr_avif,
576 };
577
578 #[test]
579 fn hdr_luminance_heatmap_returns_rgba8_image() {
580 let image = HdrRgbaImage::new(1, 1, vec![4.0, 2.0, 1.0, 1.0]).unwrap();
581 let heatmap = hdr_luminance_heatmap(&image).unwrap();
582 assert_eq!(heatmap.width(), 1);
583 assert_eq!(heatmap.height(), 1);
584 assert_eq!(heatmap.pixels().len(), 4);
585 assert_eq!(heatmap.pixels()[3], 255);
586 }
587
588 #[test]
589 fn hdr_headroom_heatmap_highlights_overbright_pixels() {
590 let image = HdrRgbaImage::new(1, 1, vec![2.0, 0.5, 0.5, 1.0]).unwrap();
591 let heatmap = hdr_headroom_heatmap(&image, 1.0).unwrap();
592 assert!(heatmap.pixels()[0] > heatmap.pixels()[2]);
593 }
594
595 #[test]
596 fn hdr_clip_mask_marks_pixels_above_threshold() {
597 let image = HdrRgbaImage::new(2, 1, vec![0.5, 0.5, 0.5, 1.0, 3.0, 0.0, 0.0, 1.0]).unwrap();
598 let mask = hdr_clip_mask(&image, 1.0).unwrap();
599 assert_eq!(&mask.pixels()[0..4], &[0, 0, 0, 255]);
600 assert_eq!(&mask.pixels()[4..8], &[255, 64, 64, 255]);
601 }
602
603 #[test]
604 fn screenshot_new_rejects_wrong_length() {
605 assert!(Screenshot::new(2, 2, vec![0; 4]).is_err());
606 }
607
608 #[test]
609 fn screenshot_from_hdr_linear_image_encodes_sdr_rgba() {
610 let image = HdrRgbaImage::new(
611 3,
612 1,
613 vec![
614 0.0,
615 0.0,
616 0.0,
617 1.0, 1.0,
619 1.0,
620 1.0,
621 0.5, 2.0,
623 0.25,
624 0.003_130_8,
625 -1.0,
626 ],
627 )
628 .unwrap();
629 let screenshot = Screenshot::from_hdr_linear_image(&image).unwrap();
630
631 assert_eq!(&screenshot.pixels()[0..4], &[0, 0, 0, 255]);
632 assert_eq!(&screenshot.pixels()[4..8], &[255, 255, 255, 128]);
633 assert_eq!(screenshot.pixels()[8], 255);
634 assert!(screenshot.pixels()[9] > screenshot.pixels()[10]);
635 assert_eq!(screenshot.pixels()[11], 0);
636 }
637
638 #[test]
639 fn screenshots_match_with_one_channel_value_tolerance() {
640 let expected = Screenshot::new(2, 1, vec![10, 20, 30, 40, 100, 110, 120, 130]).unwrap();
641 let actual = Screenshot::new(2, 1, vec![11, 19, 31, 39, 99, 111, 119, 131]).unwrap();
642
643 assert!(screenshots_match(&expected, &actual));
644 }
645
646 #[test]
647 fn screenshots_reject_channel_differences_above_tolerance() {
648 let expected = Screenshot::new(1, 1, vec![10, 20, 30, 40]).unwrap();
649 let actual = Screenshot::new(1, 1, vec![12, 20, 30, 40]).unwrap();
650
651 assert!(!screenshots_match(&expected, &actual));
652 }
653
654 #[test]
655 fn screenshot_diff_treats_one_channel_value_difference_as_matching() {
656 let expected = Screenshot::new(1, 1, vec![10, 20, 30, 40]).unwrap();
657 let actual = Screenshot::new(1, 1, vec![11, 19, 31, 39]).unwrap();
658
659 let diff = diff_screenshot(&expected, &actual).unwrap();
660
661 assert_eq!(diff.pixels(), &[5, 9, 15, 255]);
662 }
663
664 #[test]
665 fn screenshot_write_avif_creates_nonempty_file() {
666 let screenshot = Screenshot::new(2, 1, vec![255, 0, 0, 255, 0, 255, 0, 255]).unwrap();
667 let path = unique_test_path("screenshot-avif");
668
669 screenshot.write_avif(&path).unwrap();
670
671 let bytes = fs::read(&path).unwrap();
672 assert!(!bytes.is_empty());
673 assert_eq!(&bytes[4..8], b"ftyp");
674 }
675
676 #[test]
677 fn write_hdr_avif_emits_hdr_container_signaling() {
678 let image = HdrRgbaImage::new(2, 1, vec![4.0, 2.0, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0]).unwrap();
679 let path = unique_test_path("hdr-avif");
680
681 write_hdr_avif(&image, &path, 1.0).unwrap();
682
683 let bytes = fs::read(&path).unwrap();
684 assert!(!bytes.is_empty());
685 assert_eq!(&bytes[4..8], b"ftyp");
686 assert!(bytes.windows(4).any(|chunk| chunk == b"colr"));
687 assert!(bytes.windows(4).any(|chunk| chunk == b"clli"));
688 assert!(bytes.windows(4).any(|chunk| chunk == b"mdcv"));
689 }
690
691 fn unique_test_path(stem: &str) -> PathBuf {
692 let nanos = SystemTime::now()
693 .duration_since(UNIX_EPOCH)
694 .unwrap()
695 .as_nanos();
696 std::env::temp_dir().join(format!("{stem}-{nanos}.avif"))
697 }
698}