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