Skip to main content

sui_testing/
screenshot.rs

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().as_chunks::<4>().0 {
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().as_chunks::<4>().0 {
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().as_chunks::<4>().0 {
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().as_chunks::<4>().0 {
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            .as_chunks::<4>()
348            .0
349            .iter()
350            .zip(actual.pixels.as_chunks::<4>().0.iter())
351            .all(|(expected, actual)| {
352                rgba_channels_match(
353                    [expected[0], expected[1], expected[2], expected[3]],
354                    [actual[0], actual[1], actual[2], actual[3]],
355                )
356            })
357}
358
359fn rgba_channels_match(expected: [u8; 4], actual: [u8; 4]) -> bool {
360    expected
361        .into_iter()
362        .zip(actual)
363        .all(|(expected, actual)| expected.abs_diff(actual) <= SCREENSHOT_CHANNEL_TOLERANCE)
364}
365
366pub(crate) fn screenshot_mismatch_paths(path: &Path) -> (PathBuf, PathBuf) {
367    let parent = path.parent().unwrap_or_else(|| Path::new("."));
368    let stem = path
369        .file_stem()
370        .and_then(|stem| stem.to_str())
371        .unwrap_or("screenshot");
372    let actual = parent.join(format!("{stem}.actual.png"));
373    let diff = parent.join(format!("{stem}.diff.png"));
374    (actual, diff)
375}
376
377pub(crate) fn semantics_overlay(base: &Screenshot, snapshot: &WindowSnapshot) -> Screenshot {
378    let mut overlay = base.clone();
379    for node in &snapshot.accessibility.nodes {
380        let color = if node.state.focused {
381            Color::rgba(1.0, 0.2, 0.2, 1.0)
382        } else {
383            Color::rgba(0.2, 1.0, 0.3, 1.0)
384        };
385        draw_rect_outline(&mut overlay, node.bounds, color);
386    }
387    overlay
388}
389
390pub(crate) fn widget_overlay(base: &Screenshot, snapshot: &WindowSnapshot) -> Screenshot {
391    let mut overlay = base.clone();
392    for node in &snapshot.widget_graph.nodes {
393        let color = if node.focused {
394            Color::rgba(1.0, 0.6, 0.1, 1.0)
395        } else {
396            Color::rgba(0.2, 0.6, 1.0, 1.0)
397        };
398        draw_rect_outline(&mut overlay, node.bounds, color);
399    }
400    overlay
401}
402
403fn format_summary(snapshot: &WindowSnapshot) -> String {
404    let mut lines = vec![
405        format!("window: {} ({})", snapshot.title, snapshot.window_id.get()),
406        format!(
407            "focus: {:?}",
408            snapshot.focus_state.focused_widget.map(|id| id.get())
409        ),
410        format!("semantics nodes: {}", snapshot.accessibility.nodes.len()),
411        format!("widget graph nodes: {}", snapshot.widget_graph.nodes.len()),
412    ];
413
414    if let Some(scene) = &snapshot.scene_summary {
415        lines.push(format!(
416            "scene: viewport=({}, {}), dirty_regions={}, commands={}",
417            scene.viewport.width,
418            scene.viewport.height,
419            scene.dirty_regions.len(),
420            scene.command_count
421        ));
422    }
423
424    lines.join("\n")
425}
426
427fn format_semantics(snapshot: &WindowSnapshot) -> String {
428    snapshot
429        .accessibility
430        .nodes
431        .iter()
432        .map(|node| {
433            format!(
434                "id={} parent={:?} role={:?} name={:?} description={:?} value={:?} bounds=({}, {}, {}, {}) focused={} hidden={}",
435                node.id.get(),
436                node.parent.map(|id| id.get()),
437                node.role,
438                node.name,
439                node.description,
440                node.value,
441                node.bounds.x(),
442                node.bounds.y(),
443                node.bounds.width(),
444                node.bounds.height(),
445                node.state.focused,
446                node.state.hidden,
447            )
448        })
449        .collect::<Vec<_>>()
450        .join("\n")
451}
452
453fn format_widget_graph(snapshot: &WindowSnapshot) -> String {
454    snapshot
455        .widget_graph
456        .nodes
457        .iter()
458        .map(|node| {
459            format!(
460                "id={} parent={:?} children={:?} bounds=({}, {}, {}, {}) focusable={} focused={}",
461                node.id.get(),
462                node.parent.map(|id| id.get()),
463                node.children.iter().map(|id| id.get()).collect::<Vec<_>>(),
464                node.bounds.x(),
465                node.bounds.y(),
466                node.bounds.width(),
467                node.bounds.height(),
468                node.accepts_focus,
469                node.focused,
470            )
471        })
472        .collect::<Vec<_>>()
473        .join("\n")
474}
475
476fn format_scene(scene: &crate::snapshot::SceneSummary) -> String {
477    format!(
478        "viewport=({}, {})\ndirty_regions={:?}\ncommand_count={}\ncommand_breakdown={:?}\n",
479        scene.viewport.width,
480        scene.viewport.height,
481        scene.dirty_regions,
482        scene.command_count,
483        scene.command_breakdown,
484    )
485}
486
487fn draw_rect_outline(image: &mut Screenshot, bounds: Rect, color: Color) {
488    let left = bounds.x().floor().max(0.0) as i32;
489    let top = bounds.y().floor().max(0.0) as i32;
490    let right = bounds.max_x().ceil().min(image.width as f32) as i32 - 1;
491    let bottom = bounds.max_y().ceil().min(image.height as f32) as i32 - 1;
492
493    if left > right || top > bottom {
494        return;
495    }
496
497    for x in left..=right {
498        blend_pixel(image, x, top, color);
499        blend_pixel(image, x, bottom, color);
500    }
501    for y in top..=bottom {
502        blend_pixel(image, left, y, color);
503        blend_pixel(image, right, y, color);
504    }
505}
506
507fn blend_pixel(image: &mut Screenshot, x: i32, y: i32, color: Color) {
508    if x < 0 || y < 0 || x >= image.width as i32 || y >= image.height as i32 {
509        return;
510    }
511
512    let offset = ((y as u32 * image.width + x as u32) * 4) as usize;
513    let overlay = [
514        (color.red * 255.0) as u8,
515        (color.green * 255.0) as u8,
516        (color.blue * 255.0) as u8,
517        (color.alpha * 255.0) as u8,
518    ];
519    let alpha = overlay[3] as f32 / 255.0;
520
521    for (channel, &over) in overlay.iter().take(3).enumerate() {
522        let base = image.pixels[offset + channel] as f32;
523        image.pixels[offset + channel] = ((base * (1.0 - alpha)) + (f32::from(over) * alpha)) as u8;
524    }
525    image.pixels[offset + 3] = 255;
526}
527
528fn pixel_at(image: &Screenshot, x: u32, y: u32) -> Option<[u8; 4]> {
529    if x >= image.width || y >= image.height {
530        return None;
531    }
532
533    let offset = ((y * image.width + x) * 4) as usize;
534    Some([
535        image.pixels[offset],
536        image.pixels[offset + 1],
537        image.pixels[offset + 2],
538        image.pixels[offset + 3],
539    ])
540}
541
542fn io_error(error: std::io::Error) -> Error {
543    Error::new(format!("I/O error: {error}"))
544}
545
546fn png_error<E>(error: E) -> Error
547where
548    E: std::fmt::Display,
549{
550    Error::new(format!("PNG error: {error}"))
551}
552
553fn avif_error<E>(error: E) -> Error
554where
555    E: std::fmt::Display,
556{
557    Error::new(format!("AVIF error: {error}"))
558}
559
560fn exr_error<E>(error: E) -> Error
561where
562    E: std::fmt::Display,
563{
564    Error::new(format!("EXR error: {error}"))
565}
566
567#[cfg(test)]
568mod tests {
569    use std::{
570        fs,
571        path::PathBuf,
572        time::{SystemTime, UNIX_EPOCH},
573    };
574
575    use super::{
576        HdrRgbaImage, Screenshot, diff_screenshot, hdr_clip_mask, hdr_headroom_heatmap,
577        hdr_luminance_heatmap, screenshots_match, write_hdr_avif,
578    };
579
580    #[test]
581    fn hdr_luminance_heatmap_returns_rgba8_image() {
582        let image = HdrRgbaImage::new(1, 1, vec![4.0, 2.0, 1.0, 1.0]).unwrap();
583        let heatmap = hdr_luminance_heatmap(&image).unwrap();
584        assert_eq!(heatmap.width(), 1);
585        assert_eq!(heatmap.height(), 1);
586        assert_eq!(heatmap.pixels().len(), 4);
587        assert_eq!(heatmap.pixels()[3], 255);
588    }
589
590    #[test]
591    fn hdr_headroom_heatmap_highlights_overbright_pixels() {
592        let image = HdrRgbaImage::new(1, 1, vec![2.0, 0.5, 0.5, 1.0]).unwrap();
593        let heatmap = hdr_headroom_heatmap(&image, 1.0).unwrap();
594        assert!(heatmap.pixels()[0] > heatmap.pixels()[2]);
595    }
596
597    #[test]
598    fn hdr_clip_mask_marks_pixels_above_threshold() {
599        let image = HdrRgbaImage::new(2, 1, vec![0.5, 0.5, 0.5, 1.0, 3.0, 0.0, 0.0, 1.0]).unwrap();
600        let mask = hdr_clip_mask(&image, 1.0).unwrap();
601        assert_eq!(&mask.pixels()[0..4], &[0, 0, 0, 255]);
602        assert_eq!(&mask.pixels()[4..8], &[255, 64, 64, 255]);
603    }
604
605    #[test]
606    fn screenshot_new_rejects_wrong_length() {
607        assert!(Screenshot::new(2, 2, vec![0; 4]).is_err());
608    }
609
610    #[test]
611    fn screenshot_from_hdr_linear_image_encodes_sdr_rgba() {
612        let image = HdrRgbaImage::new(
613            3,
614            1,
615            vec![
616                0.0,
617                0.0,
618                0.0,
619                1.0, //
620                1.0,
621                1.0,
622                1.0,
623                0.5, //
624                2.0,
625                0.25,
626                0.003_130_8,
627                -1.0,
628            ],
629        )
630        .unwrap();
631        let screenshot = Screenshot::from_hdr_linear_image(&image).unwrap();
632
633        assert_eq!(&screenshot.pixels()[0..4], &[0, 0, 0, 255]);
634        assert_eq!(&screenshot.pixels()[4..8], &[255, 255, 255, 128]);
635        assert_eq!(screenshot.pixels()[8], 255);
636        assert!(screenshot.pixels()[9] > screenshot.pixels()[10]);
637        assert_eq!(screenshot.pixels()[11], 0);
638    }
639
640    #[test]
641    fn screenshots_match_with_one_channel_value_tolerance() {
642        let expected = Screenshot::new(2, 1, vec![10, 20, 30, 40, 100, 110, 120, 130]).unwrap();
643        let actual = Screenshot::new(2, 1, vec![11, 19, 31, 39, 99, 111, 119, 131]).unwrap();
644
645        assert!(screenshots_match(&expected, &actual));
646    }
647
648    #[test]
649    fn screenshots_reject_channel_differences_above_tolerance() {
650        let expected = Screenshot::new(1, 1, vec![10, 20, 30, 40]).unwrap();
651        let actual = Screenshot::new(1, 1, vec![12, 20, 30, 40]).unwrap();
652
653        assert!(!screenshots_match(&expected, &actual));
654    }
655
656    #[test]
657    fn screenshot_diff_treats_one_channel_value_difference_as_matching() {
658        let expected = Screenshot::new(1, 1, vec![10, 20, 30, 40]).unwrap();
659        let actual = Screenshot::new(1, 1, vec![11, 19, 31, 39]).unwrap();
660
661        let diff = diff_screenshot(&expected, &actual).unwrap();
662
663        assert_eq!(diff.pixels(), &[5, 9, 15, 255]);
664    }
665
666    #[test]
667    fn screenshot_write_avif_creates_nonempty_file() {
668        let screenshot = Screenshot::new(2, 1, vec![255, 0, 0, 255, 0, 255, 0, 255]).unwrap();
669        let path = unique_test_path("screenshot-avif");
670
671        screenshot.write_avif(&path).unwrap();
672
673        let bytes = fs::read(&path).unwrap();
674        assert!(!bytes.is_empty());
675        assert_eq!(&bytes[4..8], b"ftyp");
676    }
677
678    #[test]
679    fn write_hdr_avif_emits_hdr_container_signaling() {
680        let image = HdrRgbaImage::new(2, 1, vec![4.0, 2.0, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0]).unwrap();
681        let path = unique_test_path("hdr-avif");
682
683        write_hdr_avif(&image, &path, 1.0).unwrap();
684
685        let bytes = fs::read(&path).unwrap();
686        assert!(!bytes.is_empty());
687        assert_eq!(&bytes[4..8], b"ftyp");
688        assert!(bytes.windows(4).any(|chunk| chunk == b"colr"));
689        assert!(bytes.windows(4).any(|chunk| chunk == b"clli"));
690        assert!(bytes.windows(4).any(|chunk| chunk == b"mdcv"));
691    }
692
693    fn unique_test_path(stem: &str) -> PathBuf {
694        let nanos = SystemTime::now()
695            .duration_since(UNIX_EPOCH)
696            .unwrap()
697            .as_nanos();
698        std::env::temp_dir().join(format!("{stem}-{nanos}.avif"))
699    }
700}