Skip to main content

meo_canvas_core/
encode.rs

1//! Turns a painted surface into the bytes of an image file.
2//!
3//! The last pass, and the only one whose output leaves the process. It is
4//! separate from [`crate::paint`] because one painted surface is often encoded
5//! more than once -- a PNG for the response and a WebP for the cache -- and
6//! re-painting to change container is work with no drawing in it.
7//!
8//! # Pages
9//!
10//! A [`Scene`] carries several page roots, and what a page means is the
11//! format's answer rather than the scene's: a frame for GIF and APNG, a sheet
12//! for PDF and TIFF, one size of the same icon for ICO. Every other format
13//! writes a single page and [`EncodeOptions::page`] chooses which.
14//!
15//! That rule is the renderer's, and it is asked rather than restated:
16//! [`ImageFormat::spans_pages`] and [`ImageFormat::is_animated`] forward to
17//! `meo-skia-canvas`, so there is one table and this module reads it. The
18//! conformance test walks the renderer's own format list rather than ours, so a
19//! format it gains that this crate has not mapped fails a test instead of
20//! passing unnoticed.
21//!
22//! # Timing
23//!
24//! [`Scene`] carries no frame rate, no duration and no per-page delay, and this
25//! module does not invent one. Timing reaches the encoder through
26//! [`EncodeOptions::fps`] or [`EncodeOptions::frame_delays`], which is a
27//! property of the encode rather than of the scene -- the same pages played at
28//! two rates are two files from one scene, not two scenes.
29//!
30//! [`Scene`]: meo_canvas_scene::Scene
31
32use crate::Error;
33
34/// The container an encoded image is written in.
35///
36/// The set here is what a caller picks between; which crate writes the bytes is
37/// not part of the promise, and neither is whether Skia or a dedicated encoder
38/// does it.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40#[non_exhaustive]
41pub enum ImageFormat {
42    /// Lossless raster with an alpha channel.
43    Png,
44    /// Lossy raster without one. Transparency is flattened against
45    /// [`EncodeOptions::matte`], or black when none is given.
46    Jpeg,
47    /// Lossy or lossless raster with an alpha channel, and animated when the
48    /// scene carries more than one page.
49    Webp,
50    /// Raster as AV1 intra frames, animated when the scene carries more than
51    /// one page. The smallest files here and by far the slowest to write.
52    Avif,
53    /// Uncompressed raster. The format some Windows tooling reads and nothing
54    /// else does.
55    Bmp,
56    /// Raster, one page per directory entry, and the only format whose pages
57    /// may differ in size -- an icon at 16, 32, 48 and 256 pixels is one file.
58    Ico,
59    /// Raster, one page per directory. Paged but not animated: the pages are
60    /// sheets and carry no timing.
61    Tiff,
62    /// Animated raster, one page per frame, from a palette of 256 colours per
63    /// frame.
64    Gif,
65    /// Animated raster, one page per frame, in full colour with alpha.
66    Apng,
67    /// Vector markup.
68    Svg,
69    /// Vector document, one page per sheet.
70    Pdf,
71    /// Unencoded pixel bytes in the surface's own layout, with no container
72    /// around them.
73    Raw,
74}
75
76impl core::fmt::Display for ImageFormat {
77    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
78        f.write_str(self.name())
79    }
80}
81
82impl ImageFormat {
83    /// Every format, in declaration order.
84    ///
85    /// Exists so a test can exercise the whole set without listing it a second
86    /// time, which is what keeps a format added later from being untested by
87    /// omission.
88    pub const ALL: &'static [Self] = &[
89        Self::Png,
90        Self::Jpeg,
91        Self::Webp,
92        Self::Avif,
93        Self::Bmp,
94        Self::Ico,
95        Self::Tiff,
96        Self::Gif,
97        Self::Apng,
98        Self::Svg,
99        Self::Pdf,
100        Self::Raw,
101    ];
102
103    /// The format's name as a reader would write it.
104    #[must_use]
105    pub const fn name(self) -> &'static str {
106        match self {
107            Self::Png => "PNG",
108            Self::Jpeg => "JPEG",
109            Self::Webp => "WebP",
110            Self::Avif => "AVIF",
111            Self::Bmp => "BMP",
112            Self::Ico => "ICO",
113            Self::Tiff => "TIFF",
114            Self::Gif => "GIF",
115            Self::Apng => "APNG",
116            Self::Svg => "SVG",
117            Self::Pdf => "PDF",
118            Self::Raw => "raw",
119        }
120    }
121
122    /// The extension conventionally given to this format, without a dot.
123    #[must_use]
124    pub const fn extension(self) -> &'static str {
125        match self {
126            Self::Png => "png",
127            // `apng`, not `png`: upstream registers the two separately
128            // (`export.rs:426` against `:362`), and a filename that says which
129            // it is spares a decoder guessing from the chunks.
130            Self::Apng => "apng",
131            Self::Jpeg => "jpg",
132            Self::Webp => "webp",
133            Self::Avif => "avif",
134            Self::Bmp => "bmp",
135            Self::Ico => "ico",
136            Self::Tiff => "tiff",
137            Self::Gif => "gif",
138            Self::Svg => "svg",
139            Self::Pdf => "pdf",
140            Self::Raw => "bin",
141        }
142    }
143
144    /// The IANA media type this format is served as.
145    ///
146    /// Delegated to the renderer, whose `mime_type` reads the same traits table
147    /// as its `extension` and `is_animated`, so there is one table rather than
148    /// a second restating it.
149    ///
150    /// [`Raw`](ImageFormat::Raw) has no registered type and reports
151    /// `application/octet-stream`.
152    #[must_use]
153    pub fn media_type(self) -> &'static str {
154        to_skia_format(self).mime_type()
155    }
156
157    /// The format a **caller** named, by extension or by name.
158    ///
159    /// [`ImageFormat::from_extension`] answers the other question: what format
160    /// a filename *found on disk* implies. It refuses `raw` deliberately, and
161    /// rightly — upstream calls that container `.bin`, and a `.bin` of pixel
162    /// bytes is not something any format may be inferred from.
163    ///
164    /// This is for a path the caller has just typed, where `.raw` is as plain a
165    /// statement of intent as `.png`. A caller who writes `to_file("x.raw")`
166    /// has named the format; nothing is being inferred.
167    ///
168    /// The addon's format tag and the facade's `to_file` both resolve through
169    /// this, so a `.raw` path means the same on both surfaces.
170    #[must_use]
171    pub fn from_named(name: &str) -> Option<Self> {
172        if name.eq_ignore_ascii_case("raw") {
173            return Some(Self::Raw);
174        }
175        Self::from_extension(name)
176    }
177
178    /// The format a filename extension names, if any.
179    ///
180    /// Delegates to the renderer rather than matching here, so the aliases it
181    /// accepts -- `jpeg` for `jpg`, and whichever others it registers -- are
182    /// the same set on both sides and there is one table rather than a third
183    /// copy. A format the renderer marks as not inferable, `raw` among them,
184    /// answers `None`: asking for pixel bytes is something a caller says by
185    /// name, and a `.bin` that wrote them would be a file nothing reads back.
186    #[must_use]
187    pub fn from_extension(extension: &str) -> Option<Self> {
188        use meo_skia_canvas::export::ImageFormat as Skia;
189
190        Some(match Skia::from_extension(extension)? {
191            Skia::Png => Self::Png,
192            Skia::Jpeg => Self::Jpeg,
193            Skia::Webp => Self::Webp,
194            Skia::Avif => Self::Avif,
195            Skia::Bmp => Self::Bmp,
196            Skia::Ico => Self::Ico,
197            Skia::Tiff => Self::Tiff,
198            Skia::Gif => Self::Gif,
199            Skia::Apng => Self::Apng,
200            Skia::Svg => Self::Svg,
201            Skia::Pdf => Self::Pdf,
202            Skia::Raw => Self::Raw,
203        })
204    }
205
206    /// Whether one file of this format carries every page.
207    ///
208    /// The renderer's answer, not a copy of it. PDF, TIFF, ICO and the animated
209    /// formats span; the rest write the page [`EncodeOptions::page`] names.
210    #[must_use]
211    pub fn spans_pages(self) -> bool {
212        to_skia_format(self).spans_pages()
213    }
214
215    /// Whether this format's pages are frames with durations.
216    ///
217    /// Distinct from [`spans_pages`](Self::spans_pages): PDF, TIFF and ICO
218    /// gather every page and carry no clock, so a frame rate means nothing to
219    /// them. WebP and AVIF animate as well as GIF and APNG.
220    #[must_use]
221    pub fn is_animated(self) -> bool {
222        to_skia_format(self).is_animated()
223    }
224
225    /// Whether the drawing is written as vectors rather than pixels.
226    #[must_use]
227    pub fn is_vector(self) -> bool {
228        to_skia_format(self).is_vector()
229    }
230}
231
232/// Finished bytes and what they are.
233#[derive(Debug, Clone)]
234pub struct EncodedImage {
235    /// The file's contents.
236    pub bytes: Vec<u8>,
237    /// The container those bytes are in.
238    pub format: ImageFormat,
239}
240
241/// Quality and container settings that only apply to some formats.
242///
243/// A single struct with `Option` fields rather than one per format: a caller
244/// setting quality does not want to know which formats read it, and a format
245/// that ignores a field ignores it rather than refusing the call.
246///
247/// The timing fields are the exception, and deliberately: naming a frame rate
248/// for a format with no clock is [`Error::Encode`] rather than something
249/// quietly dropped, because a caller who wrote `fps` and got a still image back
250/// asked for something that did not happen.
251#[derive(Debug, Clone, Default)]
252pub struct EncodeOptions {
253    /// Lossy quality from `0.0` to `1.0`, read by JPEG, WebP and AVIF. `None`
254    /// is each format's own default.
255    ///
256    /// A WebP at `1.0`, with [`lossless`](Self::lossless) unset, is lossless.
257    /// AVIF at `1.0` is its finest lossy quantizer, not lossless.
258    pub quality: Option<f32>,
259    /// Whether a WebP or AVIF encode is lossless. `None` is each format's own
260    /// rule, which for WebP is the [`quality`](Self::quality): lossless at
261    /// `1.0`.
262    ///
263    /// `Some(true)` writes a lossless WebP, still or animated, and a lossless
264    /// AVIF; beside a quality below `1.0` it is refused, and so it is for
265    /// every other format. `Some(false)` writes a lossy WebP at any
266    /// quality, its finest at `1.0`. Passed to `meo-skia-canvas`'s
267    /// `EncodeOptions::lossless` as it is.
268    pub lossless: Option<bool>,
269    /// The colour transparency is flattened against by a format with no alpha
270    /// channel, as a packed `0xRRGGBB`.
271    pub matte: Option<u32>,
272    /// Which page is written, counting from zero.
273    ///
274    /// Naming a page wins over a format that would otherwise gather them all:
275    /// a GIF asked for page 1 of three is a one-frame GIF, and a PDF asked
276    /// for one page is a one-sheet PDF. [`EncodeOptions::written_pages`]
277    /// is that rule, and `tests/write_path.rs` pins it on both the
278    /// encoding and the writing path.
279    ///
280    /// An index past the last page is refused rather than clamped. `None`
281    /// writes every page for a format that spans them, and otherwise the last
282    /// page, the one a caller who drew a sequence and asked for a PNG almost
283    /// always means.
284    pub page: Option<usize>,
285    /// Frames per second for an animated format.
286    ///
287    /// `None` leaves the encoder's own default, which is 30.
288    pub fps: Option<f32>,
289    /// Per-frame durations in milliseconds, overriding [`fps`](Self::fps).
290    ///
291    /// Read only when it holds one entry per written page. A shorter or longer
292    /// list is [`Error::Encode`] rather than a partial application, because a
293    /// list that silently retimed some frames and not others is worse than a
294    /// refusal.
295    pub frame_delays: Vec<u32>,
296    /// How many times an animation plays. `None` plays it forever.
297    pub loops: Option<u32>,
298}
299
300impl EncodeOptions {
301    /// Rejects a combination the format cannot honour.
302    ///
303    /// Checked before anything is drawn or encoded, so a caller learns that
304    /// `fps` means nothing to a PNG without waiting for a surface to be
305    /// rasterised first.
306    ///
307    /// `pages` is the number the scene carries, which for a single-page format
308    /// is the number [`EncodeOptions::page`] indexes into.
309    ///
310    /// # Errors
311    ///
312    /// Returns [`Error::Encode`] when a timing field is set for a format with
313    /// no clock, when `frame_delays` does not hold one entry per written page,
314    /// or when `page` is past the last one.
315    pub fn validate(
316        &self,
317        format: ImageFormat,
318        pages: usize,
319    ) -> Result<(), Error> {
320        let timed = self.fps.is_some()
321            || !self.frame_delays.is_empty()
322            || self.loops.is_some();
323        if timed && !format.is_animated() {
324            return Err(Error::Encode {
325                format,
326                detail: format!(
327                    "{format} has no frame timing, so fps, frame_delays and loops name nothing"
328                ),
329            });
330        }
331
332        if let Some(page) = self.page
333            && page >= pages
334        {
335            return Err(Error::Encode {
336                format,
337                detail: format!(
338                    "page {page} is out of range; the scene has {pages}"
339                ),
340            });
341        }
342
343        let written = self.written_pages(format, pages);
344        if !self.frame_delays.is_empty() && self.frame_delays.len() != written {
345            return Err(Error::Encode {
346                format,
347                detail: format!(
348                    "frame_delays holds {} entries for {written} written pages",
349                    self.frame_delays.len()
350                ),
351            });
352        }
353
354        Ok(())
355    }
356
357    /// How many pages this encode writes.
358    ///
359    /// A named page wins over the format spanning them: asking for one page of
360    /// a PDF writes a one-sheet PDF rather than the whole document. That is the
361    /// order `meo-skia-canvas` resolves the pair in, and the two must agree or
362    /// a `frame_delays` list sized against one is refused by the other.
363    #[must_use]
364    pub fn written_pages(&self, format: ImageFormat, pages: usize) -> usize {
365        if self.page.is_some() || !format.spans_pages() {
366            1
367        } else {
368            pages
369        }
370    }
371}
372
373/// The renderer's own format for one of ours.
374const fn to_skia_format(
375    format: ImageFormat,
376) -> meo_skia_canvas::export::ImageFormat {
377    use meo_skia_canvas::export::ImageFormat as Skia;
378    match format {
379        ImageFormat::Png => Skia::Png,
380        ImageFormat::Jpeg => Skia::Jpeg,
381        ImageFormat::Webp => Skia::Webp,
382        ImageFormat::Avif => Skia::Avif,
383        ImageFormat::Bmp => Skia::Bmp,
384        ImageFormat::Ico => Skia::Ico,
385        ImageFormat::Tiff => Skia::Tiff,
386        ImageFormat::Gif => Skia::Gif,
387        ImageFormat::Apng => Skia::Apng,
388        ImageFormat::Svg => Skia::Svg,
389        ImageFormat::Pdf => Skia::Pdf,
390        ImageFormat::Raw => Skia::Raw,
391    }
392}
393
394/// Lowers this crate's options onto the renderer's, writing only the fields a
395/// caller set, so `fps: None` means the renderer's 30 rather than zero. Fields
396/// this crate does not expose, `density`, `msaa` and the rest, keep the
397/// renderer's defaults, of which there is one copy.
398fn to_skia_options(
399    options: &EncodeOptions,
400) -> meo_skia_canvas::export::EncodeOptions {
401    let mut lowered = meo_skia_canvas::export::EncodeOptions {
402        quality: options.quality,
403        lossless: options.lossless,
404        ..Default::default()
405    };
406    if let Some(matte) = options.matte {
407        // Packed `0xRRGGBB`, opaque: a matte is what transparency is flattened
408        // against, so a translucent one would leave some of it unflattened.
409        lowered.matte = Some(meo_skia_canvas::color::RgbaLinear::from_srgb8(
410            ((matte >> 16) & 0xff) as u8,
411            ((matte >> 8) & 0xff) as u8,
412            (matte & 0xff) as u8,
413            1.0,
414        ));
415    }
416    lowered.page = options.page;
417    lowered.fps = options.fps;
418    lowered.frame_delays.clone_from(&options.frame_delays);
419    lowered.loops = options.loops;
420
421    lowered
422}
423
424/// A painted surface's pages, resolved and ready to encode on any thread.
425///
426/// [`Send`] where a painted canvas is not, which is the whole of the point.
427/// An export has a cheap half that needs the canvas -- resolving which pages
428/// the call names, folding the surface's colour and text settings into the
429/// options, snapshotting each page's recorded drawing -- and an expensive half
430/// that does not. This is the boundary between them, so the second half can be
431/// handed to a worker while the thread that owns the canvas goes on with
432/// something else.
433///
434/// **The expensive half is nearly all of it.** Measured on this crate's
435/// pipeline: at 4000x4000 the record costs 2.74 ms and the encode 97.23 ms, so
436/// 97% of a `to_buffer` is on this side of the line. Rasterising is about a
437/// tenth of that -- 10.42 ms against a 97.24 ms PNG -- and it moves too, since
438/// nothing here rasterises until [`PreparedEncode::encode`] does.
439///
440/// **Bound to one format and one set of options.** They are fixed when the
441/// handle is taken rather than when it is used, because a rasterised page is
442/// cached under the options it was rasterised for: a handle is not
443/// format-neutral, and encoding one twice under two formats would hand back
444/// the first format's pixels. Two formats of one picture are two handles, both
445/// taken on the thread that owns the canvas.
446///
447/// **Nothing here needs a font.** The pages hold recorded drawings with their
448/// text already shaped, so a worker encoding one has no font registry to
449/// consult and cannot fall back to a face the caller did not register. That is
450/// what makes crossing the thread safe at all, because a registered family is
451/// visible only to the thread that registered it.
452pub struct PreparedEncode {
453    pages: meo_skia_canvas::Pages,
454    format: ImageFormat,
455}
456
457impl core::fmt::Debug for PreparedEncode {
458    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
459        // `Pages` does not implement `Debug`, and a dump of snapshotted Skia
460        // pictures would not help a reader. What it is for and how much of it
461        // there is are the two facts worth printing.
462        f.debug_struct("PreparedEncode")
463            .field("format", &self.format)
464            .field("pages", &self.pages.len())
465            .finish_non_exhaustive()
466    }
467}
468
469impl PreparedEncode {
470    /// The format this handle was taken for.
471    #[must_use]
472    pub const fn format(&self) -> ImageFormat {
473        self.format
474    }
475
476    /// How many pages this handle holds.
477    ///
478    /// The pages the call selected. Naming [`EncodeOptions::page`] does not
479    /// slice them -- that index is resolved when the bytes are produced -- so
480    /// a handle for one page of twenty still reports twenty.
481    #[must_use]
482    pub fn page_count(&self) -> usize {
483        self.pages.len()
484    }
485
486    /// Rasterises the pages and compresses them.
487    ///
488    /// Takes `self` because the handle is spent: see the type's own note on
489    /// why one handle is one format.
490    ///
491    /// # Errors
492    ///
493    /// Returns [`Error::Encode`] when the encoder rejects the drawing, which
494    /// for [`ImageFormat::Jpeg`] includes a surface whose alpha channel cannot
495    /// be flattened without a stated background.
496    pub fn encode(self) -> Result<EncodedImage, Error> {
497        let format = self.format;
498        let bytes = self.pages.encode().map_err(|error| Error::Encode {
499            format,
500            detail: error.to_string(),
501        })?;
502        Ok(EncodedImage { bytes, format })
503    }
504
505    /// Encodes the pages straight into a file.
506    ///
507    /// **Bounded by disk rather than by memory**, which is the reason to
508    /// prefer it over [`encode`](Self::encode) followed by a write: a format
509    /// that gathers every page streams into the file, where `encode` has to
510    /// hold the whole document to hand it back. A hundred-frame animation is
511    /// the case that makes the difference visible.
512    ///
513    /// The format is the one this handle was taken for, not one inferred from
514    /// the extension. A caller who has a path and no format asks
515    /// [`ImageFormat::from_named`] first, which is what the two public
516    /// surfaces do.
517    ///
518    /// **Which page or pages reach the file is decided in one place.** This
519    /// asks nothing about the format that [`encode`](Self::encode) does not
520    /// ask: both defer to the same handle, so an [`EncodeOptions::page`]
521    /// naming one frame of a GIF writes that frame here exactly as it encodes
522    /// that frame there. Asking it a second way -- a `format.spans_pages()`
523    /// beside the call, say -- is how the two paths come to disagree, and the
524    /// disagreement is silent: one file with every frame in it is a plausible
525    /// GIF.
526    ///
527    /// # Errors
528    ///
529    /// Returns [`Error::Encode`] for everything [`encode`](Self::encode)
530    /// reports, and for a file that cannot be written.
531    pub fn write(self, path: impl AsRef<std::path::Path>) -> Result<(), Error> {
532        let format = self.format;
533        self.pages.write(path).map_err(|error| Error::Encode {
534            format,
535            detail: error.to_string(),
536        })
537    }
538}
539
540/// Takes the half of an export that needs the surface, and stops there.
541///
542/// The counterpart to [`encode`], which is this followed immediately by
543/// [`PreparedEncode::encode`]. Split so a caller who wants the expensive half
544/// elsewhere can have it, and written as the one path so the two cannot drift:
545/// `encode` is defined in terms of this rather than beside it.
546///
547/// # Errors
548///
549/// Returns [`Error::Encode`] when the options do not suit the format -- see
550/// [`EncodeOptions::validate`] -- and when the surface cannot resolve the
551/// pages the options name.
552pub fn prepare(
553    surface: &mut crate::paint::Surface,
554    format: ImageFormat,
555    options: &EncodeOptions,
556) -> Result<PreparedEncode, Error> {
557    // The surface's page count, read before the mutable borrow the prepare
558    // needs: a page that failed to begin is not one the encoder can write.
559    // Validating before the snapshot means a caller error costs no snapshot,
560    // and with no `page_range` here the handle's own count would agree.
561    options.validate(format, surface.page_count())?;
562
563    // `&mut`, because `prepare_export` resolves the page selection against the
564    // canvas and folds the canvas's own colour and text settings into the
565    // options, which is a mutation of the canvas.
566    surface
567        .canvas_mut()
568        .prepare_export(to_skia_format(format), &to_skia_options(options))
569        .map(|pages| PreparedEncode { pages, format })
570        .map_err(|error| Error::Encode {
571            format,
572            detail: error.to_string(),
573        })
574}
575
576/// Encodes a painted surface.
577///
578/// Every page the surface holds is already drawn; which of them reach the file
579/// is the format's rule, and [`EncodeOptions::validate`] has already refused
580/// the combinations that cannot be honoured.
581///
582/// [`prepare`] followed by [`PreparedEncode::encode`], and defined as exactly
583/// that rather than as a second route to the same bytes: the two paths produce
584/// identical files because they are one path, not because a test found them
585/// equal.
586///
587/// # Errors
588///
589/// Returns [`Error::Encode`] when the options do not suit the format -- see
590/// [`EncodeOptions::validate`] -- or when the encoder rejects the surface,
591/// which for [`ImageFormat::Jpeg`] includes a surface whose alpha channel
592/// cannot be flattened without a stated background.
593pub fn encode(
594    surface: &mut crate::paint::Surface,
595    format: ImageFormat,
596    options: &EncodeOptions,
597) -> Result<EncodedImage, Error> {
598    prepare(surface, format, options)?.encode()
599}
600
601#[cfg(test)]
602mod tests {
603    use super::{EncodeOptions, ImageFormat};
604    use crate::Error;
605
606    #[test]
607    fn every_format_names_an_extension_a_name_and_a_media_type() {
608        for format in ImageFormat::ALL {
609            assert!(!format.extension().is_empty());
610            assert!(!format.name().is_empty());
611            assert!(
612                format.media_type().contains('/'),
613                "{format} has no media type"
614            );
615        }
616        // The one a caller is most likely to read, spelled out rather than
617        // only asserted structurally.
618        assert_eq!(ImageFormat::Png.media_type(), "image/png");
619        assert_eq!(ImageFormat::Jpeg.media_type(), "image/jpeg");
620        assert_eq!(ImageFormat::Raw.media_type(), "application/octet-stream");
621    }
622
623    #[test]
624    fn a_caller_may_name_raw_where_a_filename_may_not_imply_it() {
625        // The two questions this crate answers about a string, and the one
626        // place they differ. Inference from a filename found on disk refuses
627        // `raw`; a caller typing `.raw` has named it.
628        assert_eq!(ImageFormat::from_extension("raw"), None);
629        assert_eq!(ImageFormat::from_named("raw"), Some(ImageFormat::Raw));
630        assert_eq!(ImageFormat::from_named("RAW"), Some(ImageFormat::Raw));
631
632        // Everything else answers the same to both, so the pair cannot drift
633        // into two different tables.
634        for format in ImageFormat::ALL {
635            if *format == ImageFormat::Raw {
636                continue;
637            }
638            let extension = format.extension();
639            assert_eq!(
640                ImageFormat::from_named(extension),
641                ImageFormat::from_extension(extension),
642                "{format} answers differently to the two questions"
643            );
644        }
645        assert_eq!(ImageFormat::from_named("nonsense"), None);
646    }
647
648    #[test]
649    fn every_extension_this_crate_names_round_trips_through_the_renderer() {
650        // Each format's own extension resolves back to it, so the two tables
651        // agree on every entry rather than only on the ones a test happened to
652        // name. `raw` is the exception the renderer states: it is asked for by
653        // name and its `.bin` is deliberately not inferable.
654        for format in ImageFormat::ALL {
655            let resolved = ImageFormat::from_extension(format.extension());
656            if *format == ImageFormat::Raw {
657                assert_eq!(resolved, None, "raw should not be inferable");
658            } else {
659                assert_eq!(
660                    resolved,
661                    Some(*format),
662                    "{format} did not round-trip"
663                );
664            }
665        }
666    }
667
668    #[test]
669    fn an_unknown_extension_names_no_format() {
670        assert_eq!(ImageFormat::from_extension("docx"), None);
671        assert_eq!(ImageFormat::from_extension(""), None);
672    }
673
674    #[test]
675    fn no_two_formats_claim_the_same_extension() {
676        // Including APNG and PNG, which upstream registers separately. A
677        // collision here would make a filename ambiguous about what wrote it.
678        let mut extensions: Vec<&str> = ImageFormat::ALL
679            .iter()
680            .map(|format| format.extension())
681            .collect();
682        extensions.sort_unstable();
683        let total = extensions.len();
684        extensions.dedup();
685
686        assert_eq!(total, extensions.len());
687    }
688
689    #[test]
690    fn animated_formats_span_pages_but_not_every_spanning_format_is_animated() {
691        for format in ImageFormat::ALL {
692            assert!(
693                !format.is_animated() || format.spans_pages(),
694                "{format} is animated but writes one page"
695            );
696        }
697
698        // The pair that makes the two axes distinct: sheets, not frames.
699        for format in [ImageFormat::Pdf, ImageFormat::Tiff] {
700            assert!(format.spans_pages(), "{format} gathers every page");
701            assert!(!format.is_animated(), "{format} has no clock");
702        }
703    }
704
705    #[test]
706    fn timing_named_for_a_format_with_no_clock_is_refused() {
707        let options = EncodeOptions {
708            fps: Some(24.0),
709            ..EncodeOptions::default()
710        };
711
712        for format in ImageFormat::ALL {
713            let checked = options.validate(*format, 2);
714            if format.is_animated() {
715                assert!(checked.is_ok(), "{format} takes a frame rate");
716            } else {
717                assert!(
718                    matches!(checked, Err(Error::Encode { .. })),
719                    "{format} has no clock and should refuse one"
720                );
721            }
722        }
723    }
724
725    #[test]
726    fn this_crates_format_table_conforms_to_the_renderers() {
727        use meo_skia_canvas::export::ImageFormat as Skia;
728
729        /// The local format that lowers onto `upstream`, if this crate has one.
730        fn local(upstream: Skia) -> Option<ImageFormat> {
731            ImageFormat::ALL
732                .iter()
733                .copied()
734                .find(|format| super::to_skia_format(*format) == upstream)
735        }
736
737        // Driven from `Skia::all()` rather than `ImageFormat::ALL`, so a format
738        // the renderer gains and this crate has not mapped is a failure rather
739        // than a missing row. Collected, so three new formats report three.
740        let unmapped: Vec<Skia> = Skia::all()
741            .filter(|upstream| local(*upstream).is_none())
742            .collect();
743        assert!(
744            unmapped.is_empty(),
745            "the renderer has formats this crate does not map: {unmapped:?}"
746        );
747
748        let disagreements: Vec<String> = Skia::all()
749            .filter_map(|upstream| {
750                let ours = local(upstream)?;
751                let mut wrong = Vec::new();
752                if ours.extension() != upstream.extension() {
753                    wrong.push("extension");
754                }
755                if ours.is_animated() != upstream.is_animated() {
756                    wrong.push("is_animated");
757                }
758                if ours.spans_pages() != upstream.spans_pages() {
759                    wrong.push("spans_pages");
760                }
761                if ours.is_vector() != upstream.is_vector() {
762                    wrong.push("is_vector");
763                }
764                if ours.media_type() != upstream.mime_type() {
765                    wrong.push("media_type");
766                }
767                (!wrong.is_empty()).then(|| {
768                    format!("{ours} disagrees on {}", wrong.join(", "))
769                })
770            })
771            .collect();
772        assert!(
773            disagreements.is_empty(),
774            "this crate's table disagrees with the renderer's: {disagreements:?}"
775        );
776
777        // The other direction: a variant of ours lowering onto a format
778        // `all()` never yields would be one the renderer does not have.
779        assert_eq!(Skia::all().count(), ImageFormat::ALL.len());
780    }
781
782    #[test]
783    fn every_format_lowers_onto_the_renderers_own() {
784        use meo_skia_canvas::export::ImageFormat as Skia;
785
786        // A mapping that is total and injective is one that lost nothing. The
787        // two enums carry the same twelve formats, so anything else here is a
788        // format silently encoded as another.
789        let lowered: Vec<Skia> = ImageFormat::ALL
790            .iter()
791            .copied()
792            .map(super::to_skia_format)
793            .collect();
794
795        for (index, format) in lowered.iter().enumerate() {
796            assert!(
797                !lowered[..index].contains(format),
798                "two formats lower onto {format:?}"
799            );
800        }
801        assert_eq!(lowered.len(), ImageFormat::ALL.len());
802    }
803
804    #[test]
805    fn an_unset_option_keeps_the_renderers_default() {
806        // `fps: None` meaning 30 is the renderer's default, not a copy of the
807        // number held here.
808        let lowered = super::to_skia_options(&EncodeOptions::default());
809        let untouched = meo_skia_canvas::export::EncodeOptions::default();
810
811        assert_eq!(lowered.fps, untouched.fps);
812        assert_eq!(lowered.quality, untouched.quality);
813        assert_eq!(lowered.lossless, untouched.lossless);
814        assert!(lowered.matte.is_none());
815    }
816
817    #[test]
818    fn the_timing_fields_reach_the_renderer() {
819        let options = EncodeOptions {
820            fps: Some(12.0),
821            frame_delays: vec![80, 80],
822            loops: Some(3),
823            page: Some(1),
824            ..EncodeOptions::default()
825        };
826
827        let lowered = super::to_skia_options(&options);
828
829        assert_eq!(lowered.fps, Some(12.0));
830        assert_eq!(lowered.frame_delays, vec![80, 80]);
831        assert_eq!(lowered.loops, Some(3));
832        assert_eq!(lowered.page, Some(1));
833    }
834
835    #[test]
836    fn a_matte_unpacks_to_an_opaque_colour() {
837        // A matte is what transparency is flattened against, so a translucent
838        // one would leave some of it unflattened.
839        let options = EncodeOptions {
840            matte: Some(0x00_40_80),
841            ..EncodeOptions::default()
842        };
843
844        let lowered = super::to_skia_options(&options);
845        let matte = lowered
846            .matte
847            .unwrap_or_else(|| unreachable!("a matte was set"));
848
849        assert_eq!(matte.a.to_bits(), 1.0_f32.to_bits());
850        assert!(matte.r < matte.g && matte.g < matte.b);
851    }
852
853    #[test]
854    fn the_animated_set_is_the_one_v9_names() {
855        // v9's `AnimatedFormat` in `src/canvas/canvas.type.ts` is
856        // `'gif' | 'apng' | 'webp' | 'avif'`, and `meo-skia-canvas`'s traits
857        // table agrees. WebP and AVIF animate over a multi-page scene, though
858        // each is best known as a still format.
859        let animated: Vec<ImageFormat> = ImageFormat::ALL
860            .iter()
861            .copied()
862            .filter(|format| format.is_animated())
863            .collect();
864
865        assert_eq!(
866            animated,
867            vec![
868                ImageFormat::Webp,
869                ImageFormat::Avif,
870                ImageFormat::Gif,
871                ImageFormat::Apng
872            ]
873        );
874    }
875
876    #[test]
877    fn a_page_past_the_last_is_refused() {
878        let options = EncodeOptions {
879            page: Some(3),
880            ..EncodeOptions::default()
881        };
882
883        assert!(matches!(
884            options.validate(ImageFormat::Png, 3),
885            Err(Error::Encode { .. })
886        ));
887        assert!(options.validate(ImageFormat::Png, 4).is_ok());
888    }
889
890    #[test]
891    fn a_named_page_wins_over_the_format_spanning_them() {
892        // Asking for one page of a PDF writes a one-sheet PDF. The
893        // `frame_delays` length is checked against what is written, so
894        // the two rules have to agree or a correctly sized list is
895        // refused.
896        let all = EncodeOptions::default();
897        assert_eq!(all.written_pages(ImageFormat::Pdf, 5), 5);
898
899        let one = EncodeOptions {
900            page: Some(1),
901            ..EncodeOptions::default()
902        };
903        assert_eq!(one.written_pages(ImageFormat::Pdf, 5), 1);
904        assert_eq!(one.written_pages(ImageFormat::Png, 5), 1);
905    }
906
907    #[test]
908    fn frame_delays_must_hold_one_entry_per_written_page() {
909        let short = EncodeOptions {
910            frame_delays: vec![100, 100],
911            ..EncodeOptions::default()
912        };
913        assert!(matches!(
914            short.validate(ImageFormat::Gif, 3),
915            Err(Error::Encode { .. })
916        ));
917
918        let exact = EncodeOptions {
919            frame_delays: vec![100, 100, 100],
920            ..EncodeOptions::default()
921        };
922        assert!(exact.validate(ImageFormat::Gif, 3).is_ok());
923
924        // One named page writes one frame, so one delay is the right count
925        // even though the scene carries three pages.
926        let single = EncodeOptions {
927            page: Some(0),
928            frame_delays: vec![100],
929            ..EncodeOptions::default()
930        };
931        assert!(single.validate(ImageFormat::Gif, 3).is_ok());
932    }
933
934    #[test]
935    fn a_scene_of_one_page_encodes_to_a_still_image_in_every_format() {
936        let options = EncodeOptions::default();
937        for format in ImageFormat::ALL {
938            assert!(
939                options.validate(*format, 1).is_ok(),
940                "{format} refused one page"
941            );
942            assert_eq!(options.written_pages(*format, 1), 1);
943        }
944    }
945
946    #[test]
947    fn only_the_two_vector_formats_are_vector() {
948        let vector: Vec<ImageFormat> = ImageFormat::ALL
949            .iter()
950            .copied()
951            .filter(|format| format.is_vector())
952            .collect();
953
954        assert_eq!(vector, vec![ImageFormat::Svg, ImageFormat::Pdf]);
955    }
956}
957
958#[cfg(test)]
959mod ico_pages {
960    use meo_canvas_scene::Size;
961
962    use super::{ImageFormat, encode};
963    use crate::paint::{Surface, SurfaceOptions};
964
965    /// One directory entry of an ICO, as the file writes it.
966    #[derive(Debug, PartialEq, Eq)]
967    struct Entry {
968        width: u32,
969        height: u32,
970    }
971
972    /// Reads an ICO's directory from the bytes written: `ImageFormat::Ico`
973    /// promises something about the file. A six-byte header, then `count`
974    /// entries of sixteen bytes starting with width and height, where one byte
975    /// cannot hold 256 and so zero means 256.
976    fn directory(bytes: &[u8]) -> Vec<Entry> {
977        assert!(bytes.len() >= 6, "an ICO has at least a header");
978        assert_eq!(
979            u16::from_le_bytes([bytes[0], bytes[1]]),
980            0,
981            "the reserved field is not zero, so this is not an ICO"
982        );
983        assert_eq!(
984            u16::from_le_bytes([bytes[2], bytes[3]]),
985            1,
986            "the type field does not say icon"
987        );
988        let count = usize::from(u16::from_le_bytes([bytes[4], bytes[5]]));
989        (0..count)
990            .map(|index| {
991                let at = 6 + index * 16;
992                let dimension = |byte: u8| {
993                    if byte == 0 { 256 } else { u32::from(byte) }
994                };
995                Entry {
996                    width: dimension(bytes[at]),
997                    height: dimension(bytes[at + 1]),
998                }
999            })
1000            .collect()
1001    }
1002
1003    #[test]
1004    fn an_ico_carries_one_directory_entry_per_page_at_that_page_s_own_size() {
1005        let sizes = [16.0_f32, 32.0, 48.0, 256.0];
1006        let mut surface = Surface::new(
1007            Size {
1008                width: sizes[0],
1009                height: sizes[0],
1010            },
1011            1.0,
1012            SurfaceOptions::default(),
1013        )
1014        .unwrap_or_else(|error| {
1015            unreachable!("the surface did not allocate: {error}")
1016        });
1017
1018        for &side in &sizes[1..] {
1019            surface
1020                .begin_page(Size {
1021                    width: side,
1022                    height: side,
1023                })
1024                .unwrap_or_else(|error| {
1025                    unreachable!("a page did not begin: {error}")
1026                });
1027        }
1028
1029        let written = encode(
1030            &mut surface,
1031            ImageFormat::Ico,
1032            &super::EncodeOptions::default(),
1033        )
1034        .unwrap_or_else(|error| {
1035            unreachable!("the ICO did not encode: {error}")
1036        });
1037
1038        let entries = directory(&written.bytes);
1039        assert_eq!(
1040            entries,
1041            sizes
1042                .iter()
1043                .map(|&side| Entry {
1044                    #[expect(
1045                        clippy::cast_possible_truncation,
1046                        clippy::cast_sign_loss,
1047                        reason = "every side here is a small whole number"
1048                    )]
1049                    width: side as u32,
1050                    #[expect(
1051                        clippy::cast_possible_truncation,
1052                        clippy::cast_sign_loss,
1053                        reason = "every side here is a small whole number"
1054                    )]
1055                    height: side as u32,
1056                })
1057                .collect::<Vec<_>>(),
1058            "the pages went in at four sizes and the directory should say so"
1059        );
1060    }
1061}