otf-pixels-core 0.1.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
//! Container formats and the codec traits every format plugs in behind.
//!
//! Ownership per format — implemented from scratch versus wrapped — is
//! recorded in ADR-0004 and 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,
}

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",
        }
    }
}

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,
        }
    }
}

/// 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.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[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,
}

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> {
        if !(1..=100).contains(&quality) {
            return Err(PixelsError::invalid_argument(
                "quality",
                format!("must be in 1..=100, got {quality}"),
            ));
        }
        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
    }
}

impl Default for EncodeOptions {
    fn default() -> Self {
        Self {
            quality: Self::DEFAULT_QUALITY,
            lossless: 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
    }

    /// 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
    }

    /// 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(())
    }

    /// 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,
        ];
        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);
    }
}