Skip to main content

webp/api/
encode.rs

1//! Safe Rust API over the encoder of the translation; no upstream unit.
2//!
3//! Wraps the translated types and functions in validated Rust types and adds
4//! no codec behavior of its own; see `docs/adr/`.
5//!
6//! Work package: WP17 (safe encoder API).
7//!
8//! The decision record is `docs/adr/0006-safe-encoder-api.md`. Every encoding
9//! calls the translated `WebPEncode` ([`webp_encode`]) with the stored
10//! [`WebPConfig`], so its output is byte-identical to libwebp v1.6.0 with the
11//! same configuration and samples. The API validates dimensions, strides,
12//! buffer lengths and floating-point parameters first, so that caller input
13//! never reaches a panic of the translation, and reports failures as
14//! [`EncodeError`].
15//!
16//! # Example
17//!
18//! ```
19//! use webp::api::encode::{Config, Encoder, Picture, PixelLayout, PixelRows, SampleForm};
20//!
21//! // A 4 by 2 RGBA picture, rows packed.
22//! let rgba = [255_u8, 0, 0, 255].repeat(8);
23//! let rows = PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 4, height: 2, stride: 16 };
24//! let mut picture = Picture::import(rows, SampleForm::Argb)?;
25//! let config = Config::new().quality(80.0).method(4);
26//! let webp = Encoder::new(&config).encode(&mut picture)?;
27//! assert_eq!(&webp[..4], b"RIFF");
28//! assert_eq!(&webp[8..12], b"WEBP");
29//! # Ok::<(), webp::api::encode::EncodeError>(())
30//! ```
31//!
32//! # Pictures and memory
33//!
34//! [`Picture::import`] copies strided rows into planes that the picture
35//! allocates. [`Picture::from_argb`] and [`Picture::from_yuva`] borrow planes
36//! that the caller allocated, exclusively for the picture's lifetime, so that
37//! the caller can account for that memory; libwebp writes into them where the
38//! semantics below say so. Strides count elements of the slice's type: bytes
39//! for `&[u8]` rows and planes, pixels for the `&mut [u32]` ARGB plane. The
40//! encoder converts what it needs: a lossy encoding of an ARGB picture
41//! allocates YUVA planes, a lossless encoding of a YUVA picture an ARGB plane.
42//! Those planes stay with the picture and [`Picture::owned_sample_bytes`]
43//! counts them; the encoder's internal state is not observable.
44//!
45//! # Semantics
46//!
47//! - **Lossy samples** are ITU-R BT.601 `Y'CbCr` 4:2:0 in limited range (Y 16 to
48//!   235, Cb and Cr 16 to 240), converted with the fixed-point constants of
49//!   libwebp's `src/dsp/yuv.h` and gamma-corrected chroma averaging, which is
50//!   weighted by alpha in blocks with transparency; a decoder converts back
51//!   with the same matrix. Sharp YUV ([`Config::sharp_yuv`]) and dithering
52//!   (`preprocessing` bit 2, through [`Config::raw_mut`]) apply only when the
53//!   picture holds ARGB samples at encoding time ([`SampleForm::Argb`] or
54//!   [`Picture::from_argb`]); [`SampleForm::Yuva`] converts during the import,
55//!   without them, as libwebp does. Planes from [`Picture::from_yuva`] are
56//!   encoded as they are.
57//! - **Alpha** is straight (not premultiplied); the encoder has no
58//!   premultiplied input. Unless [`Config::exact`] is set, the encoder rewrites
59//!   the samples under fully transparent areas in the picture's planes, the
60//!   caller's included: in 8 by 8 blocks of the Y, U and V planes for a lossy
61//!   encoding, and every transparent ARGB pixel becomes 0 for a lossless one.
62//!   `show_compressed` (through [`Config::raw_mut`]) writes the decoded samples
63//!   back into the Y, U and V planes.
64//! - **Metadata**: the output is a still WebP file with no `ICCP`, `EXIF` or
65//!   `XMP` chunk; WebP carries no other color or orientation signal. Metadata
66//!   and animation belong to the muxer (WP15).
67//!
68//! # Deviations from upstream
69//!
70//! Changes of representation that the ADRs allow, or behavior that the Rust
71//! side cannot reproduce exactly. Each records the reason.
72//!
73//! 1. **Early refusal of dimensions.** Widths and heights above 16383 are
74//!    refused with `InvalidDimensions` before anything is allocated; C imports
75//!    them and fails in `WebPEncode` with `VP8_ENC_ERROR_BAD_DIMENSION`. Zero
76//!    dimensions are refused as well, where C fails the import.
77//! 2. **Floats.** A NaN or infinite `quality` or `target_psnr` is refused with
78//!    `InvalidParameter`; C accepts it and converts it to an integer, which is
79//!    undefined. A quality outside 0 to 100 is `InvalidParameter`, where C
80//!    reports `INVALID_CONFIGURATION` (or `WebPConfigPreset` returns 0).
81//! 3. **Row strides of the X layouts** must hold four bytes per pixel, and the
82//!    last row `width * bytes_per_pixel` bytes; C checks three bytes per pixel,
83//!    which lets RGBX and BGRX rows overlap, and reads `4 * width - 1` bytes of
84//!    the last row.
85//! 4. **Negative strides and dimensions** cannot be expressed (`u32`, `usize`),
86//!    so bottom-up rows are not accepted (C reads them upward; the translation
87//!    panics on them, see item 4 of `# Deviations from upstream` in
88//!    `src/enc/picture_enc.rs`).
89//! 5. **`Encoder::encode`** returns the bytes only on success; C's memory
90//!    writer keeps the partial output of a failed encoding. Its vector keeps
91//!    the memory writer's capacity, up to twice the length.
92//! 6. **`target_size`** takes a `u32` and saturates at `i32::MAX`, C's `int`.
93//! 7. **Panicking callbacks** leave the picture without planes; C has no
94//!    panics.
95//! 8. **The simple functions** return the recorded error instead of C's 0, and
96//!    accept RGBX and BGRX, which C's simple API lacks; their bytes are C's.
97//! 9. **A successful encoding is `Ok`** even when libwebp recorded
98//!    `VP8_ENC_ERROR_USER_ABORT` at a report whose answer it ignores
99//!    (`ResetAllMBInfo` in `src/enc/analysis_enc.c`, and `StatLoop`, whose
100//!    result `VP8EncLoop` in `src/enc/frame_enc.c` drops for lossy methods 0 to
101//!    2); C returns 1 and leaves the code in the picture, which the API does
102//!    not expose on success.
103//! 10. **Callbacks** receive no picture (ADR 0003, as in the translation).
104//!
105//! # Upstream behavior preserved
106//!
107//! Behavior of the C code that a reader might take for a defect, which the
108//! translation keeps:
109//!
110//! 1. **The encoder writes into the picture's planes unless `exact`:** the Y, U
111//!    and V samples under fully transparent 8 by 8 blocks (lossy), every
112//!    transparent ARGB pixel to 0 (lossless), and with `show_compressed` the
113//!    decoded samples. A second encoding of a picture sees these writes and the
114//!    planes of the first encoding's conversion.
115//! 2. **A lossy encoding of ARGB samples converts with sharp YUV or dithering**
116//!    when configured; an import into YUVA converts at once without them.
117//! 3. **`WebPConfigLosslessPreset` overrides `lossless`, `method` and
118//!    `quality`.**
119//! 4. **libwebp ignores the progress hook's answer** at the end of an analysis
120//!    without segments and during the statistics pass of lossy methods 0 to 2;
121//!    the documentation of `Encoder::progress` tells a cancelling hook to keep
122//!    returning `false`.
123//!
124//! # Checks not applicable
125//!
126//! These checks do not apply, or cannot be made, with the reason:
127//!
128//! 1. **Source correspondence.** This module translates no upstream unit, so
129//!    there are no `// upstream:` markers, no `tools/rust_name.py` names and no
130//!    probe of its own.
131//! 2. **`NULL` arguments** do not exist in the API (references and slices).
132//! 3. **Views, crop, rescale, distortion, alpha blending, `extra_info` and the
133//!    standalone conversions** are not in the API (ADR 0006); their cases in
134//!    `tests/support/wp13_cases.rs` are left out or run without the map.
135//!    Metadata chunks and animation belong to the muxer and the animation
136//!    encoder in `src/mux/`.
137//! 4. **Undefined behavior in C.** The exclusions of the encoder translation
138//!    hold through its case records (statistics of alpha with
139//!    `alpha_compression` 0 and of failed threaded alpha encodings,
140//!    `extra_info_type` 6), and the simple-API test skips
141//!    `WebPEncodeLosslessRGBA` on misaligned rows (see
142//!    `# Excluded undefined behavior` in `src/enc/picture_csp_enc.rs`). The API
143//!    accepts such rows; the translation reads them as bytes, which C cannot
144//!    confirm.
145//! 5. **Allocation failures** are not injected; `OutOfMemory`, `BadWrite` from
146//!    a refused memory-writer growth and `Unreported` are reached only through
147//!    the translation's fallible reservations.
148//! 6. **32-bit targets** are not run; the `usize` overflow of a plane's extent
149//!    maps to `InvalidStride` and is reachable there only.
150
151use std::fmt;
152
153use crate::enc::config_enc::{webp_config_lossless_preset, webp_validate_config};
154use crate::enc::picture_csp_enc::{
155    webp_picture_import_bgr, webp_picture_import_bgra, webp_picture_import_bgrx,
156    webp_picture_import_rgb, webp_picture_import_rgba, webp_picture_import_rgbx,
157};
158use crate::enc::picture_enc::{
159    LOSSLESS_DEFAULT_QUALITY, webp_memory_write, webp_memory_writer_init,
160};
161use crate::enc::webp_enc::webp_encode;
162pub use crate::webp::encode::WebPAuxStats;
163use crate::webp::encode::{
164    WEBP_MAX_DIMENSION, WebPConfig, WebPEncCSP, WebPEncodingError, WebPImageHint, WebPMemoryWriter,
165    WebPPicture, WebPPreset, webp_config_init, webp_config_preset, webp_picture_init,
166};
167use crate::webp::types::{PlaneOffset, PlaneStorage};
168
169//------------------------------------------------------------------------------
170// Enumerations
171
172/// A predefined configuration set, tuned for a kind of content (C:
173/// `WebPPreset`).
174///
175/// # Examples
176///
177/// ```
178/// use webp::api::encode::{Config, Preset};
179///
180/// let config = Config::preset(Preset::Photo, 80.0)?;
181/// assert_eq!(config.as_raw().quality, 80.0);
182/// # Ok::<(), webp::api::encode::EncodeError>(())
183/// ```
184#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
185pub enum Preset {
186    /// The default preset (C: `WEBP_PRESET_DEFAULT`).
187    #[default]
188    Default,
189    /// A digital picture, such as a portrait or an indoor shot
190    /// (C: `WEBP_PRESET_PICTURE`).
191    Picture,
192    /// An outdoor photograph with natural lighting (C: `WEBP_PRESET_PHOTO`).
193    Photo,
194    /// A hand or line drawing with high-contrast details
195    /// (C: `WEBP_PRESET_DRAWING`).
196    Drawing,
197    /// A small, colorful image (C: `WEBP_PRESET_ICON`).
198    Icon,
199    /// Text-like content (C: `WEBP_PRESET_TEXT`).
200    Text,
201}
202
203impl Preset {
204    const fn raw(self) -> WebPPreset {
205        match self {
206            Self::Default => WebPPreset::WEBP_PRESET_DEFAULT,
207            Self::Picture => WebPPreset::WEBP_PRESET_PICTURE,
208            Self::Photo => WebPPreset::WEBP_PRESET_PHOTO,
209            Self::Drawing => WebPPreset::WEBP_PRESET_DRAWING,
210            Self::Icon => WebPPreset::WEBP_PRESET_ICON,
211            Self::Text => WebPPreset::WEBP_PRESET_TEXT,
212        }
213    }
214}
215
216/// A hint about the content that the lossless encoder uses
217/// (C: `WebPImageHint`).
218///
219/// # Examples
220///
221/// ```
222/// use webp::api::encode::{Config, ImageHint};
223///
224/// let config = Config::new().lossless(true).image_hint(ImageHint::Graph);
225/// assert_eq!(config.as_raw().image_hint.0, 3);
226/// ```
227#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
228pub enum ImageHint {
229    /// No hint (C: `WEBP_HINT_DEFAULT`).
230    #[default]
231    Default,
232    /// A digital picture, such as a portrait or an indoor shot
233    /// (C: `WEBP_HINT_PICTURE`).
234    Picture,
235    /// An outdoor photograph with natural lighting (C: `WEBP_HINT_PHOTO`).
236    Photo,
237    /// A discrete-tone image such as a graph or map (C: `WEBP_HINT_GRAPH`).
238    Graph,
239}
240
241impl ImageHint {
242    const fn raw(self) -> WebPImageHint {
243        match self {
244            Self::Default => WebPImageHint::WEBP_HINT_DEFAULT,
245            Self::Picture => WebPImageHint::WEBP_HINT_PICTURE,
246            Self::Photo => WebPImageHint::WEBP_HINT_PHOTO,
247            Self::Graph => WebPImageHint::WEBP_HINT_GRAPH,
248        }
249    }
250}
251
252/// The predictive filter of the alpha plane in a lossy encoding
253/// (C: `WebPConfig::alpha_filtering` 0, 1 and 2).
254///
255/// # Examples
256///
257/// ```
258/// use webp::api::encode::{AlphaFilter, Config};
259///
260/// let config = Config::new().alpha_filter(AlphaFilter::Best);
261/// assert_eq!(config.as_raw().alpha_filtering, 2);
262/// ```
263#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
264pub enum AlphaFilter {
265    /// No filter (C: 0).
266    None,
267    /// The fast filter, the default (C: 1).
268    #[default]
269    Fast,
270    /// The best filter, slower (C: 2).
271    Best,
272}
273
274impl AlphaFilter {
275    const fn raw(self) -> i32 {
276        match self {
277            Self::None => 0,
278            Self::Fast => 1,
279            Self::Best => 2,
280        }
281    }
282}
283
284/// The order of the channels of packed rows, as libwebp's six importers read
285/// them (C: `WebPPictureImportRGB` and its siblings).
286///
287/// # Examples
288///
289/// ```
290/// use webp::api::encode::PixelLayout;
291///
292/// assert_eq!(PixelLayout::Bgr.bytes_per_pixel(), 3);
293/// assert_eq!(PixelLayout::Rgbx.bytes_per_pixel(), 4);
294/// ```
295#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
296pub enum PixelLayout {
297    /// Red, green, blue (C: `WebPPictureImportRGB`).
298    Rgb,
299    /// Red, green, blue, straight alpha (C: `WebPPictureImportRGBA`).
300    Rgba,
301    /// Red, green, blue and an ignored byte (C: `WebPPictureImportRGBX`).
302    Rgbx,
303    /// Blue, green, red (C: `WebPPictureImportBGR`).
304    Bgr,
305    /// Blue, green, red, straight alpha (C: `WebPPictureImportBGRA`).
306    Bgra,
307    /// Blue, green, red and an ignored byte (C: `WebPPictureImportBGRX`).
308    Bgrx,
309}
310
311impl PixelLayout {
312    /// The bytes of one pixel: 3 or 4.
313    ///
314    /// # Examples
315    ///
316    /// ```
317    /// use webp::api::encode::PixelLayout;
318    ///
319    /// assert_eq!(PixelLayout::Rgba.bytes_per_pixel(), 4);
320    /// ```
321    #[must_use]
322    pub const fn bytes_per_pixel(self) -> usize {
323        match self {
324            Self::Rgb | Self::Bgr => 3,
325            Self::Rgba | Self::Rgbx | Self::Bgra | Self::Bgrx => 4,
326        }
327    }
328
329    fn importer(self) -> fn(&mut WebPPicture<'_>, &[u8], i32) -> bool {
330        match self {
331            Self::Rgb => webp_picture_import_rgb,
332            Self::Rgba => webp_picture_import_rgba,
333            Self::Rgbx => webp_picture_import_rgbx,
334            Self::Bgr => webp_picture_import_bgr,
335            Self::Bgra => webp_picture_import_bgra,
336            Self::Bgrx => webp_picture_import_bgrx,
337        }
338    }
339}
340
341/// The samples that an imported picture keeps (C: `WebPPicture::use_argb`).
342///
343/// # Examples
344///
345/// ```
346/// use webp::api::encode::{Picture, PixelLayout, PixelRows, SampleForm};
347///
348/// let rgb = [10_u8, 20, 30].repeat(4);
349/// let rows = PixelRows { layout: PixelLayout::Rgb, data: &rgb, width: 2, height: 2, stride: 6 };
350/// let yuva = Picture::import(rows, SampleForm::Yuva)?;
351/// let argb = Picture::import(rows, SampleForm::Argb)?;
352/// assert_eq!(yuva.owned_sample_bytes(), 4 + 1 + 1);
353/// assert_eq!(argb.owned_sample_bytes(), 4 * 4);
354/// # Ok::<(), webp::api::encode::EncodeError>(())
355/// ```
356#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
357pub enum SampleForm {
358    /// Y, U and V planes (4:2:0), and an alpha plane when the rows are not
359    /// opaque: what the lossy encoder reads. The conversion happens during the
360    /// import, without sharp YUV or dithering.
361    Yuva,
362    /// One plane of ARGB pixels: what the lossless encoder reads. A lossy
363    /// encoding converts it at encoding time, with sharp YUV or dithering
364    /// when the configuration asks for them.
365    Argb,
366}
367
368/// The input that an [`EncodeError`] refers to.
369///
370/// # Examples
371///
372/// ```
373/// use webp::api::encode::{EncodeError, Picture, Plane};
374///
375/// let mut argb = vec![0_u32; 3];
376/// let error = Picture::from_argb(&mut argb, 2, 2, 2).unwrap_err();
377/// assert_eq!(error, EncodeError::BufferTooShort { plane: Plane::Argb, len: 3, needed: 4 });
378/// ```
379#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
380pub enum Plane {
381    /// The packed rows of [`PixelRows`].
382    Pixels,
383    /// The luma plane of [`YuvaPlanes`].
384    Y,
385    /// The U chroma plane of [`YuvaPlanes`].
386    U,
387    /// The V chroma plane of [`YuvaPlanes`].
388    V,
389    /// The alpha plane of [`YuvaPlanes`].
390    A,
391    /// The ARGB plane of [`Picture::from_argb`].
392    Argb,
393}
394
395//------------------------------------------------------------------------------
396// Errors
397
398/// Why an encoding or one of its inputs failed.
399///
400/// The variants up to [`EncodeError::Unreported`] are the codes that libwebp
401/// records in `WebPPicture::error_code`, with C's rule that the first recorded
402/// error is kept; [`EncodeError::code`] returns the C code. The others are the
403/// API's own validation, which runs before the translation is called.
404///
405/// # Examples
406///
407/// ```
408/// use webp::api::encode::{Config, EncodeError};
409///
410/// let error = Config::new().quality(f32::NAN).validate().unwrap_err();
411/// assert_eq!(error, EncodeError::InvalidParameter { name: "quality" });
412/// assert_eq!(error.code(), None);
413/// assert_eq!(error.to_string(), "invalid parameter: quality");
414/// ```
415#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
416#[non_exhaustive]
417pub enum EncodeError {
418    /// Memory for the picture or the encoder could not be allocated
419    /// (C: `VP8_ENC_ERROR_OUT_OF_MEMORY`).
420    OutOfMemory,
421    /// Memory for the bitstream could not be allocated
422    /// (C: `VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY`).
423    BitstreamOutOfMemory,
424    /// A required plane is missing (C: `VP8_ENC_ERROR_NULL_PARAMETER`); the
425    /// picture of an encoding whose callback panicked has no planes.
426    NullParameter,
427    /// The configuration fails libwebp's validation, or the encoder rejects a
428    /// combination (C: `VP8_ENC_ERROR_INVALID_CONFIGURATION`).
429    InvalidConfiguration,
430    /// The picture's dimensions are rejected (C: `VP8_ENC_ERROR_BAD_DIMENSION`).
431    BadDimension,
432    /// The first partition exceeds 512 KiB (C:
433    /// `VP8_ENC_ERROR_PARTITION0_OVERFLOW`); a lower quality or more segments
434    /// help.
435    Partition0Overflow,
436    /// A token partition exceeds 16 MiB (C: `VP8_ENC_ERROR_PARTITION_OVERFLOW`).
437    PartitionOverflow,
438    /// The writer returned `false`, or the memory writer could not grow
439    /// (C: `VP8_ENC_ERROR_BAD_WRITE`).
440    BadWrite,
441    /// The file would exceed 4 GiB (C: `VP8_ENC_ERROR_FILE_TOO_BIG`).
442    FileTooBig,
443    /// The progress hook returned `false` (C: `VP8_ENC_ERROR_USER_ABORT`).
444    UserAbort,
445    /// The encoder failed without recording a code (C returns 0 with
446    /// `VP8_ENC_OK`; libwebp does so when `QuantizeLevels` runs out of memory).
447    Unreported,
448    /// The width or height is 0 or above 16383 (`WEBP_MAX_DIMENSION`).
449    InvalidDimensions {
450        /// The width given.
451        width: u32,
452        /// The height given.
453        height: u32,
454    },
455    /// A stride is shorter than a row, longer than `i32::MAX`, or so long that
456    /// the plane's extent does not fit in `usize`.
457    InvalidStride {
458        /// The input with the stride.
459        plane: Plane,
460        /// The stride given, in elements of the input's type.
461        stride: usize,
462    },
463    /// A buffer is shorter than its rows: `(rows - 1) * stride + row length`
464    /// elements.
465    BufferTooShort {
466        /// The input that is too short.
467        plane: Plane,
468        /// Its length, in elements.
469        len: usize,
470        /// The elements that its dimensions and stride address.
471        needed: usize,
472    },
473    /// A parameter is outside the range the API accepts: `quality` (finite,
474    /// 0 to 100), `target_psnr` (finite) or `lossless_level` (0 to 9).
475    InvalidParameter {
476        /// The parameter's name.
477        name: &'static str,
478    },
479}
480
481impl EncodeError {
482    /// The `WebPEncodingError` that libwebp recorded for this error, or `None`
483    /// for an error of the API's own validation. [`EncodeError::Unreported`]
484    /// returns `VP8_ENC_OK`, the code C leaves in that case.
485    ///
486    /// # Examples
487    ///
488    /// ```
489    /// use webp::api::encode::EncodeError;
490    /// use webp::webp::encode::WebPEncodingError;
491    ///
492    /// assert_eq!(EncodeError::UserAbort.code(), Some(WebPEncodingError::VP8_ENC_ERROR_USER_ABORT));
493    /// assert_eq!(EncodeError::InvalidDimensions { width: 0, height: 1 }.code(), None);
494    /// ```
495    #[must_use]
496    pub const fn code(&self) -> Option<WebPEncodingError> {
497        Some(match self {
498            Self::OutOfMemory => WebPEncodingError::VP8_ENC_ERROR_OUT_OF_MEMORY,
499            Self::BitstreamOutOfMemory => WebPEncodingError::VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY,
500            Self::NullParameter => WebPEncodingError::VP8_ENC_ERROR_NULL_PARAMETER,
501            Self::InvalidConfiguration => WebPEncodingError::VP8_ENC_ERROR_INVALID_CONFIGURATION,
502            Self::BadDimension => WebPEncodingError::VP8_ENC_ERROR_BAD_DIMENSION,
503            Self::Partition0Overflow => WebPEncodingError::VP8_ENC_ERROR_PARTITION0_OVERFLOW,
504            Self::PartitionOverflow => WebPEncodingError::VP8_ENC_ERROR_PARTITION_OVERFLOW,
505            Self::BadWrite => WebPEncodingError::VP8_ENC_ERROR_BAD_WRITE,
506            Self::FileTooBig => WebPEncodingError::VP8_ENC_ERROR_FILE_TOO_BIG,
507            Self::UserAbort => WebPEncodingError::VP8_ENC_ERROR_USER_ABORT,
508            Self::Unreported => WebPEncodingError::VP8_ENC_OK,
509            Self::InvalidDimensions { .. }
510            | Self::InvalidStride { .. }
511            | Self::BufferTooShort { .. }
512            | Self::InvalidParameter { .. } => return None,
513        })
514    }
515
516    /// The error for the code that a failed call of the translation recorded.
517    const fn from_code(code: WebPEncodingError) -> Self {
518        match code {
519            WebPEncodingError::VP8_ENC_ERROR_OUT_OF_MEMORY => Self::OutOfMemory,
520            WebPEncodingError::VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY => Self::BitstreamOutOfMemory,
521            WebPEncodingError::VP8_ENC_ERROR_NULL_PARAMETER => Self::NullParameter,
522            WebPEncodingError::VP8_ENC_ERROR_INVALID_CONFIGURATION => Self::InvalidConfiguration,
523            WebPEncodingError::VP8_ENC_ERROR_BAD_DIMENSION => Self::BadDimension,
524            WebPEncodingError::VP8_ENC_ERROR_PARTITION0_OVERFLOW => Self::Partition0Overflow,
525            WebPEncodingError::VP8_ENC_ERROR_PARTITION_OVERFLOW => Self::PartitionOverflow,
526            WebPEncodingError::VP8_ENC_ERROR_BAD_WRITE => Self::BadWrite,
527            WebPEncodingError::VP8_ENC_ERROR_FILE_TOO_BIG => Self::FileTooBig,
528            WebPEncodingError::VP8_ENC_ERROR_USER_ABORT => Self::UserAbort,
529            _ => Self::Unreported,
530        }
531    }
532}
533
534impl fmt::Display for EncodeError {
535    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
536        match self {
537            Self::OutOfMemory => f.write_str("out of memory"),
538            Self::BitstreamOutOfMemory => f.write_str("out of memory for the bitstream"),
539            Self::NullParameter => f.write_str("a required plane is missing"),
540            Self::InvalidConfiguration => f.write_str("invalid configuration"),
541            Self::BadDimension => f.write_str("invalid picture dimensions"),
542            Self::Partition0Overflow => f.write_str("the first partition exceeds 512 KiB"),
543            Self::PartitionOverflow => f.write_str("a token partition exceeds 16 MiB"),
544            Self::BadWrite => f.write_str("the writer failed"),
545            Self::FileTooBig => f.write_str("the file would exceed 4 GiB"),
546            Self::UserAbort => f.write_str("aborted by the progress hook"),
547            Self::Unreported => f.write_str("the encoder failed without an error code"),
548            Self::InvalidDimensions { width, height } => write!(
549                f,
550                "invalid dimensions {width} by {height}: each must be 1 to {WEBP_MAX_DIMENSION}"
551            ),
552            Self::InvalidStride { plane, stride } => {
553                write!(f, "invalid stride {stride} for the {plane:?} plane")
554            }
555            Self::BufferTooShort { plane, len, needed } => write!(
556                f,
557                "the {plane:?} plane holds {len} elements, its rows need {needed}"
558            ),
559            Self::InvalidParameter { name } => write!(f, "invalid parameter: {name}"),
560        }
561    }
562}
563
564impl std::error::Error for EncodeError {}
565
566//------------------------------------------------------------------------------
567// Configuration
568
569/// The API's own check of a quality: finite and in 0 to 100.
570fn check_quality(quality: f32) -> Result<(), EncodeError> {
571    if quality.is_finite() && (0.0..=100.0).contains(&quality) {
572        Ok(())
573    } else {
574        Err(EncodeError::InvalidParameter { name: "quality" })
575    }
576}
577
578/// Compression parameters: a [`WebPConfig`] with typed setters.
579///
580/// The setters store their value in the matching C field and never fail;
581/// [`Config::validate`], which every encoding calls first, reports a value
582/// that is out of range. [`Config::raw_mut`] reaches the fields without a
583/// setter (segments, filters, passes, partitions and the like).
584///
585/// # Examples
586///
587/// ```
588/// use webp::api::encode::{AlphaFilter, Config, ImageHint, Preset};
589///
590/// let lossy = Config::preset(Preset::Picture, 82.0)?
591///     .method(6)
592///     .alpha_quality(90)
593///     .alpha_filter(AlphaFilter::Best)
594///     .sharp_yuv(true);
595/// lossy.validate()?;
596///
597/// let lossless = Config::new().lossless_level(9)?.exact(true).image_hint(ImageHint::Photo);
598/// assert_eq!(lossless.as_raw().lossless, 1);
599/// # Ok::<(), webp::api::encode::EncodeError>(())
600/// ```
601#[derive(Clone, Copy, Debug, PartialEq)]
602pub struct Config {
603    raw: WebPConfig,
604}
605
606impl Default for Config {
607    fn default() -> Self {
608        Self::new()
609    }
610}
611
612impl From<WebPConfig> for Config {
613    /// Wraps a configuration of the translation as it is; [`Config::validate`]
614    /// checks it.
615    fn from(raw: WebPConfig) -> Self {
616        Self { raw }
617    }
618}
619
620impl Config {
621    /// The default configuration: the default preset at quality 75, lossy
622    /// (C: `WebPConfigInit`).
623    ///
624    /// # Examples
625    ///
626    /// ```
627    /// use webp::api::encode::Config;
628    ///
629    /// let config = Config::new();
630    /// assert_eq!((config.as_raw().quality, config.as_raw().method), (75.0, 4));
631    /// ```
632    #[must_use]
633    pub fn new() -> Self {
634        let mut raw = WebPConfig::default();
635        let valid = webp_config_init(&mut raw);
636        debug_assert!(valid, "the default configuration is valid");
637        Self { raw }
638    }
639
640    /// The configuration of `preset` at `quality` (C: `WebPConfigPreset`).
641    ///
642    /// # Errors
643    ///
644    /// [`EncodeError::InvalidParameter`] when `quality` is not finite or
645    /// outside 0 to 100.
646    ///
647    /// # Examples
648    ///
649    /// ```
650    /// use webp::api::encode::{Config, EncodeError, Preset};
651    ///
652    /// let config = Config::preset(Preset::Text, 90.0)?;
653    /// assert_eq!(config.as_raw().quality, 90.0);
654    /// assert_eq!(
655    ///     Config::preset(Preset::Text, 100.5),
656    ///     Err(EncodeError::InvalidParameter { name: "quality" })
657    /// );
658    /// # Ok::<(), EncodeError>(())
659    /// ```
660    pub fn preset(preset: Preset, quality: f32) -> Result<Self, EncodeError> {
661        check_quality(quality)?;
662        let mut raw = WebPConfig::default();
663        if webp_config_preset(&mut raw, preset.raw(), quality) {
664            Ok(Self { raw })
665        } else {
666            Err(EncodeError::InvalidConfiguration)
667        }
668    }
669
670    /// Switches to lossless encoding with the method and quality of `level`,
671    /// from 0 (fastest) to 9 (smallest), as `cwebp -z` does
672    /// (C: `WebPConfigLosslessPreset`).
673    ///
674    /// # Errors
675    ///
676    /// [`EncodeError::InvalidParameter`] when `level` is above 9.
677    ///
678    /// # Examples
679    ///
680    /// ```
681    /// use webp::api::encode::Config;
682    ///
683    /// let config = Config::new().lossless_level(6)?;
684    /// assert_eq!((config.as_raw().lossless, config.as_raw().method), (1, 4));
685    /// assert!(Config::new().lossless_level(10).is_err());
686    /// # Ok::<(), webp::api::encode::EncodeError>(())
687    /// ```
688    pub fn lossless_level(mut self, level: u8) -> Result<Self, EncodeError> {
689        if webp_config_lossless_preset(&mut self.raw, i32::from(level)) {
690            Ok(self)
691        } else {
692            Err(EncodeError::InvalidParameter {
693                name: "lossless_level",
694            })
695        }
696    }
697
698    /// Lossless (`true`) or lossy (`false`, the default) encoding
699    /// (C: `lossless`).
700    ///
701    /// # Examples
702    ///
703    /// ```
704    /// use webp::api::encode::Config;
705    ///
706    /// assert_eq!(Config::new().lossless(true).as_raw().lossless, 1);
707    /// ```
708    #[must_use]
709    pub fn lossless(mut self, on: bool) -> Self {
710        self.raw.lossless = i32::from(on);
711        self
712    }
713
714    /// The quality, 0 to 100 (C: `quality`). Lossy: from small and poor to
715    /// large and good. Lossless: from fast to slow and small.
716    ///
717    /// # Examples
718    ///
719    /// ```
720    /// use webp::api::encode::Config;
721    ///
722    /// assert_eq!(Config::new().quality(30.0).as_raw().quality, 30.0);
723    /// ```
724    #[must_use]
725    pub fn quality(mut self, quality: f32) -> Self {
726        self.raw.quality = quality;
727        self
728    }
729
730    /// The trade-off between speed and size, 0 (fast) to 6 (slow, smaller)
731    /// (C: `method`).
732    ///
733    /// # Examples
734    ///
735    /// ```
736    /// use webp::api::encode::Config;
737    ///
738    /// assert_eq!(Config::new().method(6).as_raw().method, 6);
739    /// ```
740    #[must_use]
741    pub fn method(mut self, method: u8) -> Self {
742        self.raw.method = i32::from(method);
743        self
744    }
745
746    /// A hint about the content for the lossless encoder (C: `image_hint`).
747    ///
748    /// # Examples
749    ///
750    /// ```
751    /// use webp::api::encode::{Config, ImageHint};
752    ///
753    /// assert_eq!(Config::new().image_hint(ImageHint::Photo).as_raw().image_hint.0, 2);
754    /// ```
755    #[must_use]
756    pub fn image_hint(mut self, hint: ImageHint) -> Self {
757        self.raw.image_hint = hint.raw();
758        self
759    }
760
761    /// A target size in bytes for a lossy encoding, 0 for none
762    /// (C: `target_size`). The C field is an `int`, so the value saturates at
763    /// `i32::MAX`, which no picture within the dimension limit reaches.
764    ///
765    /// # Examples
766    ///
767    /// ```
768    /// use webp::api::encode::Config;
769    ///
770    /// let config = Config::new().target_size(20_000);
771    /// assert_eq!(config.as_raw().target_size, 20_000);
772    /// assert_eq!(Config::new().target_size(u32::MAX).as_raw().target_size, i32::MAX);
773    /// ```
774    #[must_use]
775    pub fn target_size(mut self, bytes: u32) -> Self {
776        self.raw.target_size = i32::try_from(bytes).unwrap_or(i32::MAX);
777        self
778    }
779
780    /// A target PSNR in dB for a lossy encoding, 0 for none (C: `target_PSNR`);
781    /// it takes precedence over [`Config::target_size`].
782    ///
783    /// # Examples
784    ///
785    /// ```
786    /// use webp::api::encode::Config;
787    ///
788    /// assert_eq!(Config::new().target_psnr(42.0).as_raw().target_psnr, 42.0);
789    /// ```
790    #[must_use]
791    pub fn target_psnr(mut self, db: f32) -> Self {
792        self.raw.target_psnr = db;
793        self
794    }
795
796    /// Lossless compression of the alpha plane in a lossy encoding (`true`,
797    /// the default) or no compression (C: `alpha_compression`).
798    ///
799    /// # Examples
800    ///
801    /// ```
802    /// use webp::api::encode::Config;
803    ///
804    /// assert_eq!(Config::new().alpha_compression(false).as_raw().alpha_compression, 0);
805    /// ```
806    #[must_use]
807    pub fn alpha_compression(mut self, on: bool) -> Self {
808        self.raw.alpha_compression = i32::from(on);
809        self
810    }
811
812    /// The predictive filter of the alpha plane (C: `alpha_filtering`).
813    ///
814    /// # Examples
815    ///
816    /// ```
817    /// use webp::api::encode::{AlphaFilter, Config};
818    ///
819    /// assert_eq!(Config::new().alpha_filter(AlphaFilter::None).as_raw().alpha_filtering, 0);
820    /// ```
821    #[must_use]
822    pub fn alpha_filter(mut self, filter: AlphaFilter) -> Self {
823        self.raw.alpha_filtering = filter.raw();
824        self
825    }
826
827    /// The quality of the alpha plane, 0 (smallest) to 100 (lossless, the
828    /// default) (C: `alpha_quality`).
829    ///
830    /// # Examples
831    ///
832    /// ```
833    /// use webp::api::encode::Config;
834    ///
835    /// assert_eq!(Config::new().alpha_quality(50).as_raw().alpha_quality, 50);
836    /// ```
837    #[must_use]
838    pub fn alpha_quality(mut self, quality: u8) -> Self {
839        self.raw.alpha_quality = i32::from(quality);
840        self
841    }
842
843    /// Keeps the samples under fully transparent areas (C: `exact`); see the
844    /// module documentation for what the encoder writes otherwise.
845    ///
846    /// # Examples
847    ///
848    /// ```
849    /// use webp::api::encode::Config;
850    ///
851    /// assert_eq!(Config::new().exact(true).as_raw().exact, 1);
852    /// ```
853    #[must_use]
854    pub fn exact(mut self, on: bool) -> Self {
855        self.raw.exact = i32::from(on);
856        self
857    }
858
859    /// Near-lossless preprocessing of a lossless encoding, 0 (most loss) to 100
860    /// (off, the default) (C: `near_lossless`).
861    ///
862    /// # Examples
863    ///
864    /// ```
865    /// use webp::api::encode::Config;
866    ///
867    /// assert_eq!(Config::new().lossless(true).near_lossless(60).as_raw().near_lossless, 60);
868    /// ```
869    #[must_use]
870    pub fn near_lossless(mut self, level: u8) -> Self {
871        self.raw.near_lossless = i32::from(level);
872        self
873    }
874
875    /// The sharp (iterative, slower) RGB-to-YUV conversion of a lossy encoding
876    /// of ARGB samples (C: `use_sharp_yuv`).
877    ///
878    /// # Examples
879    ///
880    /// ```
881    /// use webp::api::encode::Config;
882    ///
883    /// assert_eq!(Config::new().sharp_yuv(true).as_raw().use_sharp_yuv, 1);
884    /// ```
885    #[must_use]
886    pub fn sharp_yuv(mut self, on: bool) -> Self {
887        self.raw.use_sharp_yuv = i32::from(on);
888        self
889    }
890
891    /// Lets the encoder use one more thread inside the call (C:
892    /// `thread_level`). The output depends on this setting, not on the
893    /// machine; the writer and the progress hook stay on the calling thread.
894    ///
895    /// # Examples
896    ///
897    /// ```
898    /// use webp::api::encode::Config;
899    ///
900    /// assert_eq!(Config::new().multithreaded(true).as_raw().thread_level, 1);
901    /// ```
902    #[must_use]
903    pub fn multithreaded(mut self, on: bool) -> Self {
904        self.raw.thread_level = i32::from(on);
905        self
906    }
907
908    /// Checks the configuration as every encoding does before it starts:
909    /// first the API's own rules (`quality` finite and in 0 to 100,
910    /// `target_psnr` finite, which C does not check), then libwebp's
911    /// validation (C: `WebPValidateConfig`).
912    ///
913    /// # Errors
914    ///
915    /// [`EncodeError::InvalidParameter`] for the API's rules,
916    /// [`EncodeError::InvalidConfiguration`] for libwebp's.
917    ///
918    /// # Examples
919    ///
920    /// ```
921    /// use webp::api::encode::{Config, EncodeError};
922    ///
923    /// assert_eq!(Config::new().validate(), Ok(()));
924    /// assert_eq!(Config::new().method(7).validate(), Err(EncodeError::InvalidConfiguration));
925    /// ```
926    pub fn validate(&self) -> Result<(), EncodeError> {
927        check_quality(self.raw.quality)?;
928        if !self.raw.target_psnr.is_finite() {
929            return Err(EncodeError::InvalidParameter {
930                name: "target_psnr",
931            });
932        }
933        if webp_validate_config(&self.raw) {
934            Ok(())
935        } else {
936            Err(EncodeError::InvalidConfiguration)
937        }
938    }
939
940    /// The configuration of the translation.
941    ///
942    /// # Examples
943    ///
944    /// ```
945    /// use webp::api::encode::Config;
946    ///
947    /// assert_eq!(Config::new().as_raw().segments, 4);
948    /// ```
949    #[must_use]
950    pub const fn as_raw(&self) -> &WebPConfig {
951        &self.raw
952    }
953
954    /// The configuration of the translation, mutably, for the fields without a
955    /// setter; [`Config::validate`] checks what is written.
956    ///
957    /// # Examples
958    ///
959    /// ```
960    /// use webp::api::encode::Config;
961    ///
962    /// let mut config = Config::new();
963    /// config.raw_mut().segments = 1;
964    /// config.raw_mut().pass = 6;
965    /// config.validate()?;
966    /// # Ok::<(), webp::api::encode::EncodeError>(())
967    /// ```
968    pub const fn raw_mut(&mut self) -> &mut WebPConfig {
969        &mut self.raw
970    }
971}
972
973//------------------------------------------------------------------------------
974// Input validation
975
976/// Checks a width and height against 1 to `WEBP_MAX_DIMENSION`.
977fn check_dimensions(width: u32, height: u32) -> Result<(i32, i32), EncodeError> {
978    let limit = WEBP_MAX_DIMENSION.unsigned_abs();
979    if width == 0 || height == 0 || width > limit || height > limit {
980        return Err(EncodeError::InvalidDimensions { width, height });
981    }
982    let invalid = EncodeError::InvalidDimensions { width, height };
983    Ok((
984        i32::try_from(width).map_err(|_| invalid)?,
985        i32::try_from(height).map_err(|_| invalid)?,
986    ))
987}
988
989/// Checks the stride and length of a plane of `rows` rows of `columns`
990/// elements, and returns the stride as C's `int`.
991fn check_plane(
992    plane: Plane,
993    len: usize,
994    columns: usize,
995    rows: usize,
996    stride: usize,
997) -> Result<i32, EncodeError> {
998    let invalid = EncodeError::InvalidStride { plane, stride };
999    if stride < columns {
1000        return Err(invalid);
1001    }
1002    let c_stride = i32::try_from(stride).map_err(|_| invalid)?;
1003    let needed = rows
1004        .checked_sub(1)
1005        .and_then(|rows| rows.checked_mul(stride))
1006        .and_then(|start| start.checked_add(columns))
1007        .ok_or(invalid)?;
1008    if len < needed {
1009        return Err(EncodeError::BufferTooShort { plane, len, needed });
1010    }
1011    Ok(c_stride)
1012}
1013
1014/// A dimension that `check_dimensions` accepted, as `usize`.
1015fn count(value: i32) -> usize {
1016    usize::try_from(value).unwrap_or(0)
1017}
1018
1019//------------------------------------------------------------------------------
1020// Pictures
1021
1022/// Strided rows of packed pixels, the input of [`Picture::import`] and of the
1023/// simple functions.
1024///
1025/// `stride` counts elements of the slice's type, which for `data: &[u8]` are
1026/// bytes: at least `width * layout.bytes_per_pixel()`, at most `i32::MAX`.
1027/// `data` holds at least `(height - 1) * stride + width * bytes_per_pixel`
1028/// bytes; the bytes between rows are not read.
1029///
1030/// # Examples
1031///
1032/// ```
1033/// use webp::api::encode::{PixelLayout, PixelRows};
1034///
1035/// // 3 by 2 BGR pixels with rows padded to 12 bytes.
1036/// let data = [0_u8; 12 + 9];
1037/// let rows = PixelRows { layout: PixelLayout::Bgr, data: &data, width: 3, height: 2, stride: 12 };
1038/// assert_eq!(rows.stride, 12);
1039/// ```
1040#[derive(Clone, Copy)]
1041pub struct PixelRows<'p> {
1042    /// The order of the channels.
1043    pub layout: PixelLayout,
1044    /// The rows, top to bottom.
1045    pub data: &'p [u8],
1046    /// The pixels of a row, 1 to 16383.
1047    pub width: u32,
1048    /// The rows, 1 to 16383.
1049    pub height: u32,
1050    /// The distance from the start of a row to the next, in bytes.
1051    pub stride: usize,
1052}
1053
1054impl fmt::Debug for PixelRows<'_> {
1055    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1056        f.debug_struct("PixelRows")
1057            .field("layout", &self.layout)
1058            .field("data_len", &self.data.len())
1059            .field("width", &self.width)
1060            .field("height", &self.height)
1061            .field("stride", &self.stride)
1062            .finish()
1063    }
1064}
1065
1066/// The caller's Y, U, V and optional A planes, the input of
1067/// [`Picture::from_yuva`].
1068///
1069/// Strides count elements of the slices' type, which are bytes. The Y and A
1070/// planes have `height` rows of `width` samples, the U and V planes
1071/// `(height + 1) / 2` rows of `(width + 1) / 2` samples; each stride is at
1072/// least its row length and at most `i32::MAX`, and each plane holds at least
1073/// `(rows - 1) * stride + row length` samples. `a_stride` is ignored when `a`
1074/// is `None`.
1075///
1076/// # Examples
1077///
1078/// ```
1079/// use webp::api::encode::{Picture, YuvaPlanes};
1080///
1081/// // 3 by 3: chroma planes of 2 by 2, alpha omitted.
1082/// let (mut y, mut u, mut v) = (vec![128_u8; 9], vec![128_u8; 4], vec![128_u8; 4]);
1083/// let planes = YuvaPlanes {
1084///     y: &mut y, y_stride: 3,
1085///     u: &mut u, v: &mut v, uv_stride: 2,
1086///     a: None, a_stride: 0,
1087/// };
1088/// let picture = Picture::from_yuva(3, 3, planes)?;
1089/// assert_eq!(picture.owned_sample_bytes(), 0);
1090/// # Ok::<(), webp::api::encode::EncodeError>(())
1091/// ```
1092pub struct YuvaPlanes<'a> {
1093    /// The luma plane.
1094    pub y: &'a mut [u8],
1095    /// The distance between luma rows, in bytes.
1096    pub y_stride: usize,
1097    /// The U (Cb) chroma plane.
1098    pub u: &'a mut [u8],
1099    /// The V (Cr) chroma plane.
1100    pub v: &'a mut [u8],
1101    /// The distance between rows of both chroma planes, in bytes.
1102    pub uv_stride: usize,
1103    /// The alpha plane, straight alpha, or `None` for an opaque picture.
1104    pub a: Option<&'a mut [u8]>,
1105    /// The distance between alpha rows, in bytes.
1106    pub a_stride: usize,
1107}
1108
1109impl fmt::Debug for YuvaPlanes<'_> {
1110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1111        f.debug_struct("YuvaPlanes")
1112            .field("y_len", &self.y.len())
1113            .field("y_stride", &self.y_stride)
1114            .field("u_len", &self.u.len())
1115            .field("v_len", &self.v.len())
1116            .field("uv_stride", &self.uv_stride)
1117            .field("a_len", &self.a.as_ref().map(|a| a.len()))
1118            .field("a_stride", &self.a_stride)
1119            .finish()
1120    }
1121}
1122
1123/// The fields of a `WebPPicture` that describe its samples, without the
1124/// storages and the per-call callbacks.
1125#[derive(Clone, Copy, Default)]
1126struct Specs {
1127    use_argb: i32,
1128    colorspace: WebPEncCSP,
1129    width: i32,
1130    height: i32,
1131    y: Option<PlaneOffset>,
1132    u: Option<PlaneOffset>,
1133    v: Option<PlaneOffset>,
1134    a: Option<PlaneOffset>,
1135    y_stride: i32,
1136    uv_stride: i32,
1137    a_stride: i32,
1138    argb: Option<PlaneOffset>,
1139    argb_stride: i32,
1140}
1141
1142impl Specs {
1143    fn of(pic: &WebPPicture<'_>) -> Self {
1144        Self {
1145            use_argb: pic.use_argb,
1146            colorspace: pic.colorspace,
1147            width: pic.width,
1148            height: pic.height,
1149            y: pic.y,
1150            u: pic.u,
1151            v: pic.v,
1152            a: pic.a,
1153            y_stride: pic.y_stride,
1154            uv_stride: pic.uv_stride,
1155            a_stride: pic.a_stride,
1156            argb: pic.argb,
1157            argb_stride: pic.argb_stride,
1158        }
1159    }
1160
1161    fn apply(self, pic: &mut WebPPicture<'_>) {
1162        pic.use_argb = self.use_argb;
1163        pic.colorspace = self.colorspace;
1164        pic.width = self.width;
1165        pic.height = self.height;
1166        pic.y = self.y;
1167        pic.u = self.u;
1168        pic.v = self.v;
1169        pic.a = self.a;
1170        pic.y_stride = self.y_stride;
1171        pic.uv_stride = self.uv_stride;
1172        pic.a_stride = self.a_stride;
1173        pic.argb = self.argb;
1174        pic.argb_stride = self.argb_stride;
1175    }
1176}
1177
1178/// The plane at the start of storage region `region`.
1179const fn region_start(region: usize) -> PlaneOffset {
1180    PlaneOffset { region, offset: 0 }
1181}
1182
1183/// A storage for one call: owned samples move out (and come back through
1184/// [`Returned`]), the caller's slices are reborrowed.
1185fn lend<'s, T>(storage: &'s mut PlaneStorage<'_, T>) -> PlaneStorage<'s, T> {
1186    match storage {
1187        PlaneStorage::Internal(samples) => PlaneStorage::Internal(std::mem::take(samples)),
1188        PlaneStorage::External(slices) => {
1189            PlaneStorage::External(slices.iter_mut().map(|slice| &mut **slice).collect())
1190        }
1191        // Not produced by this API; a view's regions are shared references.
1192        PlaneStorage::Shared(slices) => PlaneStorage::Shared(slices.clone()),
1193    }
1194}
1195
1196/// The owned samples of a storage after a call; the caller's slices of an
1197/// `External` storage are still held by the picture.
1198fn owned<T>(storage: PlaneStorage<'_, T>) -> Option<Vec<T>> {
1199    match storage {
1200        PlaneStorage::Internal(samples) => Some(samples),
1201        PlaneStorage::External(_) | PlaneStorage::Shared(_) => None,
1202    }
1203}
1204
1205/// What a call leaves in its `WebPPicture`, without the call's lifetime.
1206struct Returned {
1207    specs: Specs,
1208    yuva: Option<Vec<u8>>,
1209    argb: Option<Vec<u32>>,
1210    error: WebPEncodingError,
1211}
1212
1213impl Returned {
1214    fn take(pic: WebPPicture<'_>) -> Self {
1215        Self {
1216            specs: Specs::of(&pic),
1217            error: pic.error_code,
1218            yuva: owned(pic.yuva),
1219            argb: owned(pic.argb_storage),
1220        }
1221    }
1222}
1223
1224/// A picture to encode: its dimensions and its samples, either planes it
1225/// allocated ([`Picture::import`]) or the caller's planes, borrowed
1226/// exclusively for `'a` ([`Picture::from_argb`], [`Picture::from_yuva`]).
1227///
1228/// A picture holds no callbacks, so it is `Send` and `Sync`; the writer, the
1229/// progress hook and the statistics belong to one [`Encoder`] call.
1230///
1231/// # Examples
1232///
1233/// ```
1234/// use webp::api::encode::{Config, Encoder, Picture};
1235///
1236/// // Caller-owned ARGB pixels (0xAARRGGBB), 2 by 2 with one pixel of padding.
1237/// let mut argb = vec![0xff20_4060_u32; 2 * 3];
1238/// let mut picture = Picture::from_argb(&mut argb, 2, 2, 3)?;
1239/// assert_eq!((picture.width(), picture.height()), (2, 2));
1240/// let config = Config::new().lossless(true);
1241/// let webp = Encoder::new(&config).encode(&mut picture)?;
1242/// assert_eq!(&webp[12..16], b"VP8L");
1243/// # Ok::<(), webp::api::encode::EncodeError>(())
1244/// ```
1245pub struct Picture<'a> {
1246    specs: Specs,
1247    yuva: PlaneStorage<'a, u8>,
1248    argb_storage: PlaneStorage<'a, u32>,
1249}
1250
1251impl fmt::Debug for Picture<'_> {
1252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1253        f.debug_struct("Picture")
1254            .field("width", &self.width())
1255            .field("height", &self.height())
1256            .field("use_argb", &self.specs.use_argb)
1257            .field("owned_sample_bytes", &self.owned_sample_bytes())
1258            .finish_non_exhaustive()
1259    }
1260}
1261
1262impl Picture<'static> {
1263    /// Copies `rows` into planes that the picture allocates, in the form that
1264    /// `form` selects (C: `WebPPictureImportRGB` and its siblings, with
1265    /// `use_argb`). [`SampleForm::Yuva`] converts to YUV at once, and adds an
1266    /// alpha plane only when some pixel is not opaque.
1267    ///
1268    /// # Errors
1269    ///
1270    /// [`EncodeError::InvalidDimensions`], [`EncodeError::InvalidStride`] or
1271    /// [`EncodeError::BufferTooShort`] for rows outside the rules of
1272    /// [`PixelRows`]; [`EncodeError::OutOfMemory`] when the planes cannot be
1273    /// allocated.
1274    ///
1275    /// # Examples
1276    ///
1277    /// ```
1278    /// use webp::api::encode::{Picture, PixelLayout, PixelRows, SampleForm};
1279    ///
1280    /// let rgba = [1_u8, 2, 3, 128].repeat(6);
1281    /// let rows = PixelRows { layout: PixelLayout::Rgba, data: &rgba, width: 3, height: 2, stride: 12 };
1282    /// let picture = Picture::import(rows, SampleForm::Yuva)?;
1283    /// // Y 3 by 2, U and V 2 by 1, and alpha, since the pixels are translucent.
1284    /// assert_eq!(picture.owned_sample_bytes(), 6 + 2 + 2 + 6);
1285    /// # Ok::<(), webp::api::encode::EncodeError>(())
1286    /// ```
1287    pub fn import(rows: PixelRows<'_>, form: SampleForm) -> Result<Self, EncodeError> {
1288        let (width, height) = check_dimensions(rows.width, rows.height)?;
1289        let columns = count(width)
1290            .checked_mul(rows.layout.bytes_per_pixel())
1291            .ok_or(EncodeError::InvalidDimensions {
1292                width: rows.width,
1293                height: rows.height,
1294            })?;
1295        let stride = check_plane(
1296            Plane::Pixels,
1297            rows.data.len(),
1298            columns,
1299            count(height),
1300            rows.stride,
1301        )?;
1302        let mut pic = WebPPicture::default();
1303        let initialized = webp_picture_init(&mut pic);
1304        debug_assert!(initialized, "the picture's version is the crate's");
1305        pic.width = width;
1306        pic.height = height;
1307        pic.use_argb = i32::from(form == SampleForm::Argb);
1308        if !(rows.layout.importer())(&mut pic, rows.data, stride) {
1309            // A refusal without a code is the stride test, which the checks
1310            // above already passed.
1311            return Err(if pic.error_code == WebPEncodingError::VP8_ENC_OK {
1312                EncodeError::InvalidStride {
1313                    plane: Plane::Pixels,
1314                    stride: rows.stride,
1315                }
1316            } else {
1317                EncodeError::from_code(pic.error_code)
1318            });
1319        }
1320        Ok(Self {
1321            specs: Specs::of(&pic),
1322            yuva: pic.yuva,
1323            argb_storage: pic.argb_storage,
1324        })
1325    }
1326}
1327
1328impl<'a> Picture<'a> {
1329    /// Borrows the caller's ARGB pixels, `0xAARRGGBB` in each `u32` with
1330    /// straight alpha, as the picture's samples (C: `use_argb` with the
1331    /// caller's `argb` plane).
1332    ///
1333    /// `stride` counts elements of the slice's type, which for `&mut [u32]`
1334    /// are pixels, not bytes: at least `width`, at most `i32::MAX`. `argb`
1335    /// holds at least `(height - 1) * stride + width` pixels.
1336    ///
1337    /// # Errors
1338    ///
1339    /// [`EncodeError::InvalidDimensions`], [`EncodeError::InvalidStride`] or
1340    /// [`EncodeError::BufferTooShort`] (with [`Plane::Argb`]).
1341    ///
1342    /// # Examples
1343    ///
1344    /// ```
1345    /// use webp::api::encode::Picture;
1346    ///
1347    /// let mut argb = vec![0x80ff_0000_u32; 4 * 4];
1348    /// let picture = Picture::from_argb(&mut argb, 4, 4, 4)?;
1349    /// assert_eq!(picture.owned_sample_bytes(), 0);
1350    /// # Ok::<(), webp::api::encode::EncodeError>(())
1351    /// ```
1352    pub fn from_argb(
1353        argb: &'a mut [u32],
1354        width: u32,
1355        height: u32,
1356        stride: usize,
1357    ) -> Result<Self, EncodeError> {
1358        let (c_width, c_height) = check_dimensions(width, height)?;
1359        let argb_stride = check_plane(
1360            Plane::Argb,
1361            argb.len(),
1362            count(c_width),
1363            count(c_height),
1364            stride,
1365        )?;
1366        Ok(Self {
1367            specs: Specs {
1368                use_argb: 1,
1369                width: c_width,
1370                height: c_height,
1371                argb: Some(region_start(0)),
1372                argb_stride,
1373                ..Specs::default()
1374            },
1375            yuva: PlaneStorage::default(),
1376            argb_storage: PlaneStorage::External(vec![argb]),
1377        })
1378    }
1379
1380    /// Borrows the caller's Y, U, V and optional alpha planes as the picture's
1381    /// samples, taken as they are (C: `use_argb` 0 with the caller's planes,
1382    /// colorspace `WEBP_YUV420` or, with alpha, `WEBP_YUV420A`). See
1383    /// [`YuvaPlanes`] for the stride and length rules.
1384    ///
1385    /// # Errors
1386    ///
1387    /// [`EncodeError::InvalidDimensions`], [`EncodeError::InvalidStride`] or
1388    /// [`EncodeError::BufferTooShort`], naming the plane.
1389    ///
1390    /// # Examples
1391    ///
1392    /// ```
1393    /// use webp::api::encode::{Config, Encoder, Picture, YuvaPlanes};
1394    ///
1395    /// let (mut y, mut u, mut v, mut a) = (vec![100_u8; 16], vec![90_u8; 4], vec![160_u8; 4], vec![255_u8; 16]);
1396    /// let planes = YuvaPlanes {
1397    ///     y: &mut y, y_stride: 4,
1398    ///     u: &mut u, v: &mut v, uv_stride: 2,
1399    ///     a: Some(&mut a), a_stride: 4,
1400    /// };
1401    /// let mut picture = Picture::from_yuva(4, 4, planes)?;
1402    /// let webp = Encoder::new(&Config::new()).encode(&mut picture)?;
1403    /// assert_eq!(&webp[12..16], b"VP8 ");
1404    /// # Ok::<(), webp::api::encode::EncodeError>(())
1405    /// ```
1406    pub fn from_yuva(width: u32, height: u32, planes: YuvaPlanes<'a>) -> Result<Self, EncodeError> {
1407        let (c_width, c_height) = check_dimensions(width, height)?;
1408        let (columns, rows) = (count(c_width), count(c_height));
1409        let (uv_columns, uv_rows) = (count((c_width + 1) >> 1), count((c_height + 1) >> 1));
1410        let y_stride = check_plane(Plane::Y, planes.y.len(), columns, rows, planes.y_stride)?;
1411        let uv_stride = check_plane(
1412            Plane::U,
1413            planes.u.len(),
1414            uv_columns,
1415            uv_rows,
1416            planes.uv_stride,
1417        )?;
1418        check_plane(
1419            Plane::V,
1420            planes.v.len(),
1421            uv_columns,
1422            uv_rows,
1423            planes.uv_stride,
1424        )?;
1425        let a_stride = match &planes.a {
1426            Some(a) => check_plane(Plane::A, a.len(), columns, rows, planes.a_stride)?,
1427            None => 0,
1428        };
1429        let has_alpha = planes.a.is_some();
1430        let mut regions = vec![planes.y, planes.u, planes.v];
1431        regions.extend(planes.a);
1432        Ok(Self {
1433            specs: Specs {
1434                use_argb: 0,
1435                colorspace: if has_alpha {
1436                    WebPEncCSP::WEBP_YUV420A
1437                } else {
1438                    WebPEncCSP::WEBP_YUV420
1439                },
1440                width: c_width,
1441                height: c_height,
1442                y: Some(region_start(0)),
1443                u: Some(region_start(1)),
1444                v: Some(region_start(2)),
1445                a: has_alpha.then_some(region_start(3)),
1446                y_stride,
1447                uv_stride,
1448                a_stride,
1449                ..Specs::default()
1450            },
1451            yuva: PlaneStorage::External(regions),
1452            argb_storage: PlaneStorage::default(),
1453        })
1454    }
1455
1456    /// The width in pixels.
1457    ///
1458    /// # Examples
1459    ///
1460    /// ```
1461    /// use webp::api::encode::Picture;
1462    ///
1463    /// let mut argb = vec![0_u32; 6];
1464    /// assert_eq!(Picture::from_argb(&mut argb, 3, 2, 3)?.width(), 3);
1465    /// # Ok::<(), webp::api::encode::EncodeError>(())
1466    /// ```
1467    #[must_use]
1468    pub const fn width(&self) -> u32 {
1469        self.specs.width.unsigned_abs()
1470    }
1471
1472    /// The height in pixels.
1473    ///
1474    /// # Examples
1475    ///
1476    /// ```
1477    /// use webp::api::encode::Picture;
1478    ///
1479    /// let mut argb = vec![0_u32; 6];
1480    /// assert_eq!(Picture::from_argb(&mut argb, 3, 2, 3)?.height(), 2);
1481    /// # Ok::<(), webp::api::encode::EncodeError>(())
1482    /// ```
1483    #[must_use]
1484    pub const fn height(&self) -> u32 {
1485        self.specs.height.unsigned_abs()
1486    }
1487
1488    /// The bytes of the samples that the picture allocated itself: the
1489    /// imported planes, and the planes that an encoding's conversion added.
1490    /// The caller's planes are not counted, nor is the encoder's internal
1491    /// state.
1492    ///
1493    /// # Examples
1494    ///
1495    /// ```
1496    /// use webp::api::encode::{Config, Encoder, Picture};
1497    ///
1498    /// let mut argb = vec![0xff00_ff00_u32; 4 * 4];
1499    /// let mut picture = Picture::from_argb(&mut argb, 4, 4, 4)?;
1500    /// assert_eq!(picture.owned_sample_bytes(), 0);
1501    /// // A lossy encoding converts the ARGB pixels into YUV planes it keeps.
1502    /// Encoder::new(&Config::new()).encode(&mut picture)?;
1503    /// assert_eq!(picture.owned_sample_bytes(), 16 + 4 + 4);
1504    /// # Ok::<(), webp::api::encode::EncodeError>(())
1505    /// ```
1506    #[must_use]
1507    pub fn owned_sample_bytes(&self) -> usize {
1508        let yuva = match &self.yuva {
1509            PlaneStorage::Internal(samples) => samples.len(),
1510            PlaneStorage::External(_) | PlaneStorage::Shared(_) => 0,
1511        };
1512        let argb = match &self.argb_storage {
1513            PlaneStorage::Internal(samples) => samples.len() * std::mem::size_of::<u32>(),
1514            PlaneStorage::External(_) | PlaneStorage::Shared(_) => 0,
1515        };
1516        yuva + argb
1517    }
1518
1519    /// Encodes the picture with the translated `WebPEncode` in a `WebPPicture`
1520    /// that lives for this call. The planes leave the picture for the call and
1521    /// come back afterwards, so a panicking callback leaves it without planes.
1522    fn encode_with<'c>(
1523        &'c mut self,
1524        config: &WebPConfig,
1525        writer: &'c mut dyn FnMut(&[u8]) -> bool,
1526        progress: Option<Box<dyn FnMut(i32) -> bool + 'c>>,
1527        stats: Option<&'c mut WebPAuxStats>,
1528    ) -> Result<(), EncodeError> {
1529        let specs = self.specs;
1530        self.specs = Specs {
1531            y: None,
1532            u: None,
1533            v: None,
1534            a: None,
1535            argb: None,
1536            ..specs
1537        };
1538        let mut call = WebPPicture::default();
1539        let initialized = webp_picture_init(&mut call);
1540        debug_assert!(initialized, "the picture's version is the crate's");
1541        specs.apply(&mut call);
1542        call.yuva = lend(&mut self.yuva);
1543        call.argb_storage = lend(&mut self.argb_storage);
1544        call.writer = Some(Box::new(move |data: &[u8]| writer(data)));
1545        call.progress_hook = progress;
1546        call.stats = stats;
1547
1548        let ok = webp_encode(config, &mut call);
1549
1550        let returned = Returned::take(call);
1551        self.specs = returned.specs;
1552        if let Some(samples) = returned.yuva {
1553            self.yuva = PlaneStorage::Internal(samples);
1554        }
1555        if let Some(samples) = returned.argb {
1556            self.argb_storage = PlaneStorage::Internal(samples);
1557        }
1558        if ok {
1559            Ok(())
1560        } else {
1561            Err(EncodeError::from_code(returned.error))
1562        }
1563    }
1564}
1565
1566//------------------------------------------------------------------------------
1567// Encoding
1568
1569/// One encoding: a configuration, and optionally a progress hook and
1570/// statistics, applied to a [`Picture`] with [`Encoder::encode`] or
1571/// [`Encoder::encode_to`].
1572///
1573/// # Examples
1574///
1575/// ```
1576/// use webp::api::encode::{Config, Encoder, Picture, WebPAuxStats};
1577///
1578/// let mut argb = vec![0xff40_8020_u32; 32 * 32];
1579/// let mut picture = Picture::from_argb(&mut argb, 32, 32, 32)?;
1580/// let config = Config::new().quality(60.0);
1581/// let mut stats = WebPAuxStats::default();
1582/// let mut reports = Vec::new();
1583/// let webp = Encoder::new(&config)
1584///     .progress(|percent| {
1585///         reports.push(percent);
1586///         true
1587///     })
1588///     .stats(&mut stats)
1589///     .encode(&mut picture)?;
1590/// assert_eq!(stats.coded_size as usize, webp.len());
1591/// assert!(!reports.is_empty());
1592/// # Ok::<(), webp::api::encode::EncodeError>(())
1593/// ```
1594pub struct Encoder<'e> {
1595    config: &'e Config,
1596    progress: Option<Box<dyn FnMut(i32) -> bool + 'e>>,
1597    stats: Option<&'e mut WebPAuxStats>,
1598}
1599
1600impl fmt::Debug for Encoder<'_> {
1601    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1602        f.debug_struct("Encoder")
1603            .field("config", self.config)
1604            .field("progress", &self.progress.is_some())
1605            .field("stats", &self.stats.is_some())
1606            .finish()
1607    }
1608}
1609
1610impl<'e> Encoder<'e> {
1611    /// An encoding with `config`, no progress hook and no statistics.
1612    ///
1613    /// # Examples
1614    ///
1615    /// ```
1616    /// use webp::api::encode::{Config, Encoder};
1617    ///
1618    /// let config = Config::new();
1619    /// let encoder = Encoder::new(&config);
1620    /// # let _ = encoder;
1621    /// ```
1622    #[must_use]
1623    pub const fn new(config: &'e Config) -> Self {
1624        Self {
1625            config,
1626            progress: None,
1627            stats: None,
1628        }
1629    }
1630
1631    /// Reports progress to `hook` (C: `WebPPicture::progress_hook`). It
1632    /// receives libwebp's percentages, 0 to 100, each time the value changes,
1633    /// on the calling thread. Returning `false` stops the encoding with
1634    /// [`EncodeError::UserAbort`]; the writer keeps what it received.
1635    ///
1636    /// libwebp ignores the answer at two places, the end of a lossy analysis
1637    /// without segments (C: `ResetAllMBInfo`) and the statistics pass of lossy
1638    /// methods 0 to 2 (C: `VP8EncLoop` drops the result of `StatLoop`): the
1639    /// encoding then goes on and can succeed. A hook that cancels should
1640    /// therefore keep returning `false`.
1641    ///
1642    /// # Examples
1643    ///
1644    /// ```
1645    /// use webp::api::encode::{Config, EncodeError, Encoder, Picture};
1646    ///
1647    /// let mut argb = vec![0xff00_0000_u32; 64 * 64];
1648    /// let mut picture = Picture::from_argb(&mut argb, 64, 64, 64)?;
1649    /// let config = Config::new();
1650    /// let result = Encoder::new(&config).progress(|percent| percent < 50).encode(&mut picture);
1651    /// assert_eq!(result, Err(EncodeError::UserAbort));
1652    /// # Ok::<(), EncodeError>(())
1653    /// ```
1654    #[must_use]
1655    pub fn progress(mut self, hook: impl FnMut(i32) -> bool + 'e) -> Self {
1656        self.progress = Some(Box::new(hook));
1657        self
1658    }
1659
1660    /// Fills `stats` with the encoding's statistics (C:
1661    /// `WebPPicture::stats`). They are reset once the configuration and the
1662    /// picture pass libwebp's validation and filled as libwebp fills them, on
1663    /// failure too.
1664    ///
1665    /// # Examples
1666    ///
1667    /// ```
1668    /// use webp::api::encode::{Config, Encoder, Picture, WebPAuxStats};
1669    ///
1670    /// let mut argb = vec![0xff80_8080_u32; 16 * 16];
1671    /// let mut picture = Picture::from_argb(&mut argb, 16, 16, 16)?;
1672    /// let config = Config::new().quality(90.0);
1673    /// let mut stats = WebPAuxStats::default();
1674    /// let webp = Encoder::new(&config).stats(&mut stats).encode(&mut picture)?;
1675    /// assert_eq!(stats.coded_size as usize, webp.len());
1676    /// assert!(stats.psnr[3] > 40.0); // Y, U and V together, in dB
1677    /// # Ok::<(), webp::api::encode::EncodeError>(())
1678    /// ```
1679    #[must_use]
1680    pub fn stats(mut self, stats: &'e mut WebPAuxStats) -> Self {
1681        self.stats = Some(stats);
1682        self
1683    }
1684
1685    /// Encodes `picture` into memory, through libwebp's memory writer
1686    /// (C: `WebPEncode` with `WebPMemoryWrite`), and returns the WebP file.
1687    ///
1688    /// The encoder may write into the picture's planes, as the module
1689    /// documentation describes, and leaves the planes of its conversions with
1690    /// the picture. If the progress hook panics, the panic propagates and the
1691    /// picture is left without planes: a later encoding of it returns
1692    /// [`EncodeError::NullParameter`].
1693    ///
1694    /// # Errors
1695    ///
1696    /// The errors of [`Config::validate`], and the code libwebp records:
1697    /// [`EncodeError::BadWrite`] when the output cannot grow,
1698    /// [`EncodeError::UserAbort`] from the progress hook, and the others of
1699    /// [`EncodeError`].
1700    ///
1701    /// # Examples
1702    ///
1703    /// ```
1704    /// use webp::api::encode::{Config, Encoder, Picture, PixelLayout, PixelRows, SampleForm};
1705    ///
1706    /// let rgb = [200_u8, 100, 50].repeat(16 * 16);
1707    /// let rows = PixelRows { layout: PixelLayout::Rgb, data: &rgb, width: 16, height: 16, stride: 48 };
1708    /// let mut picture = Picture::import(rows, SampleForm::Yuva)?;
1709    /// let webp = Encoder::new(&Config::new()).encode(&mut picture)?;
1710    /// assert_eq!(&webp[..4], b"RIFF");
1711    /// # Ok::<(), webp::api::encode::EncodeError>(())
1712    /// ```
1713    pub fn encode(self, picture: &mut Picture<'_>) -> Result<Vec<u8>, EncodeError> {
1714        let mut memory = WebPMemoryWriter::default();
1715        webp_memory_writer_init(&mut memory);
1716        self.encode_to(picture, |data| webp_memory_write(&mut memory, data))?;
1717        let mut bytes = memory.mem;
1718        bytes.truncate(memory.size);
1719        Ok(bytes)
1720    }
1721
1722    /// Encodes `picture` through `writer` (C: `WebPEncode` with
1723    /// `WebPPicture::writer`). The writer receives the WebP file in order, in
1724    /// chunks that may be empty, on the calling thread; returning `false`
1725    /// stops the encoding with [`EncodeError::BadWrite`], and the bytes it
1726    /// accepted stay with it.
1727    ///
1728    /// The encoder may write into the picture's planes, as the module
1729    /// documentation describes, and leaves the planes of its conversions with
1730    /// the picture. If the writer or the progress hook panics, the panic
1731    /// propagates and the picture is left without planes: a later encoding of
1732    /// it returns [`EncodeError::NullParameter`].
1733    ///
1734    /// # Errors
1735    ///
1736    /// The errors of [`Config::validate`], and the code libwebp records:
1737    /// [`EncodeError::BadWrite`] from the writer, [`EncodeError::UserAbort`]
1738    /// from the progress hook, and the others of [`EncodeError`].
1739    ///
1740    /// # Examples
1741    ///
1742    /// ```
1743    /// use webp::api::encode::{Config, EncodeError, Encoder, Picture};
1744    ///
1745    /// let mut argb = vec![0xff12_3456_u32; 10 * 10];
1746    /// let mut picture = Picture::from_argb(&mut argb, 10, 10, 10)?;
1747    /// let config = Config::new();
1748    /// let mut file = Vec::new();
1749    /// Encoder::new(&config).encode_to(&mut picture, |chunk| {
1750    ///     file.extend_from_slice(chunk);
1751    ///     true
1752    /// })?;
1753    /// assert_eq!(&file[..4], b"RIFF");
1754    ///
1755    /// let refused = Encoder::new(&config).encode_to(&mut picture, |_| false);
1756    /// assert_eq!(refused, Err(EncodeError::BadWrite));
1757    /// # Ok::<(), EncodeError>(())
1758    /// ```
1759    pub fn encode_to(
1760        self,
1761        picture: &mut Picture<'_>,
1762        mut writer: impl FnMut(&[u8]) -> bool,
1763    ) -> Result<(), EncodeError> {
1764        self.config.validate()?;
1765        picture.encode_with(&self.config.raw, &mut writer, self.progress, self.stats)
1766    }
1767}
1768
1769//------------------------------------------------------------------------------
1770// Simple functions
1771
1772/// The steps of C's `Encode` (`src/enc/picture_enc.c`): the default preset at
1773/// `quality`, `lossless`, ARGB samples for a lossless encoding, the importer,
1774/// and `WebPEncode` into the memory writer.
1775fn encode_simple(
1776    rows: PixelRows<'_>,
1777    quality: f32,
1778    lossless: bool,
1779) -> Result<Vec<u8>, EncodeError> {
1780    let config = Config::preset(Preset::Default, quality)?.lossless(lossless);
1781    let form = if lossless {
1782        SampleForm::Argb
1783    } else {
1784        SampleForm::Yuva
1785    };
1786    let mut picture = Picture::import(rows, form)?;
1787    Encoder::new(&config).encode(&mut picture)
1788}
1789
1790/// Encodes `rows` lossily at `quality` with the default preset, as libwebp's
1791/// simple API does (C: `WebPEncodeRGB`, `WebPEncodeBGR`, `WebPEncodeRGBA` and
1792/// `WebPEncodeBGRA`; the X layouts take the same steps).
1793///
1794/// # Errors
1795///
1796/// [`EncodeError::InvalidParameter`] for a quality that is not finite or not
1797/// in 0 to 100, the errors of [`Picture::import`], and the code libwebp
1798/// records.
1799///
1800/// # Examples
1801///
1802/// ```
1803/// use webp::api::encode::{PixelLayout, PixelRows, encode_lossy};
1804///
1805/// let bgra = [30_u8, 60, 90, 255].repeat(8 * 8);
1806/// let rows = PixelRows { layout: PixelLayout::Bgra, data: &bgra, width: 8, height: 8, stride: 32 };
1807/// let webp = encode_lossy(rows, 75.0)?;
1808/// assert_eq!(&webp[12..16], b"VP8 ");
1809/// # Ok::<(), webp::api::encode::EncodeError>(())
1810/// ```
1811pub fn encode_lossy(rows: PixelRows<'_>, quality: f32) -> Result<Vec<u8>, EncodeError> {
1812    encode_simple(rows, quality, false)
1813}
1814
1815/// Encodes `rows` losslessly with the default preset at quality 70, as
1816/// libwebp's simple API does (C: `WebPEncodeLosslessRGB`,
1817/// `WebPEncodeLosslessBGR`, `WebPEncodeLosslessRGBA` and
1818/// `WebPEncodeLosslessBGRA`; the X layouts take the same steps).
1819///
1820/// # Errors
1821///
1822/// The errors of [`Picture::import`], and the code libwebp records.
1823///
1824/// # Examples
1825///
1826/// ```
1827/// use webp::api::encode::{PixelLayout, PixelRows, encode_lossless};
1828///
1829/// let rgbx = [1_u8, 2, 3, 0].repeat(5 * 4);
1830/// let rows = PixelRows { layout: PixelLayout::Rgbx, data: &rgbx, width: 5, height: 4, stride: 20 };
1831/// let webp = encode_lossless(rows)?;
1832/// assert_eq!(&webp[12..16], b"VP8L");
1833/// # Ok::<(), webp::api::encode::EncodeError>(())
1834/// ```
1835pub fn encode_lossless(rows: PixelRows<'_>) -> Result<Vec<u8>, EncodeError> {
1836    encode_simple(rows, LOSSLESS_DEFAULT_QUALITY, true)
1837}