otf-pixels-core 0.5.0

Core engine for otf-pixels: op graph, descriptors, tiles, codec traits, evaluator.
Documentation
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
//! Container formats and the codec traits every format plugs in behind.
//!
//! Every format is implemented in this workspace (ADR-0004, then ADR-0013,
//! ADR-0014 and ADR-0018), and that is invisible here on purpose: everything
//! sits behind [`Decoder`] and [`Encoder`], so a format can be rewritten
//! without an API change.

use crate::{
    ImageDescriptor, Orientation, PixelFormat, PixelsError, Region, Result, Sink, TileMut,
};
use core::fmt;

/// A container format.
///
/// Format is **data**, not a type parameter: `output(format, options)` is the
/// single encode terminal, which keeps the API surface stable as formats are
/// added and maps cleanly onto host bindings (ADR-0006). Formats not yet
/// implemented are still nameable, so an unsupported request is a catchable
/// [`PixelsError::Unsupported`] rather than a compile error in a host binding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Format {
    /// Uncompressed pixels described entirely by the caller.
    Raw,
    /// Portable Network Graphics.
    Png,
    /// JPEG.
    Jpeg,
    /// Graphics Interchange Format.
    Gif,
    /// Tagged Image File Format.
    Tiff,
    /// WebP.
    WebP,
    /// AV1 Image File Format.
    Avif,
    /// JPEG XL.
    Jxl,
}

impl Format {
    /// A short, stable, lowercase name for this format.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Raw => "raw",
            Self::Png => "png",
            Self::Jpeg => "jpeg",
            Self::Gif => "gif",
            Self::Tiff => "tiff",
            Self::WebP => "webp",
            Self::Avif => "avif",
            Self::Jxl => "jxl",
        }
    }
}

impl fmt::Display for Format {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// What a decoder can produce without a full decode.
///
/// The scheduler uses this to decide whether it may request arbitrary regions
/// from a source or must pull rows in order (ARCHITECTURE §Layer 2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DecodeCapability {
    /// Emits rows in top-to-bottom order as bytes arrive.
    ///
    /// Out-of-order region requests are not supported; the engine reads
    /// forward. This covers non-interlaced PNG, baseline JPEG, GIF frames,
    /// strip TIFF and raw.
    Sequential,
    /// Can produce an arbitrary region without decoding the whole image.
    ///
    /// This covers tiled TIFF, and is what makes the giant-image thumbnail
    /// path constant-memory.
    ///
    /// A JPEG decoding at a reduced `M/8` scale is *not* this, though an
    /// earlier version of this comment said it was: scaled decode lowers the
    /// resolution but still emits rows in order, and every coefficient is
    /// still entropy-decoded. It is a decoder configuration, not a capability,
    /// and claiming otherwise would be a lie the scheduler acts on.
    Regions,
}

/// How an animated image plays: its frames and their timing.
///
/// Reported by [`Decoder::animation`] for a file with more than one frame.
/// The pipeline processes the first frame; this describes the source, so a
/// caller can see it is animated and decide what to do (pass it through,
/// refuse it, or take the still).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Animation {
    /// Frames in the animation, always two or more.
    pub frame_count: u32,
    /// How many times it plays; 0 means forever, as in GIF and WebP.
    pub loop_count: u32,
    /// How long each frame shows, in milliseconds, in order.
    pub frame_durations_ms: Vec<u32>,
}

impl Animation {
    /// An animation of the given frame durations, playing `loop_count`
    /// times (0 for forever). `None` for fewer than two frames, which is a
    /// still image.
    #[must_use]
    pub fn new(frame_durations_ms: Vec<u32>, loop_count: u32) -> Option<Self> {
        let frame_count = u32::try_from(frame_durations_ms.len()).ok()?;
        (frame_count >= 2).then_some(Self {
            frame_count,
            loop_count,
            frame_durations_ms,
        })
    }

    /// The total time one play-through takes, in milliseconds.
    #[must_use]
    pub fn duration_ms(&self) -> u64 {
        self.frame_durations_ms.iter().map(|&d| u64::from(d)).sum()
    }
}

/// Header-only facts about an image.
///
/// Answering this must not decode pixels (SPEC §Guarantees 3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Metadata {
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
    /// The container format the image was read from.
    pub format: Format,
    /// The pixel format the decoder will produce.
    pub pixel: PixelFormat,
}

impl Metadata {
    /// Build metadata from a decoded header descriptor and its container.
    #[must_use]
    pub const fn new(desc: &ImageDescriptor, format: Format) -> Self {
        Self {
            width: desc.width,
            height: desc.height,
            format,
            pixel: desc.pixel,
        }
    }
}

/// A resolution's unit, as the file states it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ResolutionUnit {
    /// Pixels per inch.
    Inch,
    /// Pixels per centimetre.
    Centimetre,
}

/// How densely the image is meant to be printed or shown (sharp's
/// `density`, `resolutionUnit`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Density {
    /// Horizontal pixels per `unit`.
    pub x: f64,
    /// Vertical pixels per `unit`.
    pub y: f64,
    /// The unit the file states.
    pub unit: ResolutionUnit,
}

impl Density {
    /// A density of `dpi` both ways, per inch.
    #[must_use]
    pub const fn dpi(dpi: f64) -> Self {
        Self {
            x: dpi,
            y: dpi,
            unit: ResolutionUnit::Inch,
        }
    }

    /// The density an EXIF block states in IFD0 (`XResolution`,
    /// `YResolution`, `ResolutionUnit`), or `None` if it states none.
    #[must_use]
    pub fn from_exif_block(exif: &[u8]) -> Option<Self> {
        let tree = crate::exif::Exif::parse(exif)?;
        let x = tree.rational(0x011A)?;
        let y = tree.rational(0x011B).unwrap_or(x);
        let unit = match tree.integer(0x0128).unwrap_or(2) {
            3 => ResolutionUnit::Centimetre,
            2 => ResolutionUnit::Inch,
            _ => return None,
        };
        (x > 0.0 && y > 0.0).then_some(Self { x, y, unit })
    }

    /// The horizontal density in pixels per inch, sharp's `density`.
    #[must_use]
    pub fn x_dpi(&self) -> f64 {
        match self.unit {
            ResolutionUnit::Inch => self.x,
            ResolutionUnit::Centimetre => self.x * 2.54,
        }
    }

    /// The vertical density in pixels per inch.
    #[must_use]
    pub fn y_dpi(&self) -> f64 {
        match self.unit {
            ResolutionUnit::Inch => self.y,
            ResolutionUnit::Centimetre => self.y * 2.54,
        }
    }
}

/// A text entry a file carries, such as PNG's `tEXt` (sharp's `comments`).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Comment {
    /// The entry's keyword, empty where the format has none.
    pub keyword: String,
    /// Its text.
    pub text: String,
}

/// The colour a file names as its background, in its own samples.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Background {
    /// A grey level.
    Grey(u16),
    /// Red, green and blue.
    Rgb(u16, u16, u16),
}

/// What a decoder learned about its file from the header, beyond the pixel
/// layout: the facts sharp's `metadata()` reports per format. Every field is
/// empty for a format with no notion of it.
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct SourceInfo {
    /// The stated resolution, if any (JPEG's JFIF or EXIF, PNG's `pHYs`,
    /// TIFF's tags).
    pub density: Option<Density>,
    /// Progressive JPEG, or interlaced PNG and GIF.
    pub progressive: bool,
    /// Samples are indices into a palette (PNG colour type 3, GIF, TIFF
    /// palette).
    pub palette: bool,
    /// Bits per stored sample, which may be fewer than the output's (a
    /// 10-bit AVIF, a 4-bit PNG).
    pub bits_per_sample: Option<u8>,
    /// Chroma subsampling as sharp spells it (`"4:2:0"`, `"4:4:4"`, ...),
    /// for formats that subsample.
    pub chroma_subsampling: Option<&'static str>,
    /// The background colour the file names (PNG `bKGD`, GIF's).
    pub background: Option<Background>,
    /// The compression scheme, where a format has several (TIFF, AVIF).
    pub compression: Option<&'static str>,
    /// Text entries (PNG `tEXt`, `zTXt`, `iTXt`; GIF and JPEG comments).
    pub comments: Vec<Comment>,
}

/// How an encoder samples chroma (sharp's `chromaSubsampling`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ChromaSubsampling {
    /// Chroma at half resolution both ways (`'4:2:0'`): smaller files, and
    /// a loss photographs rarely show.
    Yuv420,
    /// Chroma at full resolution (`'4:4:4'`): edges between colours, as in
    /// screenshots and text, stay sharp.
    Yuv444,
}

/// Encoder tuning shared across formats.
///
/// Fields that a format has no notion of are ignored by that format rather
/// than rejected, so the same options value can be handed to any encoder.
/// Every field's default leaves a format's output as it was before the field
/// existed.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct EncodeOptions {
    /// Lossy quality, 1–100. Ignored by lossless formats, and by a format
    /// with both modes when `lossless` is set.
    pub quality: u8,
    /// For a format that has both a lossy and a lossless mode (WebP), choose
    /// lossless. Off by default: such a format encodes lossy at `quality`,
    /// as `cwebp` and sharp do. Formats with one mode ignore it.
    pub lossless: bool,
    /// CPU spent for a smaller file, 0 (fastest) to 10, in each format's
    /// own range as sharp defines it: WebP 0–6 and AVIF 0–9, both with a
    /// default of 4. `None` is the format's default.
    pub effort: Option<u8>,
    /// PNG's DEFLATE level, 0 (store) to 9. `None` derives it from
    /// `quality`, as before this option existed.
    pub compression_level: Option<u8>,
    /// Write PNG as a palette image of at most `colours` entries (sharp's
    /// `palette`). Setting `colours` or `dither` implies it, as in sharp.
    pub palette: bool,
    /// The palette size for palette PNG and GIF, 2–256. `None` is 256 for
    /// PNG, and for GIF the size `quality` implies.
    pub colours: Option<u16>,
    /// How much of the quantization error a palette image diffuses, 0 (none)
    /// to 1 (full Floyd-Steinberg, the default). `None` is 1.
    pub dither: Option<f32>,
    /// Quality of lossy WebP's alpha channel, 0–100; 100, the default, keeps
    /// it lossless.
    pub alpha_quality: u8,
    /// Lossless WebP that may change pixels a little where it saves bytes,
    /// by as much as `quality` allows (sharp's `nearLossless`; 100 changes
    /// nothing). Implies lossless.
    pub near_lossless: bool,
    /// Chroma sampling for JPEG and AVIF. `None` is each format's default:
    /// for JPEG 4:2:0 below quality 90 and 4:4:4 from it, for AVIF 4:2:0.
    pub chroma_subsampling: Option<ChromaSubsampling>,
    /// Copy the source's EXIF block into the output (sharp's `keepExif`),
    /// where the format has a place for one: JPEG, PNG, WebP and AVIF. Off
    /// by default, which strips camera data and location from uploads.
    pub keep_exif: bool,
    /// Copy the source's XMP packet into the output (sharp's `keepXmp`),
    /// where the format has a place for one: JPEG, PNG, WebP, TIFF, AVIF
    /// and JPEG XL. Off by default, as for EXIF.
    pub keep_xmp: bool,
    /// Write JPEG as progressive (sharp's `progressive`): a coarse picture
    /// first, sharpened by later scans, and usually a little smaller. The
    /// encoder then holds the image's coefficients rather than streaming.
    pub progressive: bool,
}

/// Check `value` lies in `range`, naming `name` if not.
fn within(name: &'static str, value: u16, range: core::ops::RangeInclusive<u16>) -> Result<()> {
    if range.contains(&value) {
        Ok(())
    } else {
        Err(PixelsError::invalid_argument(
            name,
            format!(
                "must be in {}..={}, got {value}",
                range.start(),
                range.end()
            ),
        ))
    }
}

impl EncodeOptions {
    /// The default quality used when none is given.
    pub const DEFAULT_QUALITY: u8 = 80;

    /// Options with the given quality.
    ///
    /// # Errors
    ///
    /// Returns [`PixelsError::InvalidArgument`] unless `quality` is in 1..=100.
    pub fn with_quality(quality: u8) -> Result<Self> {
        within("quality", quality.into(), 1..=100)?;
        Ok(Self {
            quality,
            ..Self::default()
        })
    }

    /// These options with `lossless` replaced.
    #[must_use]
    pub const fn with_lossless(mut self, lossless: bool) -> Self {
        self.lossless = lossless;
        self
    }

    /// These options with an encoding effort, 0..=10 (see
    /// [`EncodeOptions::effort`]). A value past a format's own range is
    /// clamped to it.
    ///
    /// # Errors
    ///
    /// Returns [`PixelsError::InvalidArgument`] above 10.
    pub fn with_effort(mut self, effort: u8) -> Result<Self> {
        within("effort", effort.into(), 0..=10)?;
        self.effort = Some(effort);
        Ok(self)
    }

    /// These options with a PNG DEFLATE level, 0..=9.
    ///
    /// # Errors
    ///
    /// Returns [`PixelsError::InvalidArgument`] above 9.
    pub fn with_compression_level(mut self, level: u8) -> Result<Self> {
        within("compression_level", level.into(), 0..=9)?;
        self.compression_level = Some(level);
        Ok(self)
    }

    /// These options with palette PNG on or off.
    #[must_use]
    pub const fn with_palette(mut self, palette: bool) -> Self {
        self.palette = palette;
        self
    }

    /// These options with a palette size, 2..=256, which for PNG implies a
    /// palette.
    ///
    /// # Errors
    ///
    /// Returns [`PixelsError::InvalidArgument`] outside 2..=256.
    pub fn with_colours(mut self, colours: u16) -> Result<Self> {
        within("colours", colours, 2..=256)?;
        self.colours = Some(colours);
        Ok(self)
    }

    /// These options with a dithering level, 0..=1, which for PNG implies a
    /// palette.
    ///
    /// # Errors
    ///
    /// Returns [`PixelsError::InvalidArgument`] outside 0..=1.
    pub fn with_dither(mut self, dither: f32) -> Result<Self> {
        if !(0.0..=1.0).contains(&dither) {
            return Err(PixelsError::invalid_argument(
                "dither",
                format!("must be in 0..=1, got {dither}"),
            ));
        }
        self.dither = Some(dither);
        Ok(self)
    }

    /// These options with a lossy WebP alpha quality, 0..=100.
    ///
    /// # Errors
    ///
    /// Returns [`PixelsError::InvalidArgument`] above 100.
    pub fn with_alpha_quality(mut self, quality: u8) -> Result<Self> {
        within("alpha_quality", quality.into(), 0..=100)?;
        self.alpha_quality = quality;
        Ok(self)
    }

    /// These options with near-lossless WebP on or off.
    #[must_use]
    pub const fn with_near_lossless(mut self, near_lossless: bool) -> Self {
        self.near_lossless = near_lossless;
        self
    }

    /// These options with an explicit chroma subsampling.
    #[must_use]
    pub const fn with_chroma_subsampling(mut self, subsampling: ChromaSubsampling) -> Self {
        self.chroma_subsampling = Some(subsampling);
        self
    }

    /// These options keeping the source's EXIF, or not.
    #[must_use]
    pub const fn with_keep_exif(mut self, keep: bool) -> Self {
        self.keep_exif = keep;
        self
    }

    /// These options with `keep_xmp` replaced.
    #[must_use]
    pub const fn with_keep_xmp(mut self, keep: bool) -> Self {
        self.keep_xmp = keep;
        self
    }

    /// These options keeping EXIF and XMP both (sharp's `keepMetadata`;
    /// the ICC profile is always kept).
    #[must_use]
    pub const fn with_keep_metadata(mut self, keep: bool) -> Self {
        self.keep_exif = keep;
        self.keep_xmp = keep;
        self
    }

    /// These options with progressive JPEG on or off.
    #[must_use]
    pub const fn with_progressive(mut self, progressive: bool) -> Self {
        self.progressive = progressive;
        self
    }

    /// Whether a PNG should be written as a palette image.
    #[must_use]
    pub const fn wants_palette(&self) -> bool {
        self.palette || self.colours.is_some() || self.dither.is_some()
    }
}

impl Default for EncodeOptions {
    fn default() -> Self {
        Self {
            quality: Self::DEFAULT_QUALITY,
            lossless: false,
            effort: None,
            compression_level: None,
            palette: false,
            colours: None,
            dither: None,
            alpha_quality: 100,
            near_lossless: false,
            chroma_subsampling: None,
            keep_exif: false,
            keep_xmp: false,
            progressive: false,
        }
    }
}

/// Format sniffing.
///
/// Detection is by **magic bytes only** — extensions and MIME types are
/// ignored (SPEC §Formats), because they are attacker-controlled hints rather
/// than facts about the bytes.
pub trait Codec {
    /// The format this codec handles.
    fn format(&self) -> Format;

    /// The number of leading bytes [`Codec::probe`] needs to decide.
    fn magic_len(&self) -> usize;

    /// Whether `prefix` looks like this format.
    ///
    /// `prefix` may be shorter than [`Codec::magic_len`] if the source ended
    /// early; an implementation must then return `false`, never index blindly.
    fn probe(&self, prefix: &[u8]) -> bool;
}

/// Decodes a byte stream into rows of pixels.
///
/// Implementations must return [`PixelsError::Malformed`] for **every** input
/// they cannot parse. Panicking on hostile bytes is a defect, not a caller
/// error (ARCHITECTURE §Failure model); every parser is fuzzed in CI from the
/// first codec onward.
///
/// Dimension limits are enforced at header parse, before any pixel buffer is
/// allocated, so a header claiming enormous dimensions costs nothing.
pub trait Decoder: Send + fmt::Debug {
    /// The shape of the image, known after the header is parsed.
    fn descriptor(&self) -> ImageDescriptor;

    /// What this decoder can produce without a full decode.
    fn capability(&self) -> DecodeCapability {
        DecodeCapability::Sequential
    }

    /// How the stored image must be turned to display upright, as its
    /// metadata declares.
    ///
    /// Reported, never applied: rows come out in stored order whatever this
    /// says. Applying it is the pipeline's `auto_orient` decision (SPEC
    /// §Safety and limits), which a decoder that rotated its own output would
    /// take away from the caller. Known after the header is parsed, like
    /// [`Decoder::descriptor`].
    fn orientation(&self) -> Orientation {
        Orientation::Normal
    }

    /// The source's animation, if it has more than one frame.
    ///
    /// Reported, like [`Decoder::orientation`]: rows are always the first
    /// frame's. Known once the decoder is constructed; a format that must
    /// read further to count its frames does so up front.
    fn animation(&self) -> Option<Animation> {
        None
    }

    /// How many pages the source document holds, at least 1.
    ///
    /// A page is a separate image in one file, as in a multi-page TIFF: a
    /// stack of scans or faxes, not the frames of an animation, which
    /// [`Decoder::animation`] reports. Rows are always the page the decoder
    /// was opened on. Known once the decoder is constructed, without decoding
    /// any page.
    fn pages(&self) -> u32 {
        1
    }

    /// The embedded ICC colour profile, if the file carries one.
    ///
    /// Reported, never applied, like [`Decoder::orientation`]: samples come
    /// out as stored, and converting them is the pipeline's decision. Known
    /// after the header is parsed; a profile stored after the image data is
    /// not seen.
    fn icc_profile(&self) -> Option<&[u8]> {
        None
    }

    /// The embedded EXIF block, if the file carries one: the TIFF-structured
    /// bytes from the byte-order mark (`II` or `MM`), without the `Exif\0\0`
    /// identifier a JPEG wraps it in.
    ///
    /// Reported for an encoder to copy, like [`Decoder::icc_profile`]; its
    /// orientation is what [`Decoder::orientation`] reports.
    fn exif(&self) -> Option<&[u8]> {
        None
    }

    /// The embedded XMP packet, if the file carries one: the XML as stored,
    /// from `<?xpacket` or `<x:xmpmeta`.
    ///
    /// Reported for an encoder to copy, like [`Decoder::exif`].
    fn xmp(&self) -> Option<&[u8]> {
        None
    }

    /// What the header said beyond the pixel layout. Known after the header
    /// is parsed, like [`Decoder::descriptor`].
    fn source_info(&self) -> SourceInfo {
        SourceInfo::default()
    }

    /// Decode the next row, top to bottom, into `out`.
    ///
    /// `out` is exactly [`ImageDescriptor::row_bytes`] long. Each call advances
    /// the cursor by one row; the caller reads `descriptor().height` rows.
    ///
    /// # Errors
    ///
    /// Returns [`PixelsError::Malformed`] on invalid or truncated input,
    /// [`PixelsError::Io`] on source failure, or
    /// [`PixelsError::InvalidArgument`] if `out` is the wrong length or every
    /// row has already been read.
    fn read_row(&mut self, out: &mut [u8]) -> Result<()>;

    /// Decode an arbitrary region into `out`.
    ///
    /// Only meaningful when [`Decoder::capability`] is
    /// [`DecodeCapability::Regions`]; the default implementation reports that
    /// this decoder is sequential.
    ///
    /// # Errors
    ///
    /// Returns [`PixelsError::Unsupported`] for sequential decoders, and
    /// otherwise as [`Decoder::read_row`].
    fn read_region(&mut self, region: Region, out: &mut TileMut<'_>) -> Result<()> {
        let _ = (region, out);
        Err(PixelsError::unsupported(
            "this decoder is sequential; region decode requires DecodeCapability::Regions",
        ))
    }

    /// What this decoder would produce if asked for `target` or larger, when
    /// the format lets it reach that size more cheaply than a full decode.
    ///
    /// JPEG is the motivating case — the low-frequency corner of a DCT block
    /// is a smaller version of that block, so 1/8, 1/4 and 1/2 come almost
    /// free — but nothing here is JPEG-specific: a pyramidal TIFF or a WebP
    /// with scaled decode fits the same shape.
    ///
    /// **Pure**: nothing is committed. The planner asks before it knows
    /// whether the reduction is legal for the pipeline as a whole.
    ///
    /// The returned descriptor is never smaller than `target` in either axis.
    fn reduced_descriptor(&self, target: (u32, u32)) -> Option<ImageDescriptor> {
        let _ = target;
        None
    }

    /// Commit to producing `descriptor`, which
    /// [`Decoder::reduced_descriptor`] must have returned.
    ///
    /// # Errors
    ///
    /// Returns [`PixelsError::Unsupported`] if this decoder has one
    /// resolution, or [`PixelsError::InvalidArgument`] if any row has already
    /// been read — the resolution is fixed from the first row onward.
    fn reduce_to(&mut self, descriptor: ImageDescriptor) -> Result<()> {
        let _ = descriptor;
        Err(PixelsError::unsupported(
            "this decoder has only one resolution",
        ))
    }
}

/// Encodes rows of pixels into a byte stream.
///
/// The sink is passed to each call rather than held by the encoder, which
/// keeps [`Encoder`] object-safe and lets the caller retain ownership of the
/// destination. Encoders write incrementally as rows arrive; they must not
/// buffer the whole image unless the format leaves no choice (ADR-0005).
pub trait Encoder: Send {
    /// Embed `profile` as the image's ICC colour profile, or write none.
    ///
    /// Called before [`Encoder::write_header`], whose header usually holds
    /// it. The default ignores it, which is right for a format with nowhere
    /// to put one (raw pixels, GIF): the pixels are written as given either
    /// way.
    ///
    /// # Errors
    ///
    /// Returns [`PixelsError::InvalidArgument`] if the header has already
    /// been written.
    fn set_icc_profile(&mut self, profile: Option<&[u8]>) -> Result<()> {
        let _ = profile;
        Ok(())
    }

    /// Embed `exif` (TIFF-structured bytes, as [`Decoder::exif`] gives
    /// them) as the image's EXIF block, or write none.
    ///
    /// Called before [`Encoder::write_header`]. The default ignores it, which
    /// is right for a format with nowhere to put one.
    ///
    /// # Errors
    ///
    /// Returns [`PixelsError::InvalidArgument`] if the header has already
    /// been written.
    fn set_exif(&mut self, exif: Option<&[u8]>) -> Result<()> {
        let _ = exif;
        Ok(())
    }

    /// Embed `xmp`, an XMP packet as [`Decoder::xmp`] gives it, or write
    /// none.
    ///
    /// Called before [`Encoder::write_header`]. The default ignores it, which
    /// is right for a format with nowhere to put one.
    ///
    /// # Errors
    ///
    /// Returns [`PixelsError::InvalidArgument`] if the header has already
    /// been written.
    fn set_xmp(&mut self, xmp: Option<&[u8]>) -> Result<()> {
        let _ = xmp;
        Ok(())
    }

    /// Record `density` as the image's resolution, or write the format's
    /// default.
    ///
    /// Called before [`Encoder::write_header`]. The default ignores it, for
    /// a format with no resolution field.
    ///
    /// # Errors
    ///
    /// Returns [`PixelsError::InvalidArgument`] if the header has already
    /// been written.
    fn set_density(&mut self, density: Option<Density>) -> Result<()> {
        let _ = density;
        Ok(())
    }

    /// Begin an image, writing any container header.
    ///
    /// Must be called exactly once, before any [`Encoder::write_row`].
    ///
    /// # Errors
    ///
    /// Returns [`PixelsError::Io`] on sink failure, or
    /// [`PixelsError::Unsupported`] if the encoder cannot represent `desc`
    /// (for example an alpha channel in a format without one).
    fn write_header(&mut self, desc: &ImageDescriptor, sink: &mut dyn Sink) -> Result<()>;

    /// Write the next row, top to bottom.
    ///
    /// `row` is exactly [`ImageDescriptor::row_bytes`] long.
    ///
    /// # Errors
    ///
    /// Returns [`PixelsError::Io`] on sink failure, or
    /// [`PixelsError::InvalidArgument`] if `row` is the wrong length or more
    /// rows are written than the header declared.
    fn write_row(&mut self, row: &[u8], sink: &mut dyn Sink) -> Result<()>;

    /// Finish the image, writing any trailer and flushing the sink.
    ///
    /// # Errors
    ///
    /// Returns [`PixelsError::Io`] on sink failure, or
    /// [`PixelsError::Malformed`] if fewer rows were written than the header
    /// declared — a partial image is never silently emitted
    /// (ARCHITECTURE §Failure model).
    fn finish(&mut self, sink: &mut dyn Sink) -> Result<()>;
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::indexing_slicing,
    reason = "tests operate on known-good values and assert shapes directly"
)]
mod tests {
    use super::*;
    use crate::ErrorCode;

    #[test]
    fn quality_is_validated_at_the_boundary() {
        assert_eq!(EncodeOptions::with_quality(1).unwrap().quality, 1);
        assert_eq!(EncodeOptions::with_quality(100).unwrap().quality, 100);
        assert_eq!(
            EncodeOptions::with_quality(0).unwrap_err().code(),
            ErrorCode::InvalidArgument
        );
        assert_eq!(
            EncodeOptions::with_quality(101).unwrap_err().code(),
            ErrorCode::InvalidArgument
        );
        assert_eq!(EncodeOptions::default().quality, 80);
    }

    #[test]
    fn format_names_are_stable_and_unique() {
        let all = [
            Format::Raw,
            Format::Png,
            Format::Jpeg,
            Format::Gif,
            Format::Tiff,
            Format::WebP,
            Format::Avif,
            Format::Jxl,
        ];
        let mut seen = std::collections::HashSet::new();
        for f in all {
            assert!(seen.insert(f.as_str()), "duplicate name {f}");
        }
        assert_eq!(Format::WebP.as_str(), "webp");
    }

    #[test]
    fn metadata_mirrors_the_descriptor() {
        let desc = ImageDescriptor::new(7, 5, PixelFormat::Rgba8).unwrap();
        let meta = Metadata::new(&desc, Format::Png);
        assert_eq!((meta.width, meta.height), (7, 5));
        assert_eq!(meta.pixel, PixelFormat::Rgba8);
        assert_eq!(meta.format, Format::Png);
    }

    #[test]
    fn sequential_decoders_decline_region_decode() {
        #[derive(Debug)]
        struct Seq;
        impl Decoder for Seq {
            fn descriptor(&self) -> ImageDescriptor {
                ImageDescriptor::new(1, 1, PixelFormat::Gray8).unwrap_or(ImageDescriptor {
                    width: 1,
                    height: 1,
                    pixel: PixelFormat::Gray8,
                    color: crate::ColorModel::Srgb,
                })
            }
            fn read_row(&mut self, _: &mut [u8]) -> Result<()> {
                Ok(())
            }
        }
        let mut buf = crate::TileBuf::zeroed(Region::from_size(1, 1), PixelFormat::Gray8).unwrap();
        let mut tile = buf.as_tile_mut().unwrap();
        let err = Seq
            .read_region(Region::from_size(1, 1), &mut tile)
            .unwrap_err();
        assert_eq!(err.code(), ErrorCode::Unsupported);
        assert_eq!(Seq.capability(), DecodeCapability::Sequential);
    }
}