webpx 0.3.4

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

//! Compatibility shim for the `webp-animation` crate (0.9.x).
//!
//! This module provides an API-compatible interface to ease migration
//! from the `webp-animation` crate to `webpx`.
//!
//! # Deprecated as of 0.2.1
//!
//! The shim does not expose [`crate::Limits`] for untrusted-input
//! decoding, so callers can't apply `max_total_pixels` /
//! `max_frame_count` / `max_input_bytes` policies through this API.
//! [`Decoder::into_iter`] also silently produces an empty iterator on
//! construction failure instead of returning the error.
//!
//! New code should:
//!
//! - **Migrate to [`zenwebp`](https://github.com/imazen/zenwebp)** — a
//!   pure-Rust WebP codec built with `#![forbid(unsafe_code)]`. Equally
//!   or more capable than `webpx` (full feature parity with libwebp,
//!   native `wasm32-unknown-unknown` support, performance and
//!   compression within noise of libwebp on average), and with no
//!   exposure to libwebp's CVE pipeline (most recently CVE-2023-4863,
//!   the actively-exploited 0-click heap overflow) or the FFI
//!   soundness bugs every libwebp wrapper — including this one — has
//!   shipped. Recommended.
//! - Or use [`crate::AnimationDecoder::with_options_limits`] /
//!   [`crate::AnimationEncoder`] directly if you specifically need
//!   libwebp (existing link in your stack, MIPS DSP code paths, or
//!   benchmark-confirmed wins on your content).
//!
//! This module will be retained for at least one minor release; all
//! public items carry `#[deprecated]` attributes that surface as
//! compiler warnings on use.
//!
//! # Migration
//!
//! Replace your imports:
//! ```rust,ignore
//! // Before
//! use webp_animation::{Encoder, Decoder, ColorMode};
//!
//! // After
//! use webpx::compat::webp_animation::{Encoder, Decoder, ColorMode};
//! ```
//!
//! # Key Differences
//!
//! - Uses `finalize()` to match webp-animation API (webpx uses `finish()`)
//! - Uses tuple dimensions `(width, height)` like webp-animation
//! - Decoder implements `IntoIterator` for frame iteration

use alloc::vec::Vec;
use core::ops::Deref;

/// Color mode for decoded frames.
#[deprecated(
    since = "0.2.1",
    note = "use the main webpx animation API; see module docs"
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ColorMode {
    /// RGB (3 bytes per pixel).
    Rgb,
    /// RGBA (4 bytes per pixel).
    #[default]
    Rgba,
    /// BGRA (4 bytes per pixel).
    Bgra,
    /// BGR (3 bytes per pixel).
    Bgr,
}

impl ColorMode {
    /// Bytes per pixel for this color mode.
    pub fn size(&self) -> usize {
        match self {
            ColorMode::Rgb | ColorMode::Bgr => 3,
            ColorMode::Rgba | ColorMode::Bgra => 4,
        }
    }
}

impl From<ColorMode> for crate::ColorMode {
    fn from(mode: ColorMode) -> Self {
        match mode {
            ColorMode::Rgb => crate::ColorMode::Rgb,
            ColorMode::Rgba => crate::ColorMode::Rgba,
            ColorMode::Bgra => crate::ColorMode::Bgra,
            ColorMode::Bgr => crate::ColorMode::Bgr,
        }
    }
}

/// Owned WebP data buffer.
#[deprecated(
    since = "0.2.1",
    note = "use the main webpx animation API; see module docs"
)]
#[derive(Debug)]
pub struct WebPData(Vec<u8>);

impl WebPData {
    /// Check if the buffer is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Get the length of the buffer.
    pub fn len(&self) -> usize {
        self.0.len()
    }
}

impl Deref for WebPData {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl AsRef<[u8]> for WebPData {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

/// Error type compatible with webp-animation.
#[deprecated(
    since = "0.2.1",
    note = "use the main webpx animation API; see module docs"
)]
#[derive(Debug, PartialEq)]
pub enum Error {
    /// Encoder creation failed.
    EncoderCreateFailed,
    /// Frame add failed.
    EncoderAddFailed,
    /// Encoder assembly failed.
    EncoderAssmebleFailed,
    /// Decode failed.
    DecodeFailed,
    /// Buffer size mismatch.
    BufferSizeFailed(usize, usize),
    /// Timestamp ordering error.
    TimestampMustBeHigherThanPrevious(i32, i32),
    /// No frames added.
    NoFramesAdded,
    /// Dimensions must be positive.
    DimensionsMustbePositive,
}

impl core::fmt::Display for Error {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Error::EncoderCreateFailed => write!(f, "Encoder creation failed"),
            Error::EncoderAddFailed => write!(f, "Frame add failed"),
            Error::EncoderAssmebleFailed => write!(f, "Encoder assembly failed"),
            Error::DecodeFailed => write!(f, "Decode failed"),
            Error::BufferSizeFailed(got, expected) => {
                write!(
                    f,
                    "Buffer size mismatch: got {}, expected {}",
                    got, expected
                )
            }
            Error::TimestampMustBeHigherThanPrevious(ts, prev) => {
                write!(f, "Timestamp {} must be higher than previous {}", ts, prev)
            }
            Error::NoFramesAdded => write!(f, "No frames added"),
            Error::DimensionsMustbePositive => write!(f, "Dimensions must be positive"),
        }
    }
}

/// Encoder options.
#[deprecated(
    since = "0.2.1",
    note = "use the main webpx animation API; see module docs"
)]
#[derive(Debug, Clone, Default)]
pub struct EncoderOptions {
    /// Minimum keyframe interval.
    pub kmin: i32,
    /// Maximum keyframe interval.
    pub kmax: i32,
    /// Encoding configuration.
    pub encoding_config: Option<EncodingConfig>,
}

/// Encoding configuration.
#[deprecated(
    since = "0.2.1",
    note = "use the main webpx animation API; see module docs"
)]
#[derive(Debug, Clone)]
pub struct EncodingConfig {
    /// Quality (0-100).
    pub quality: f32,
    /// Encoding type.
    pub encoding_type: EncodingType,
}

impl Default for EncodingConfig {
    fn default() -> Self {
        Self {
            quality: 75.0,
            encoding_type: EncodingType::Lossy(LossyEncodingConfig::default()),
        }
    }
}

/// Encoding type.
#[deprecated(
    since = "0.2.1",
    note = "use the main webpx animation API; see module docs"
)]
#[derive(Debug, Clone)]
pub enum EncodingType {
    /// Lossy encoding.
    Lossy(LossyEncodingConfig),
    /// Lossless encoding.
    Lossless,
}

/// Lossy encoding configuration.
#[deprecated(
    since = "0.2.1",
    note = "use the main webpx animation API; see module docs"
)]
#[derive(Debug, Clone, Default)]
pub struct LossyEncodingConfig {
    /// Number of segments.
    pub segments: i32,
    /// Alpha compression.
    pub alpha_compression: bool,
}

/// Decoded animation frame.
#[deprecated(
    since = "0.2.1",
    note = "use the main webpx animation API; see module docs"
)]
#[derive(Debug, Clone)]
pub struct Frame {
    data: Vec<u8>,
    width: u32,
    height: u32,
    timestamp: i32,
    color_mode: ColorMode,
}

impl Frame {
    /// Get frame dimensions as tuple.
    pub fn dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Get frame pixel data.
    pub fn data(&self) -> &[u8] {
        &self.data
    }

    /// Get frame timestamp in milliseconds.
    pub fn timestamp(&self) -> i32 {
        self.timestamp
    }

    /// Get the color mode.
    pub fn color_mode(&self) -> ColorMode {
        self.color_mode
    }
}

/// Decoder options.
#[deprecated(
    since = "0.2.1",
    note = "use the main webpx animation API; see module docs"
)]
#[derive(Debug, Clone, Default)]
pub struct DecoderOptions {
    /// Use multi-threaded decoding.
    pub use_threads: bool,
    /// Output color mode.
    pub color_mode: ColorMode,
}

/// Animation encoder (compatible with `webp_animation::Encoder`).
#[deprecated(
    since = "0.2.1",
    note = "use the main webpx animation API; see module docs"
)]
#[cfg(all(feature = "animation", feature = "encode"))]
pub struct Encoder {
    inner: crate::AnimationEncoder,
    previous_timestamp: i32,
    frame_count: u32,
}

#[cfg(all(feature = "animation", feature = "encode"))]
impl Encoder {
    /// Create a new encoder with dimensions.
    pub fn new(dimensions: (u32, u32)) -> Result<Self, Error> {
        Self::new_with_options(dimensions, EncoderOptions::default())
    }

    /// Create a new encoder with options.
    pub fn new_with_options(
        dimensions: (u32, u32),
        options: EncoderOptions,
    ) -> Result<Self, Error> {
        let (width, height) = dimensions;
        if width == 0 || height == 0 {
            return Err(Error::DimensionsMustbePositive);
        }

        let mut inner =
            crate::AnimationEncoder::new(width, height).map_err(|_| Error::EncoderCreateFailed)?;

        if let Some(config) = &options.encoding_config {
            inner.set_quality(config.quality);
            if matches!(config.encoding_type, EncodingType::Lossless) {
                inner.set_lossless(true);
            }
        }

        Ok(Self {
            inner,
            previous_timestamp: -1,
            frame_count: 0,
        })
    }

    /// Add a frame at the given timestamp.
    pub fn add_frame(&mut self, data: &[u8], timestamp_ms: i32) -> Result<(), Error> {
        if timestamp_ms <= self.previous_timestamp {
            return Err(Error::TimestampMustBeHigherThanPrevious(
                timestamp_ms,
                self.previous_timestamp,
            ));
        }

        self.inner
            .add_frame_rgba(data, timestamp_ms)
            .map_err(|_| Error::EncoderAddFailed)?;

        self.previous_timestamp = timestamp_ms;
        self.frame_count += 1;
        Ok(())
    }

    /// Finalize the animation and return WebP data.
    ///
    /// Note: This is named `finalize` to match webp-animation API.
    /// The underlying webpx API uses `finish`.
    pub fn finalize(self, end_timestamp_ms: i32) -> Result<WebPData, Error> {
        if self.frame_count == 0 {
            return Err(Error::NoFramesAdded);
        }

        let data = self
            .inner
            .finish(end_timestamp_ms)
            .map_err(|_| Error::EncoderAssmebleFailed)?;

        Ok(WebPData(data))
    }
}

/// Animation decoder (compatible with `webp_animation::Decoder`).
#[deprecated(
    since = "0.2.1",
    note = "use the main webpx animation API; see module docs"
)]
#[cfg(all(feature = "animation", feature = "decode"))]
pub struct Decoder<'a> {
    data: &'a [u8],
    options: DecoderOptions,
}

#[cfg(all(feature = "animation", feature = "decode"))]
impl<'a> Decoder<'a> {
    /// Create a new decoder from WebP data.
    pub fn new(data: &'a [u8]) -> Result<Self, Error> {
        Self::new_with_options(data, DecoderOptions::default())
    }

    /// Create a new decoder with options.
    pub fn new_with_options(data: &'a [u8], options: DecoderOptions) -> Result<Self, Error> {
        if data.is_empty() {
            return Err(Error::DecodeFailed);
        }
        Ok(Self { data, options })
    }

    /// Decode all frames into a vector.
    pub fn decode(&self) -> Result<Vec<Frame>, Error> {
        let mut decoder = crate::AnimationDecoder::with_options(
            self.data,
            self.options.color_mode.into(),
            self.options.use_threads,
        )
        .map_err(|_| Error::DecodeFailed)?;

        let mut frames = Vec::new();

        while let Some(frame) = decoder.next_frame().map_err(|_| Error::DecodeFailed)? {
            frames.push(Frame {
                data: frame.data,
                width: frame.width,
                height: frame.height,
                timestamp: frame.timestamp_ms,
                color_mode: self.options.color_mode,
            });
        }

        Ok(frames)
    }
}

#[cfg(all(feature = "animation", feature = "decode"))]
impl<'a> IntoIterator for Decoder<'a> {
    type Item = Frame;
    type IntoIter = DecoderIterator;

    fn into_iter(self) -> Self::IntoIter {
        let inner = crate::AnimationDecoder::with_options(
            self.data,
            self.options.color_mode.into(),
            self.options.use_threads,
        )
        .ok();

        DecoderIterator {
            inner,
            color_mode: self.options.color_mode,
        }
    }
}

/// Iterator over animation frames.
#[deprecated(
    since = "0.2.1",
    note = "use the main webpx animation API; see module docs"
)]
#[cfg(all(feature = "animation", feature = "decode"))]
pub struct DecoderIterator {
    inner: Option<crate::AnimationDecoder>,
    color_mode: ColorMode,
}

#[cfg(all(feature = "animation", feature = "decode"))]
impl Iterator for DecoderIterator {
    type Item = Frame;

    fn next(&mut self) -> Option<Self::Item> {
        let decoder = self.inner.as_mut()?;
        let frame = decoder.next_frame().ok()??;

        Some(Frame {
            data: frame.data,
            width: frame.width,
            height: frame.height,
            timestamp: frame.timestamp_ms,
            color_mode: self.color_mode,
        })
    }
}

/// Prelude for common imports.
pub mod prelude {
    pub use super::ColorMode;
    #[cfg(all(feature = "animation", feature = "decode"))]
    pub use super::Decoder;
    #[cfg(all(feature = "animation", feature = "encode"))]
    pub use super::Encoder;
    #[cfg(feature = "animation")]
    pub use super::{DecoderOptions, EncoderOptions};
    #[cfg(feature = "animation")]
    pub use super::{EncodingConfig, EncodingType, LossyEncodingConfig};
}

#[cfg(all(test, feature = "animation", feature = "decode", feature = "encode"))]
mod tests {
    use super::*;

    #[test]
    fn test_encode_decode_animation() {
        let frame1 = vec![255u8; 4 * 4 * 4]; // 4x4 white
        let frame2 = vec![0u8; 4 * 4 * 4]; // 4x4 black

        let mut encoder = Encoder::new((4, 4)).expect("create encoder");
        encoder.add_frame(&frame1, 0).expect("add frame 1");
        encoder.add_frame(&frame2, 100).expect("add frame 2");

        let webp = encoder.finalize(200).expect("finalize");
        assert!(!webp.is_empty());

        let decoder = Decoder::new(&webp).expect("create decoder");
        let frames: Vec<_> = decoder.into_iter().collect();
        assert_eq!(frames.len(), 2);
        assert_eq!(frames[0].dimensions(), (4, 4));
    }

    #[test]
    fn test_timestamp_ordering() {
        let frame = vec![0u8; 4 * 4 * 4];
        let mut encoder = Encoder::new((4, 4)).expect("create encoder");

        encoder.add_frame(&frame, 100).expect("add frame");
        let result = encoder.add_frame(&frame, 50); // timestamp goes backwards
        assert!(matches!(
            result,
            Err(Error::TimestampMustBeHigherThanPrevious(50, 100))
        ));
    }
}