rosier 0.4.0

A fast picture and video viewer for large folders
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
//! Thumbnails: generate once (JPEG fast path, image crate fallback, libmpv for
//! video, AVIF, HEIC and JPEG XL), keep them in a disk cache, and hand BGRA
//! pixels to the UI.

use std::fs;
use std::io::Write as _;
use std::path::{Path, PathBuf};

use anyhow::{Result, bail};
use fast_image_resize::images::Image;
use fast_image_resize::{FilterType, PixelType, ResizeAlg, ResizeOptions, Resizer};

use crate::media::{Entry, Kind};
use crate::orient;
use crate::turbo::{self, Bgra};

/// Smallest side of the square grid thumbnails, used for tiles up to this
/// many pixels wide; larger tiles get 512 or 768 (see `side_for`).
pub const SQUARE_PX: u32 = 320;

fn cache_dir(side: u32) -> PathBuf {
    // Tests must not fill the user's own cache.
    #[cfg(test)]
    let base = std::env::temp_dir().join(format!("rosier-test-cache-{}", std::process::id()));
    #[cfg(not(test))]
    let base = std::env::var_os("XDG_CACHE_HOME")
        .map(PathBuf::from)
        .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache")))
        .unwrap_or_else(std::env::temp_dir);
    // "-v2": thumbnails since EXIF orientation is applied. Older ones may
    // be sideways, so they are not reused (see `remove_old_cache`).
    base.join("rosier").join(format!("square-{side}-v2"))
}

/// Deletes thumbnail folders from before EXIF orientation was applied.
pub fn remove_old_cache() {
    let Some(root) = cache_dir(SQUARE_PX).parent().map(Path::to_path_buf) else { return };
    for side in [SQUARE_PX, 512, 768] {
        let _ = fs::remove_dir_all(root.join(format!("square-{side}")));
    }
}

/// Caps how many non-JPEG images decode at once. PNGs cannot be decoded at
/// reduced size, and a burst of 32 full-size 8K PNGs took 7 GB of RAM.
struct Gate {
    busy: std::sync::Mutex<usize>,
    free: std::sync::Condvar,
}

static HEAVY: Gate = Gate { busy: std::sync::Mutex::new(0), free: std::sync::Condvar::new() };
const HEAVY_SLOTS: usize = 4;

struct Slot;

impl Gate {
    fn enter(&'static self) -> Slot {
        let mut n = self.busy.lock().unwrap_or_else(|e| e.into_inner());
        while *n >= HEAVY_SLOTS {
            n = self.free.wait(n).unwrap_or_else(|e| e.into_inner());
        }
        *n += 1;
        Slot
    }
}

impl Drop for Slot {
    fn drop(&mut self) {
        let mut n = HEAVY.busy.lock().unwrap_or_else(|e| e.into_inner());
        *n -= 1;
        HEAVY.free.notify_one();
    }
}

/// FNV-1a: stable across Rust versions, unlike `DefaultHasher`.
fn fnv1a(bytes: &[u8], mut h: u64) -> u64 {
    for b in bytes {
        h ^= *b as u64;
        h = h.wrapping_mul(0x100000001b3);
    }
    h
}

fn cache_path(e: &Entry, side: u32) -> PathBuf {
    let mut h = fnv1a(e.path.as_os_str().as_encoded_bytes(), 0xcbf29ce484222325);
    h = fnv1a(&e.size.to_le_bytes(), h);
    h = fnv1a(&e.mtime.to_le_bytes(), h);
    let name = format!("{h:016x}");
    cache_dir(side).join(&name[..2]).join(format!("{name}.jpg"))
}

/// Resizes BGRA pixels so the longer side is at most `max_long`.
pub fn fit(b: Bgra, max_long: u32) -> Result<Bgra> {
    let long = b.width.max(b.height);
    if long <= max_long {
        return Ok(b);
    }
    let scale = max_long as f64 / long as f64;
    let w = ((b.width as f64 * scale).round() as u32).max(1);
    let h = ((b.height as f64 * scale).round() as u32).max(1);
    let src = Image::from_vec_u8(b.width, b.height, b.pixels, PixelType::U8x4)?;
    let mut dst = Image::new(w, h, PixelType::U8x4);
    // Pixels are opaque, so skip alpha premultiplication.
    let opts = ResizeOptions::new().resize_alg(ResizeAlg::Convolution(FilterType::Bilinear)).use_alpha(false);
    Resizer::new().resize(&src, &mut dst, &opts)?;
    Ok(Bgra { width: w, height: h, pixels: dst.into_vec() })
}

fn decode_generic(data: &[u8]) -> Result<Bgra> {
    use image::ImageDecoder as _;
    // Sniff the bytes: files named .jpg are sometimes PNGs and vice versa.
    let mut decoder = image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format()?.into_decoder()?;
    let orientation = decoder.orientation().unwrap_or(image::metadata::Orientation::NoTransforms);
    let mut img = image::DynamicImage::from_decoder(decoder)?;
    img.apply_orientation(orientation);
    let img = img.into_rgba8();
    let (width, height) = img.dimensions();
    let mut pixels = img.into_raw();
    for px in pixels.as_chunks_mut::<4>().0 {
        px.swap(0, 2);
    }
    Ok(crate::icc::correct(data, Bgra { width, height, pixels }))
}

/// Decodes a JPEG at reduced size, turned upright. `min_long` is the
/// smallest long side wanted (see `turbo::decode_scaled`).
fn decode_jpeg(data: &[u8], min_long: u32) -> Result<Bgra> {
    let b = crate::icc::correct(data, turbo::decode_scaled(data, min_long)?);
    Ok(orient::apply(b, orient::jpeg_orientation(data)))
}

/// A picture decoded for the viewer, and its full upright size.
pub struct Decoded {
    /// The picture, or the first frame of an animation.
    pub image: Bgra,
    pub full: (u32, u32),
    /// Every frame of an animated GIF or WebP and how long it shows; empty
    /// for a still picture.
    pub frames: Vec<(Bgra, std::time::Duration)>,
}

/// Puts a checkerboard under the transparent parts of `b` (and leaves it
/// opaque), the usual sign of "nothing here": drawn straight on the black
/// stage, a logo or cut-out vanished into it. The squares are a fixed share
/// of the picture, so they look the same size whatever it is decoded at.
fn checker_under(b: &mut Bgra) {
    if !b.pixels.as_chunks::<4>().0.iter().any(|p| p[3] != 255) {
        return;
    }
    const LIGHT: u32 = 0x5a;
    const DARK: u32 = 0x40;
    let sq = (b.width.max(b.height) / 48).max(4);
    let w = b.width as usize;
    for (k, p) in b.pixels.as_chunks_mut::<4>().0.iter_mut().enumerate() {
        let a = u32::from(p[3]);
        if a == 255 {
            continue;
        }
        let (x, y) = ((k % w) as u32, (k / w) as u32);
        let bg = if ((x / sq) + (y / sq)).is_multiple_of(2) { LIGHT } else { DARK };
        for c in &mut p[..3] {
            *c = ((u32::from(*c) * a + bg * (255 - a)) / 255) as u8;
        }
        p[3] = 255;
    }
}

/// Decodes an image file so its longer side is at most `max_long`.
pub fn decode_image(e: &Entry, max_long: u32) -> Result<Decoded> {
    let mut d = decode_image_raw(e, max_long)?;
    if d.frames.is_empty() && may_be_transparent(e) {
        checker_under(&mut d.image);
    }
    Ok(d)
}

/// Whether a picture's format can hold transparency at all: JPEG, camera
/// RAW and what mpv decodes come out opaque, so their pixels are not
/// looked at.
fn may_be_transparent(e: &Entry) -> bool {
    let ext = crate::media::ext_lower(&e.path).unwrap_or_default();
    !(e.decoded_by_mpv()
        || matches!(ext.as_str(), "jpg" | "jpeg" | "jpe" | "jfif")
        || crate::formats::RAW.contains(&ext.as_str()))
}

fn decode_image_raw(e: &Entry, max_long: u32) -> Result<Decoded> {
    if e.decoded_by_mpv() {
        let _slot = HEAVY.enter();
        let (image, full) = crate::mpv::grab(&e.path, "0", max_long, true)?;
        return Ok(Decoded { image, full, frames: Vec::new() });
    }
    let data = crate::book::read(&e.path)?;
    if data.is_empty() {
        bail!("empty file");
    }
    if data.starts_with(&[0xFF, 0xD8])
        && let Ok((w, h)) = turbo::dimensions(&data)
        && let Ok(b) = decode_jpeg(&data, max_long)
    {
        // Orientations 5 to 8 turn the picture a quarter.
        let full = if orient::jpeg_orientation(&data) >= 5 { (h, w) } else { (w, h) };
        return Ok(Decoded { image: fit(b, max_long)?, full, frames: Vec::new() });
    }
    if let Some(b) = decode_other(e, &data, max_long) {
        let b = b?;
        let full = (b.width, b.height);
        return Ok(Decoded { image: fit(b, max_long)?, full, frames: Vec::new() });
    }
    if crate::formats::is_webp(&data)
        && let Some(r) = crate::formats::decode_webp(&data, max_long)
    {
        let (b, full) = r?;
        let b = crate::icc::correct(&data, b);
        return Ok(Decoded { image: fit(b, max_long)?, full, frames: Vec::new() });
    }
    let _slot = HEAVY.enter();
    if let Ok(Some(a)) = crate::anim::decode(&data, max_long) {
        return Ok(Decoded { image: a.frames[0].0.clone(), full: a.full, frames: a.frames });
    }
    let b = decode_generic(&data)?;
    let full = (b.width, b.height);
    Ok(Decoded { image: fit(b, max_long)?, full, frames: Vec::new() })
}

/// Cuts the part `n` ([x0, y0, x1, y1] as fractions) out of `b` and scales
/// it to `size`, in one pass.
pub fn cut(b: &Bgra, n: [f32; 4], size: (u32, u32), nearest: bool) -> Result<Bgra> {
    let (w, h) = (b.width as f64, b.height as f64);
    let (x0, y0) = (n[0] as f64 * w, n[1] as f64 * h);
    let (cw, ch) = ((n[2] - n[0]) as f64 * w, (n[3] - n[1]) as f64 * h);
    // The resizer takes the source by value; the pixels are borrowed.
    let src = fast_image_resize::images::ImageRef::new(b.width, b.height, &b.pixels, PixelType::U8x4)?;
    let mut dst = Image::new(size.0.max(1), size.1.max(1), PixelType::U8x4);
    let opts = ResizeOptions::new()
        .resize_alg(if nearest { ResizeAlg::Nearest } else { ResizeAlg::Convolution(FilterType::Bilinear) })
        .use_alpha(false)
        .crop(x0, y0, cw, ch);
    Resizer::new().resize(&src, &mut dst, &opts)?;
    Ok(Bgra { width: dst.width(), height: dst.height(), pixels: dst.into_vec() })
}

/// Center-crops to a square and scales it to `side`.
pub fn square(b: Bgra, side: u32) -> Result<Bgra> {
    let short = b.width.min(b.height).max(1);
    let (x0, y0) = ((b.width - short) / 2, (b.height - short) / 2);
    let mut crop = Vec::with_capacity((short * short * 4) as usize);
    for y in y0..y0 + short {
        let row = (y * b.width + x0) as usize * 4;
        crop.extend_from_slice(&b.pixels[row..row + short as usize * 4]);
    }
    if short <= side {
        return Ok(Bgra { width: short, height: short, pixels: crop });
    }
    fit(Bgra { width: short, height: short, pixels: crop }, side)
}

/// Decodes so the *shorter* side is at least `side`, for square crops.
fn decode_for_square(e: &Entry, side: u32) -> Result<Bgra> {
    if e.decoded_by_mpv() {
        return crate::mpv::grab_frame(&e.path, "0", side * 2);
    }
    let data = crate::book::read(&e.path)?;
    if data.is_empty() {
        bail!("empty file");
    }
    if data.starts_with(&[0xFF, 0xD8])
        && let Ok((w, h)) = turbo::dimensions(&data)
    {
        let (long, short) = (w.max(h).max(1), w.min(h).max(1));
        let min_long = (side as u64 * long as u64).div_ceil(short as u64) as u32;
        if let Ok(b) = decode_jpeg(&data, min_long) {
            return Ok(b);
        }
    }
    if let Some(b) = decode_other(e, &data, side * 2) {
        return b;
    }
    if crate::formats::is_webp(&data)
        && let Some(r) = crate::formats::decode_webp(&data, side * 2)
    {
        return r.map(|(b, _)| crate::icc::correct(&data, b));
    }
    let _slot = HEAVY.enter();
    decode_generic(&data)
}

/// SVG, camera raw and Photoshop files, by extension (None for others).
/// `min_long` is the long side wanted: SVGs are drawn at it, and a raw
/// file's JPEG preview is decoded at reduced size when that is enough.
fn decode_other(e: &Entry, data: &[u8], min_long: u32) -> Option<Result<Bgra>> {
    use crate::formats;
    let ext = crate::media::ext_lower(&e.path)?;
    Some(match ext.as_str() {
        "svg" => formats::decode_svg(data, min_long),
        "psd" => {
            let _slot = HEAVY.enter();
            formats::decode_psd(data)
        }
        e if formats::RAW.contains(&e) => match formats::raw_preview(data) {
            Some((jpeg, raw_orientation)) => {
                // The preview's own EXIF tag wins; many previews have none
                // and the raw file's tag says how to turn them.
                let o = match orient::jpeg_orientation(jpeg) {
                    1 => raw_orientation,
                    o => o,
                };
                turbo::decode_scaled(jpeg, min_long).map(|b| orient::apply(b, o))
            }
            None => Err(anyhow::anyhow!("no preview in the raw file")),
        },
        _ => return None,
    })
}

fn generate(e: &Entry, side: u32) -> Result<Bgra> {
    let full = match e.kind {
        Kind::Image => {
            let mut b = decode_for_square(e, side)?;
            if may_be_transparent(e) {
                checker_under(&mut b);
            }
            b
        }
        // 10% in skips most intros and title cards; very short or odd files
        // fall back to the first frame. Twice the side on the long edge keeps
        // the short edge above `side` for anything up to 2:1.
        Kind::Video => crate::mpv::grab_frame(&e.path, "10%", side * 2)
            .or_else(|_| crate::mpv::grab_frame(&e.path, "0", side * 2))?,
        // A book's tile is its cover.
        Kind::Book => {
            let pages = crate::book::pages(&e.path)?;
            let cover = crate::book::page_entry(e, pages.first().map_or("", String::as_str));
            decode_for_square(&cover, side)?
        }
    };
    square(full, side)
}

fn write_cache(path: &Path, jpeg: &[u8]) -> Result<()> {
    if let Some(dir) = path.parent() {
        fs::create_dir_all(dir)?;
    }
    let tmp = path.with_extension("tmp");
    fs::File::create(&tmp)?.write_all(jpeg)?;
    fs::rename(tmp, path)?;
    Ok(())
}

/// The cached thumbnail, if there is one. Cheap: one small JPEG decode.
pub fn cached(e: &Entry, side: u32) -> Option<Bgra> {
    let data = fs::read(cache_path(e, side)).ok()?;
    turbo::decode_scaled(&data, u32::MAX).ok()
}

/// Generates a thumbnail and stores it in the cache.
pub fn make(e: &Entry, side: u32) -> Result<Bgra> {
    let b = generate(e, side)?;
    let jpeg = turbo::encode(&b, 82)?;
    // A failed cache write only costs speed next time.
    let _ = write_cache(&cache_path(e, side), &jpeg);
    Ok(b)
}

/// Whether making a thumbnail for `e` is slow or memory-hungry (video, or
/// an image format that cannot be decoded at reduced size).
pub fn is_heavy(e: &Entry) -> bool {
    e.kind == Kind::Video || !e.is_jpeg()
}

/// Square thumbnail size for tiles `tile_px` physical pixels wide.
pub fn side_for(tile_px: f32) -> u32 {
    if tile_px <= SQUARE_PX as f32 {
        SQUARE_PX
    } else if tile_px <= 512.0 {
        512
    } else {
        768
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn transparent_parts_get_a_checkerboard_and_opaque_pictures_stay() {
        // 96x2: left half clear, right half opaque red, one pixel half see-through.
        let mut px = Vec::new();
        for x in 0..96u32 {
            for _ in 0..1 {
                px.extend_from_slice(if x < 48 { &[0, 0, 0, 0] } else { &[0, 0, 255, 255] });
            }
        }
        px.extend(px.clone());
        px[50 * 4..50 * 4 + 4].copy_from_slice(&[0, 0, 255, 128]);
        let mut b = Bgra { width: 96, height: 2, pixels: px };
        checker_under(&mut b);
        let at = |x: usize| &b.pixels[x * 4..x * 4 + 4];
        assert!(b.pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255), "opaque afterwards");
        // Squares of 96/48 = 2, at least 4 px: light at 0..4, dark at 4..8.
        assert_eq!(at(0), &[0x5a, 0x5a, 0x5a, 255]);
        assert_eq!(at(4), &[0x40, 0x40, 0x40, 255]);
        assert_eq!(at(60), &[0, 0, 255, 255], "opaque pixels untouched");
        assert!(at(50)[2] > 0x80 && at(50)[0] < 0x40, "half see-through red over the board: {:?}", at(50));
        let mut opaque = Bgra { width: 1, height: 1, pixels: vec![1, 2, 3, 255] };
        checker_under(&mut opaque);
        assert_eq!(opaque.pixels, vec![1, 2, 3, 255]);
    }

    use super::*;

    #[test]
    fn square_crops_the_center_and_scales_down() {
        // 8x4 image: left half black, right half white.
        let mut pixels = Vec::new();
        for _y in 0..4 {
            for x in 0..8 {
                let v = if x < 4 { 0 } else { 255 };
                pixels.extend_from_slice(&[v, v, v, 255]);
            }
        }
        let s = square(Bgra { width: 8, height: 4, pixels }, 2).unwrap();
        assert_eq!((s.width, s.height), (2, 2));
        // The center 4x4 is half black, half white.
        assert!(s.pixels[0] < 128 && s.pixels[4] > 128);
    }

    #[test]
    fn small_images_are_not_upscaled() {
        let s = square(Bgra { width: 3, height: 5, pixels: vec![9; 3 * 5 * 4] }, 320).unwrap();
        assert_eq!((s.width, s.height), (3, 3));
    }
}

#[cfg(test)]
mod orientation_tests {
    use super::*;
    use crate::library::tests::entry;

    /// A real JPEG, `w`x`h`, carrying EXIF orientation `o`.
    fn rotated_jpeg(path: &Path, w: u32, h: u32, o: u16) {
        let img = image::RgbImage::from_fn(w, h, |x, _| image::Rgb([if x < w / 2 { 0 } else { 255 }; 3]));
        let mut jpeg = Vec::new();
        image::codecs::jpeg::JpegEncoder::new(&mut jpeg).encode_image(&img).unwrap();
        let exif = crate::orient::tests::exif_jpeg(o, true);
        // Splice the EXIF segment (after its fake SOI and APP0) in after SOI.
        let app1 = exif.windows(2).position(|p| p == [0xFF, 0xE1]).unwrap();
        let sos = exif.windows(2).position(|p| p == [0xFF, 0xDA]).unwrap();
        let mut out = jpeg[..2].to_vec();
        out.extend(&exif[app1..sos]);
        out.extend(&jpeg[2..]);
        std::fs::write(path, out).unwrap();
    }

    #[test]
    fn portrait_photos_stand_upright_in_the_viewer_and_the_grid() {
        let dir = std::env::temp_dir().join(format!("rosier-orient-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("phone.jpg");
        // Stored 64x32 landscape, tagged "turn 90° clockwise".
        rotated_jpeg(&path, 64, 32, 6);
        let e = entry(1, path.to_str().unwrap(), Kind::Image, 1, 1);
        let d = decode_image(&e, 1000).unwrap();
        assert_eq!((d.image.width, d.image.height), (32, 64));
        assert_eq!(d.full, (32, 64));
        // The left half (black) is now on top.
        assert!(d.image.pixels[0] < 60);
        assert!(d.image.pixels[d.image.pixels.len() - 4] > 190);
        let t = generate(&e, 16).unwrap();
        assert_eq!((t.width, t.height), (16, 16));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn avif_heic_and_jpeg_xl_decode_through_libmpv() {
        if !crate::mpv::available() {
            eprintln!("libmpv not found: skipped");
            return;
        }
        let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
        for name in ["still.avif", "still.heic", "still.jxl"] {
            let path = fixtures.join(name);
            let e = entry(1, path.to_str().unwrap(), Kind::Image, 1, 1);
            assert!(e.decoded_by_mpv(), "{name}");
            match decode_image(&e, 48) {
                Ok(d) => {
                    assert_eq!((d.image.width, d.image.height, d.full), (48, 32, (96, 64)), "{name}");
                    let t = generate(&e, 16).unwrap();
                    assert_eq!((t.width, t.height), (16, 16), "{name}");
                }
                // HEIF arrived in FFmpeg 7; an older libmpv cannot read it,
                // and the tile shows as unreadable.
                Err(err) if name == "still.heic" => eprintln!("{name}: {err:#} (older FFmpeg)"),
                Err(err) => panic!("{name}: {err:#}"),
            }
        }
    }

    /// How far `b` is from the reference picture tests/fixtures/still.png,
    /// as the mean difference per channel (0 to 255).
    fn off_reference(b: &Bgra) -> f64 {
        let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
        let want = decode_generic(&std::fs::read(fixtures.join("still.png")).unwrap()).unwrap();
        assert_eq!((b.width, b.height), (want.width, want.height));
        let sum: u64 = b
            .pixels
            .as_chunks::<4>()
            .0
            .iter()
            .zip(want.pixels.as_chunks::<4>().0)
            .map(|(p, q)| (0..3).map(|c| p[c].abs_diff(q[c]) as u64).sum::<u64>())
            .sum();
        sum as f64 / (b.width * b.height * 3) as f64
    }

    #[test]
    fn svg_psd_and_raw_previews_match_the_reference_picture() {
        let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
        // A raw file around a JPEG of the reference, turned a quarter by
        // the raw file's orientation tag (as cameras record portraits).
        let dir = std::env::temp_dir().join(format!("rosier-formats-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let reference = decode_generic(&std::fs::read(fixtures.join("still.png")).unwrap()).unwrap();
        let turned = orient::apply(reference, 8);
        let jpeg = turbo::encode(&turned, 95).unwrap();
        let raw = crate::formats::tests::tiff(
            &[(0x0112, 3, 1, 6), (0x0201, 4, 1, u32::MAX), (0x0202, 4, 1, jpeg.len() as u32)],
            &[],
            &[jpeg],
        );
        std::fs::write(dir.join("still.nef"), raw).unwrap();
        let cases =
            [(fixtures.join("still.svg"), 1.0), (fixtures.join("still.psd"), 0.0), (dir.join("still.nef"), 3.0)];
        for (path, tolerance) in cases {
            let e = entry(1, path.to_str().unwrap(), Kind::Image, 1, 1);
            let d = decode_image(&e, 96).unwrap_or_else(|err| panic!("{}: {err:#}", path.display()));
            assert_eq!(d.full, (96, 64), "{}", path.display());
            let off = off_reference(&d.image);
            assert!(off <= tolerance, "{}: {off:.2} off the reference", path.display());
            let t = generate(&e, 16).unwrap();
            assert_eq!((t.width, t.height), (16, 16), "{}", path.display());
        }
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn animated_gifs_keep_every_frame() {
        let dir = std::env::temp_dir().join(format!("rosier-anim-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("loop.gif");
        std::fs::write(&path, crate::anim::tests::gif(4, 60, 30, 8)).unwrap();
        let e = entry(1, path.to_str().unwrap(), Kind::Image, 1, 1);
        let d = decode_image(&e, 30).unwrap();
        assert_eq!((d.frames.len(), d.full), (4, (60, 30)));
        assert_eq!((d.image.width, d.image.height), (30, 15), "the first frame stands for it");
        // The grid shows the first frame.
        assert_eq!(generate(&e, 16).unwrap().width, 16);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn other_formats_decode_upright_too() {
        let dir = std::env::temp_dir().join(format!("rosier-orient-png-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("plain.png");
        image::RgbImage::new(40, 20).save(&path).unwrap();
        let e = entry(1, path.to_str().unwrap(), Kind::Image, 1, 1);
        let d = decode_image(&e, 10).unwrap();
        assert_eq!((d.image.width, d.image.height, d.full), (10, 5, (40, 20)));
        let _ = std::fs::remove_dir_all(&dir);
    }
}