webpx 0.3.2

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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
//! `zencodec` trait implementations for `webpx`.
//!
//! Mirrors `zenwebp::zencodec`'s public types so downstream code that
//! consumes the trait surface compiles unchanged when swapping crates:
//!
//! ```rust,ignore
//! // With webpx:
//! use webpx::zencodec::WebpEncoderConfig;
//! // Or with zenwebp:
//! use zenwebp::zencodec::WebpEncoderConfig;
//!
//! use zencodec::encode::EncoderConfig;
//! let cfg = WebpEncoderConfig::lossy().with_generic_quality(85.0);
//! ```
//!
//! All four executor traits — `Encoder`, `Decode`,
//! `AnimationFrameEncoder`, `AnimationFrameDecoder`, `StreamingDecode`
//! — are wired through `zencodec`. Animation and streaming require the
//! matching webpx Cargo features (`animation`, `streaming`); when
//! disabled, the corresponding wrapper types stub out and surface
//! `Error::InvalidConfig` from their constructors.

use alloc::borrow::Cow;
use alloc::format;
use alloc::sync::Arc;
use alloc::vec::Vec;

use whereat::{At, at};
use zencodec::decode::{DecodeOutput, DecodeRowSink, OutputInfo};
use zencodec::encode::EncodeOutput;
use zencodec::{
    ImageFormat, ImageInfo, ImageSequence, Metadata, ResourceLimits, UnsupportedOperation,
};
use zenpixels::{PixelBuffer, PixelDescriptor, PixelSlice};

use crate::error::Error;
use crate::{ColorMode, DecoderConfig, EncoderConfig, Limits};

// ── Encoder side ───────────────────────────────────────────────────────────

/// WebP encoder configuration implementing
/// [`zencodec::encode::EncoderConfig`].
#[derive(Clone, Debug)]
pub struct WebpEncoderConfig {
    inner: EncoderConfig,
    lossless_flag: bool,
    trait_quality: Option<f32>,
    trait_effort: Option<i32>,
    alpha_quality_override: Option<f32>,
}

impl WebpEncoderConfig {
    /// Lossy encoder config with library defaults.
    #[must_use]
    pub fn lossy() -> Self {
        Self {
            inner: EncoderConfig::new(),
            lossless_flag: false,
            trait_quality: None,
            trait_effort: None,
            alpha_quality_override: None,
        }
    }

    /// Lossless encoder config with library defaults.
    #[must_use]
    pub fn lossless() -> Self {
        Self {
            inner: EncoderConfig::new().lossless(true),
            lossless_flag: true,
            trait_quality: None,
            trait_effort: None,
            alpha_quality_override: None,
        }
    }

    /// Construct from a webpx [`crate::EncoderConfig`] directly.
    #[must_use]
    pub fn from_native(inner: EncoderConfig) -> Self {
        let lossless_flag = inner.is_lossless();
        Self {
            inner,
            lossless_flag,
            trait_quality: None,
            trait_effort: None,
            alpha_quality_override: None,
        }
    }

    /// Borrow the underlying webpx [`crate::EncoderConfig`].
    #[must_use]
    pub fn inner(&self) -> &EncoderConfig {
        &self.inner
    }

    /// Native webpx quality (0.0–100.0).
    #[must_use]
    pub fn with_quality(mut self, quality: f32) -> Self {
        self.inner = self.inner.clone().quality(quality);
        self
    }

    /// Native webpx encoding method (0–6).
    #[must_use]
    pub fn with_method(mut self, method: u8) -> Self {
        self.inner = self.inner.clone().method(method);
        self
    }

    /// Content-aware preset (lossy only).
    #[must_use]
    pub fn with_preset_value(mut self, preset: crate::Preset) -> Self {
        self.inner = self.inner.clone().preset(preset);
        self
    }

    /// Alpha plane quality (0–100). No-op when the alpha plane is absent.
    #[must_use]
    pub fn with_alpha_quality_value(mut self, quality: u8) -> Self {
        self.inner = self.inner.clone().alpha_quality(quality);
        self
    }
}

static ENCODE_DESCRIPTORS: &[PixelDescriptor] = &[
    PixelDescriptor::RGBA8_SRGB,
    PixelDescriptor::BGRA8_SRGB,
    PixelDescriptor::RGB8_SRGB,
];

static ENCODE_CAPABILITIES: zencodec::encode::EncodeCapabilities =
    zencodec::encode::EncodeCapabilities::new()
        .with_icc(true)
        .with_exif(true)
        .with_xmp(true)
        .with_stop(true)
        .with_lossy(true)
        .with_lossless(true)
        .with_native_alpha(true)
        .with_effort_range(0, 6)
        .with_quality_range(0.0, 100.0)
        .with_enforces_max_pixels(true);

fn calibrated_webp_quality(generic_q: f32) -> f32 {
    generic_q.clamp(0.0, 100.0)
}

fn effort_to_method(effort: i32) -> u8 {
    let e = effort.clamp(0, 10) as u32;
    ((e * 6) / 10).min(6) as u8
}

impl zencodec::encode::EncoderConfig for WebpEncoderConfig {
    type Error = At<Error>;
    type Job = WebpEncodeJob;

    fn format() -> ImageFormat {
        ImageFormat::WebP
    }

    fn supported_descriptors() -> &'static [PixelDescriptor] {
        ENCODE_DESCRIPTORS
    }

    fn capabilities() -> &'static zencodec::encode::EncodeCapabilities {
        &ENCODE_CAPABILITIES
    }

    fn with_generic_quality(mut self, quality: f32) -> Self {
        let clamped = quality.clamp(0.0, 100.0);
        self.trait_quality = Some(clamped);
        self.inner = self.inner.clone().quality(calibrated_webp_quality(clamped));
        self
    }

    fn generic_quality(&self) -> Option<f32> {
        self.trait_quality
    }

    fn with_generic_effort(mut self, effort: i32) -> Self {
        let clamped = effort.clamp(0, 10);
        self.trait_effort = Some(clamped);
        self.inner = self.inner.clone().method(effort_to_method(clamped));
        self
    }

    fn generic_effort(&self) -> Option<i32> {
        self.trait_effort
    }

    fn with_lossless(mut self, lossless: bool) -> Self {
        self.lossless_flag = lossless;
        self.inner = self.inner.clone().lossless(lossless);
        self
    }

    fn is_lossless(&self) -> Option<bool> {
        Some(self.lossless_flag)
    }

    fn with_alpha_quality(mut self, quality: f32) -> Self {
        let aq = quality.clamp(0.0, 100.0);
        self.alpha_quality_override = Some(aq);
        self.inner = self.inner.clone().alpha_quality(aq as u8);
        self
    }

    fn alpha_quality(&self) -> Option<f32> {
        self.alpha_quality_override
    }

    fn job(self) -> WebpEncodeJob {
        WebpEncodeJob {
            config: self,
            stop: None,
            icc: None,
            exif: None,
            xmp: None,
            limits: ResourceLimits::none(),
        }
    }
}

/// Per-operation WebP encode job.
pub struct WebpEncodeJob {
    config: WebpEncoderConfig,
    stop: Option<zencodec::StopToken>,
    icc: Option<Arc<[u8]>>,
    exif: Option<Arc<[u8]>>,
    xmp: Option<Arc<[u8]>>,
    limits: ResourceLimits,
}

impl zencodec::encode::EncodeJob for WebpEncodeJob {
    type Error = At<Error>;
    type Enc = WebpEncoder;
    type AnimationFrameEnc = WebpAnimationFrameEncoder;

    fn with_stop(mut self, stop: zencodec::StopToken) -> Self {
        self.stop = Some(stop);
        self
    }

    fn with_metadata(mut self, meta: Metadata) -> Self {
        self.icc = meta.icc_profile;
        self.exif = meta.exif;
        self.xmp = meta.xmp;
        self
    }

    fn with_limits(mut self, limits: ResourceLimits) -> Self {
        self.limits = limits;
        self
    }

    fn encoder(self) -> Result<WebpEncoder, At<Error>> {
        Ok(WebpEncoder {
            config: self.config.inner.clone(),
            stop: self.stop,
            icc: self.icc,
            exif: self.exif,
            xmp: self.xmp,
            limits: Limits::from(self.limits),
        })
    }

    fn animation_frame_encoder(self) -> Result<WebpAnimationFrameEncoder, At<Error>> {
        #[cfg(not(feature = "animation"))]
        {
            return Err(at!(Error::InvalidConfig(
                "webpx built without `animation` feature".into(),
            )));
        }
        #[cfg(feature = "animation")]
        {
            // The trait contract gives us pixel data on push_frame, so
            // we can't construct the underlying encoder until the first
            // frame arrives — that's the only point we know the
            // canvas dimensions. Defer the AnimationEncoder::new call.
            Ok(WebpAnimationFrameEncoder {
                inner: None,
                config: self.config.inner.clone(),
                stop: self.stop,
                icc: self.icc,
                exif: self.exif,
                xmp: self.xmp,
                limits: Limits::from(self.limits),
                last_timestamp_ms: 0,
            })
        }
    }
}

/// WebP single-image encoder.
pub struct WebpEncoder {
    config: EncoderConfig,
    stop: Option<zencodec::StopToken>,
    icc: Option<Arc<[u8]>>,
    exif: Option<Arc<[u8]>>,
    xmp: Option<Arc<[u8]>>,
    limits: Limits,
}

#[allow(clippy::type_complexity)] // Single internal helper; named struct would add boilerplate without clarity.
fn pixels_to_webp_input<'a>(
    pixels: &'a PixelSlice<'a>,
) -> Result<(Cow<'a, [u8]>, ColorMode, u32, u32, u32), At<Error>> {
    let desc = pixels.descriptor();
    let w = pixels.width();
    let h = pixels.rows();
    let stride_bytes = pixels.stride() as u32;

    if desc == PixelDescriptor::RGBA8_SRGB {
        Ok((
            Cow::Borrowed(pixels.as_strided_bytes()),
            ColorMode::Rgba,
            w,
            h,
            stride_bytes,
        ))
    } else if desc == PixelDescriptor::BGRA8_SRGB {
        Ok((
            Cow::Borrowed(pixels.as_strided_bytes()),
            ColorMode::Bgra,
            w,
            h,
            stride_bytes,
        ))
    } else if desc == PixelDescriptor::RGB8_SRGB {
        Ok((
            Cow::Borrowed(pixels.as_strided_bytes()),
            ColorMode::Rgb,
            w,
            h,
            stride_bytes,
        ))
    } else {
        Err(at!(Error::InvalidInput(format!(
            "unsupported pixel format for WebP encode: {:?}",
            desc
        ))))
    }
}

fn apply_metadata(
    webp: Vec<u8>,
    icc: Option<&[u8]>,
    exif: Option<&[u8]>,
    xmp: Option<&[u8]>,
) -> Result<Vec<u8>, At<Error>> {
    #[cfg(feature = "icc")]
    {
        let mut webp = webp;
        if let Some(icc) = icc {
            webp = crate::embed_icc(&webp, icc)?;
        }
        if let Some(exif) = exif {
            webp = crate::embed_exif(&webp, exif)?;
        }
        if let Some(xmp) = xmp {
            webp = crate::embed_xmp(&webp, xmp)?;
        }
        Ok(webp)
    }
    #[cfg(not(feature = "icc"))]
    {
        if icc.is_some() || exif.is_some() || xmp.is_some() {
            return Err(at!(Error::InvalidConfig(
                "webpx built without `icc` feature; metadata cannot be embedded".into(),
            )));
        }
        Ok(webp)
    }
}

/// Bridges `zencodec::StopToken` into `enough::Stop`.
struct StopBridge<'a>(Option<&'a zencodec::StopToken>);

impl enough::Stop for StopBridge<'_> {
    fn check(&self) -> Result<(), enough::StopReason> {
        match self.0 {
            Some(t) => t.check(),
            None => Ok(()),
        }
    }
    fn should_stop(&self) -> bool {
        self.0.map(|t| t.should_stop()).unwrap_or(false)
    }
}

impl zencodec::encode::Encoder for WebpEncoder {
    type Error = At<Error>;

    fn reject(op: UnsupportedOperation) -> At<Error> {
        at!(Error::InvalidConfig(format!(
            "operation not supported by webpx WebP encoder: {op:?}"
        )))
    }

    fn encode(self, pixels: PixelSlice<'_>) -> Result<EncodeOutput, At<Error>> {
        let (buf, mode, w, h, stride_bytes) = pixels_to_webp_input(&pixels)?;
        self.limits
            .check_dimensions(w, h)
            .map_err(|e| at!(Error::LimitExceeded(e)))?;

        let stop = StopBridge(self.stop.as_ref());
        let webp = match mode {
            ColorMode::Rgba => crate::Encoder::new_rgba_stride(&buf, w, h, stride_bytes)
                .config(self.config.clone())
                .encode(&stop)?,
            ColorMode::Bgra => crate::Encoder::new_bgra_stride(&buf, w, h, stride_bytes)
                .config(self.config.clone())
                .encode(&stop)?,
            ColorMode::Rgb => crate::Encoder::new_rgb_stride(&buf, w, h, stride_bytes)
                .config(self.config.clone())
                .encode(&stop)?,
            _ => unreachable!(),
        };

        let webp = apply_metadata(
            webp,
            self.icc.as_deref(),
            self.exif.as_deref(),
            self.xmp.as_deref(),
        )?;

        self.limits
            .check_output_size(webp.len() as u64)
            .map_err(|e| at!(Error::LimitExceeded(e)))?;

        Ok(EncodeOutput::new(webp, ImageFormat::WebP))
    }
}

/// WebP animation-frame encoder implementing
/// [`zencodec::encode::AnimationFrameEncoder`].
///
/// The underlying [`crate::AnimationEncoder`] requires canvas
/// dimensions at construction, but `zencodec`'s trait gives us pixels
/// only at `push_frame` time. We defer the underlying encoder's
/// construction until the first frame arrives so we can read its
/// dimensions; subsequent frames must match.
#[cfg(feature = "animation")]
pub struct WebpAnimationFrameEncoder {
    inner: Option<crate::AnimationEncoder>,
    config: EncoderConfig,
    /// Stored at construction time but not currently propagated to
    /// libwebp's animation encoder (which doesn't take a stop token).
    /// Keep the field so `with_stop` from the EncodeJob still flows
    /// through and a future libwebp/webpx version can wire it in.
    #[allow(dead_code)]
    stop: Option<zencodec::StopToken>,
    icc: Option<Arc<[u8]>>,
    exif: Option<Arc<[u8]>>,
    xmp: Option<Arc<[u8]>>,
    limits: Limits,
    /// Cumulative timestamp of frames added so far. webpx's animation
    /// API takes per-frame timestamps; we track them ourselves so the
    /// trait's `duration_ms` parameter maps cleanly.
    last_timestamp_ms: u32,
}

#[cfg(feature = "animation")]
impl zencodec::encode::AnimationFrameEncoder for WebpAnimationFrameEncoder {
    type Error = At<Error>;

    fn reject(op: UnsupportedOperation) -> At<Error> {
        at!(Error::InvalidConfig(format!(
            "operation not supported by webpx animation encoder: {op:?}"
        )))
    }

    fn push_frame(
        &mut self,
        pixels: PixelSlice<'_>,
        duration_ms: u32,
        _stop: Option<&dyn enough::Stop>,
    ) -> Result<(), At<Error>> {
        let (buf, mode, w, h, _stride_bytes) = pixels_to_webp_input(&pixels)?;

        self.limits
            .check_dimensions(w, h)
            .map_err(|e| at!(Error::LimitExceeded(e)))?;

        // Construct the underlying AnimationEncoder lazily on the
        // first frame so we know the canvas size.
        if self.inner.is_none() {
            let mut enc = crate::AnimationEncoder::new(w, h)?;
            // Carry over the encoder-config knobs the AnimationEncoder
            // exposes setters for (quality / lossless). Other knobs on
            // EncoderConfig are not plumbed through libwebp's anim
            // encoder API.
            enc.set_quality(self.config.get_quality());
            if self.config.is_lossless() {
                enc.set_lossless(true);
            }
            self.inner = Some(enc);
        }

        let enc = self.inner.as_mut().expect("just initialized");
        let timestamp_ms = self.last_timestamp_ms as i32;

        // The native `add_frame_*` family takes tightly-packed pixel
        // slices (stride = width * bpp). When the caller passes a
        // strided slice, copy into a contiguous buffer first. The
        // common case (stride == width * bpp) is zero-copy via
        // `Cow::Borrowed` from `pixels_to_webp_input`.
        let bpp = match mode {
            ColorMode::Rgba | ColorMode::Bgra => 4,
            ColorMode::Rgb | ColorMode::Bgr => 3,
            _ => unreachable!(),
        };
        let row_bytes = w as usize * bpp;
        let stride_bytes_usize = pixels.stride();
        let contiguous: Cow<'_, [u8]> = if stride_bytes_usize == row_bytes {
            buf
        } else {
            // Strided source: copy into a tightly-packed buffer.
            let mut packed = alloc::vec![0u8; row_bytes * h as usize];
            for y in 0..h as usize {
                let src = &buf[y * stride_bytes_usize..y * stride_bytes_usize + row_bytes];
                packed[y * row_bytes..(y + 1) * row_bytes].copy_from_slice(src);
            }
            Cow::Owned(packed)
        };

        match mode {
            ColorMode::Rgba => enc.add_frame_rgba(&contiguous, timestamp_ms)?,
            ColorMode::Bgra => enc.add_frame_bgra(&contiguous, timestamp_ms)?,
            ColorMode::Rgb => enc.add_frame_rgb(&contiguous, timestamp_ms)?,
            ColorMode::Bgr => enc.add_frame_bgr(&contiguous, timestamp_ms)?,
            _ => unreachable!(),
        }

        self.last_timestamp_ms = self.last_timestamp_ms.saturating_add(duration_ms);
        Ok(())
    }

    fn finish(mut self, _stop: Option<&dyn enough::Stop>) -> Result<EncodeOutput, At<Error>> {
        let enc = self.inner.take().ok_or_else(|| {
            at!(Error::InvalidConfig(
                "AnimationFrameEncoder::finish called before any push_frame".into(),
            ))
        })?;
        let webp = enc.finish(self.last_timestamp_ms as i32)?;
        let webp = apply_metadata(
            webp,
            self.icc.as_deref(),
            self.exif.as_deref(),
            self.xmp.as_deref(),
        )?;
        self.limits
            .check_output_size(webp.len() as u64)
            .map_err(|e| at!(Error::LimitExceeded(e)))?;
        Ok(EncodeOutput::new(webp, ImageFormat::WebP))
    }
}

/// Stub when the `animation` feature is off.
#[cfg(not(feature = "animation"))]
pub struct WebpAnimationFrameEncoder {
    _marker: core::marker::PhantomData<()>,
}

#[cfg(not(feature = "animation"))]
impl zencodec::encode::AnimationFrameEncoder for WebpAnimationFrameEncoder {
    type Error = At<Error>;

    fn reject(_op: UnsupportedOperation) -> At<Error> {
        at!(Error::InvalidConfig(
            "webpx built without `animation` feature".into(),
        ))
    }

    fn push_frame(
        &mut self,
        _pixels: PixelSlice<'_>,
        _duration_ms: u32,
        _stop: Option<&dyn enough::Stop>,
    ) -> Result<(), At<Error>> {
        Err(Self::reject(UnsupportedOperation::AnimationEncode))
    }

    fn finish(self, _stop: Option<&dyn enough::Stop>) -> Result<EncodeOutput, At<Error>> {
        Err(Self::reject(UnsupportedOperation::AnimationEncode))
    }
}

// ── Decoder side ───────────────────────────────────────────────────────────

/// WebP decoder configuration.
#[derive(Clone, Debug, Default)]
pub struct WebpDecoderConfig {
    inner: DecoderConfig,
}

impl WebpDecoderConfig {
    /// Decoder config with library defaults.
    #[must_use]
    pub fn new() -> Self {
        Self {
            inner: DecoderConfig::new(),
        }
    }

    /// Construct from a webpx [`crate::DecoderConfig`] directly.
    #[must_use]
    pub fn from_native(inner: DecoderConfig) -> Self {
        Self { inner }
    }
}

static DECODE_FORMATS: &[ImageFormat] = &[ImageFormat::WebP];

static DECODE_DESCRIPTORS: &[PixelDescriptor] = &[
    PixelDescriptor::RGBA8_SRGB,
    PixelDescriptor::BGRA8_SRGB,
    PixelDescriptor::RGB8_SRGB,
];

static DECODE_CAPABILITIES: zencodec::decode::DecodeCapabilities =
    zencodec::decode::DecodeCapabilities::new()
        .with_icc(true)
        .with_exif(true)
        .with_xmp(true)
        .with_stop(true)
        .with_enforces_max_pixels(true);

impl zencodec::decode::DecoderConfig for WebpDecoderConfig {
    type Error = At<Error>;
    type Job<'a> = WebpDecodeJob;

    fn formats() -> &'static [ImageFormat] {
        DECODE_FORMATS
    }

    fn supported_descriptors() -> &'static [PixelDescriptor] {
        DECODE_DESCRIPTORS
    }

    fn capabilities() -> &'static zencodec::decode::DecodeCapabilities {
        &DECODE_CAPABILITIES
    }

    fn job<'a>(self) -> Self::Job<'a> {
        WebpDecodeJob {
            config: self,
            stop: None,
            limits: ResourceLimits::none(),
        }
    }
}

/// Per-operation WebP decode job.
pub struct WebpDecodeJob {
    config: WebpDecoderConfig,
    stop: Option<zencodec::StopToken>,
    limits: ResourceLimits,
}

fn build_zencodec_image_info(info: crate::ImageInfo) -> ImageInfo {
    let mut out = ImageInfo::new(info.width, info.height, ImageFormat::WebP);
    if info.has_alpha {
        out = out.with_alpha(true);
    }
    if info.has_animation {
        out = out.with_sequence(ImageSequence::Animation {
            frame_count: Some(info.frame_count),
            loop_count: None,
            random_access: false,
        });
    }
    out
}

fn pick_decode_descriptor(preferred: &[PixelDescriptor]) -> PixelDescriptor {
    for &p in preferred {
        if p == PixelDescriptor::RGBA8_SRGB
            || p == PixelDescriptor::BGRA8_SRGB
            || p == PixelDescriptor::RGB8_SRGB
        {
            return p;
        }
    }
    PixelDescriptor::RGBA8_SRGB
}

impl<'a> zencodec::decode::DecodeJob<'a> for WebpDecodeJob {
    type Error = At<Error>;
    type Dec = WebpDecoder<'a>;
    type StreamDec = WebpStreamingDecoder;
    type AnimationFrameDec = WebpAnimationFrameDecoder;

    fn with_stop(mut self, stop: zencodec::StopToken) -> Self {
        self.stop = Some(stop);
        self
    }

    fn with_limits(mut self, limits: ResourceLimits) -> Self {
        self.limits = limits;
        self
    }

    fn probe(&self, data: &[u8]) -> Result<ImageInfo, At<Error>> {
        let info = crate::ImageInfo::from_webp(data)?;
        Ok(build_zencodec_image_info(info))
    }

    fn output_info(&self, data: &[u8]) -> Result<OutputInfo, At<Error>> {
        let info = crate::ImageInfo::from_webp(data)?;
        let descriptor = if info.has_alpha {
            PixelDescriptor::RGBA8_SRGB
        } else {
            PixelDescriptor::RGB8_SRGB
        };
        Ok(OutputInfo::full_decode(info.width, info.height, descriptor))
    }

    fn decoder(
        self,
        data: Cow<'a, [u8]>,
        preferred: &[PixelDescriptor],
    ) -> Result<WebpDecoder<'a>, At<Error>> {
        let chosen = pick_decode_descriptor(preferred);
        Ok(WebpDecoder {
            data,
            config: self.config.inner,
            stop: self.stop,
            chosen,
            limits: Limits::from(self.limits),
        })
    }

    fn push_decoder(
        self,
        data: Cow<'a, [u8]>,
        sink: &mut dyn DecodeRowSink,
        preferred: &[PixelDescriptor],
    ) -> Result<OutputInfo, At<Error>> {
        // Decode normally, then hand the bytes to the sink as a single
        // strip. A future iteration could push the libwebp decoder
        // through scanlines, but row-level WebP decoding requires the
        // incremental API plus more bookkeeping than we want here.
        let dec_job = self;
        let info_z = dec_job.output_info(&data)?;
        let chosen = pick_decode_descriptor(preferred);
        let dec = WebpDecoder {
            data,
            config: dec_job.config.inner,
            stop: dec_job.stop,
            chosen,
            limits: Limits::from(dec_job.limits),
        };
        let out = <WebpDecoder<'_> as zencodec::decode::Decode>::decode(dec)?;
        let buf = out.into_buffer();
        let src = buf.as_slice();
        let w = src.width();
        let h = src.rows();
        sink.begin(w, h, chosen)
            .map_err(|e| at!(Error::InvalidInput(format!("sink begin: {e}"))))?;
        let mut dst = sink
            .provide_next_buffer(0, h, w, chosen)
            .map_err(|e| at!(Error::InvalidInput(format!("sink provide: {e}"))))?;
        let src_bytes = src.as_strided_bytes();
        let bpp = chosen.bytes_per_pixel();
        let row_bytes = w as usize * bpp;
        let src_stride = src.stride();
        for y in 0..h as usize {
            let src_row = &src_bytes[y * src_stride..y * src_stride + row_bytes];
            let dst_row = dst.row_mut(y as u32);
            dst_row[..row_bytes].copy_from_slice(src_row);
        }
        sink.finish()
            .map_err(|e| at!(Error::InvalidInput(format!("sink finish: {e}"))))?;
        Ok(info_z)
    }

    fn streaming_decoder(
        self,
        _data: Cow<'a, [u8]>,
        _preferred: &[PixelDescriptor],
    ) -> Result<WebpStreamingDecoder, At<Error>> {
        #[cfg(not(feature = "streaming"))]
        {
            return Err(at!(Error::InvalidConfig(
                "webpx built without `streaming` feature".into(),
            )));
        }
        #[cfg(feature = "streaming")]
        {
            // Probe the bitstream up-front for the ImageInfo we need
            // to expose via the trait, plus to surface limit
            // violations before any allocation.
            let probe = crate::ImageInfo::from_webp(&_data)?;
            let limits = Limits::from(self.limits);
            limits
                .check_dimensions(probe.width, probe.height)
                .map_err(|e| at!(Error::LimitExceeded(e)))?;

            let descriptor = pick_decode_descriptor(_preferred);
            let zen_info = build_zencodec_image_info(probe);
            // Buffered approach: stash the input, expose the whole
            // image as a single batch via the native one-shot
            // decoder. A row-by-row implementation against
            // crate::StreamingDecoder is possible but that API takes
            // mutable input chunks and we already own the data here;
            // the buffered shape is simpler and matches zenwebp's.
            Ok(WebpStreamingDecoder {
                data: _data.into_owned(),
                descriptor,
                info: zen_info,
                config: self.config.inner,
                limits,
                emitted: false,
                decoded: None,
            })
        }
    }

    fn animation_frame_decoder(
        self,
        _data: Cow<'a, [u8]>,
        _preferred: &[PixelDescriptor],
    ) -> Result<WebpAnimationFrameDecoder, At<Error>> {
        #[cfg(not(feature = "animation"))]
        {
            return Err(at!(Error::InvalidConfig(
                "webpx built without `animation` feature".into(),
            )));
        }
        #[cfg(feature = "animation")]
        {
            // libwebp's animation decoder only produces RGBA / BGRA;
            // map preferred descriptor to one of those.
            let mode = match pick_decode_descriptor(_preferred) {
                PixelDescriptor::BGRA8_SRGB => ColorMode::Bgra,
                _ => ColorMode::Rgba,
            };
            let descriptor = match mode {
                ColorMode::Bgra => PixelDescriptor::BGRA8_SRGB,
                _ => PixelDescriptor::RGBA8_SRGB,
            };
            let owned = _data.into_owned();
            let limits = Limits::from(self.limits);
            let inner = crate::AnimationDecoder::with_options_limits(&owned, mode, true, &limits)?;
            let n_info = inner.info();
            let zen_info = ImageInfo::new(n_info.width, n_info.height, ImageFormat::WebP)
                .with_alpha(true)
                .with_sequence(ImageSequence::Animation {
                    frame_count: Some(n_info.frame_count),
                    loop_count: Some(n_info.loop_count),
                    random_access: false,
                });
            Ok(WebpAnimationFrameDecoder {
                inner,
                _data: owned,
                info: zen_info,
                descriptor,
                last_pixels: Vec::new(),
                last_width: 0,
                last_height: 0,
            })
        }
    }
}

/// WebP single-image decoder.
pub struct WebpDecoder<'a> {
    data: Cow<'a, [u8]>,
    config: DecoderConfig,
    stop: Option<zencodec::StopToken>,
    chosen: PixelDescriptor,
    limits: Limits,
}

impl zencodec::decode::Decode for WebpDecoder<'_> {
    type Error = At<Error>;

    fn decode(self) -> Result<DecodeOutput, At<Error>> {
        let _ = &self.stop;
        let cfg = self.config.limits(self.limits);
        let dec = crate::Decoder::new(&self.data)?.config(cfg);
        let (bytes, w, h, descriptor) = match self.chosen {
            PixelDescriptor::RGBA8_SRGB => {
                let (b, w, h) = dec.decode_rgba_raw()?;
                (b, w, h, PixelDescriptor::RGBA8_SRGB)
            }
            PixelDescriptor::BGRA8_SRGB => {
                let (b, w, h) = dec.decode_bgra_raw()?;
                (b, w, h, PixelDescriptor::BGRA8_SRGB)
            }
            PixelDescriptor::RGB8_SRGB => {
                let (b, w, h) = dec.decode_rgb_raw()?;
                (b, w, h, PixelDescriptor::RGB8_SRGB)
            }
            _ => unreachable!(),
        };

        let buf = PixelBuffer::from_vec(bytes, w, h, descriptor)
            .map_err(|e| at!(Error::InvalidInput(format!("{e:?}"))))?;
        let info = ImageInfo::new(w, h, ImageFormat::WebP).with_alpha(descriptor.has_alpha());
        Ok(DecodeOutput::new(buf, info))
    }
}

/// WebP streaming decoder implementing
/// [`zencodec::decode::StreamingDecode`].
///
/// The current shape buffers the full input, then hands the entire
/// decoded image back as a single batch on the first `next_batch`
/// call. libwebp's true incremental decoder ([`crate::StreamingDecoder`])
/// can yield rows as they're decoded; wiring that in row-batch form
/// is left for a future iteration. The trait contract permits this
/// shape (a single `(0, full_image)` batch followed by `Ok(None)`).
#[cfg(feature = "streaming")]
pub struct WebpStreamingDecoder {
    data: Vec<u8>,
    descriptor: PixelDescriptor,
    info: ImageInfo,
    config: DecoderConfig,
    limits: Limits,
    emitted: bool,
    decoded: Option<(Vec<u8>, u32, u32)>,
}

#[cfg(feature = "streaming")]
impl zencodec::decode::StreamingDecode for WebpStreamingDecoder {
    type Error = At<Error>;

    fn next_batch(&mut self) -> Result<Option<(u32, PixelSlice<'_>)>, At<Error>> {
        if self.emitted {
            return Ok(None);
        }
        if self.decoded.is_none() {
            let cfg = self.config.clone().limits(self.limits);
            let dec = crate::Decoder::new(&self.data)?.config(cfg);
            let (bytes, w, h) = match self.descriptor {
                PixelDescriptor::RGBA8_SRGB => dec.decode_rgba_raw()?,
                PixelDescriptor::BGRA8_SRGB => dec.decode_bgra_raw()?,
                PixelDescriptor::RGB8_SRGB => dec.decode_rgb_raw()?,
                _ => unreachable!("pick_decode_descriptor only returns supported variants"),
            };
            self.decoded = Some((bytes, w, h));
        }
        self.emitted = true;
        let (bytes, w, h) = self.decoded.as_ref().unwrap();
        let stride_bytes = *w as usize * self.descriptor.bytes_per_pixel();
        let slice = PixelSlice::new(bytes, *w, *h, stride_bytes, self.descriptor)
            .map_err(|e| at!(Error::InvalidInput(format!("{e:?}"))))?;
        Ok(Some((0, slice)))
    }

    fn info(&self) -> &ImageInfo {
        &self.info
    }
}

/// Stub when the `streaming` feature is off.
#[cfg(not(feature = "streaming"))]
pub struct WebpStreamingDecoder {
    _marker: core::marker::PhantomData<()>,
}

#[cfg(not(feature = "streaming"))]
impl zencodec::decode::StreamingDecode for WebpStreamingDecoder {
    type Error = At<Error>;

    fn next_batch(&mut self) -> Result<Option<(u32, PixelSlice<'_>)>, At<Error>> {
        Err(at!(Error::InvalidConfig(
            "webpx built without `streaming` feature".into(),
        )))
    }

    fn info(&self) -> &ImageInfo {
        unreachable!("streaming feature not enabled");
    }
}

/// WebP animation-frame decoder implementing
/// [`zencodec::decode::AnimationFrameDecoder`].
#[cfg(feature = "animation")]
pub struct WebpAnimationFrameDecoder {
    inner: crate::AnimationDecoder,
    /// Holds the input bytes alive for the duration of the decoder.
    /// libwebp's demuxer keeps a raw pointer into this slice.
    _data: Vec<u8>,
    info: ImageInfo,
    descriptor: PixelDescriptor,
    /// Most recently produced frame's pixels. Owned so the
    /// `AnimationFrame<'_>` we return can borrow from it; cleared on
    /// each new `render_next_frame` call.
    last_pixels: Vec<u8>,
    last_width: u32,
    last_height: u32,
}

#[cfg(feature = "animation")]
impl zencodec::decode::AnimationFrameDecoder for WebpAnimationFrameDecoder {
    type Error = At<Error>;

    fn wrap_sink_error(e: zencodec::decode::SinkError) -> At<Error> {
        at!(Error::InvalidInput(format!("sink error: {e}")))
    }

    fn info(&self) -> &ImageInfo {
        &self.info
    }

    fn render_next_frame(
        &mut self,
        _stop: Option<&dyn enough::Stop>,
    ) -> Result<Option<zencodec::decode::AnimationFrame<'_>>, At<Error>> {
        let frame = match self.inner.next_frame()? {
            Some(f) => f,
            None => return Ok(None),
        };
        // Cache pixels so the returned PixelSlice can borrow safely.
        self.last_pixels = frame.data;
        self.last_width = frame.width;
        self.last_height = frame.height;
        let stride_bytes = self.last_width as usize * self.descriptor.bytes_per_pixel();
        let slice = PixelSlice::new(
            &self.last_pixels,
            self.last_width,
            self.last_height,
            stride_bytes,
            self.descriptor,
        )
        .map_err(|e| at!(Error::InvalidInput(format!("{e:?}"))))?;
        Ok(Some(zencodec::decode::AnimationFrame::new(
            slice,
            frame.duration_ms,
            // frame_index isn't tracked here; pass 0 as a placeholder.
            // libwebp's animation decoder doesn't expose a per-frame
            // index distinct from iteration order.
            0,
        )))
    }

    fn render_next_frame_to_sink(
        &mut self,
        stop: Option<&dyn enough::Stop>,
        sink: &mut dyn DecodeRowSink,
    ) -> Result<Option<OutputInfo>, At<Error>> {
        let descriptor = self.descriptor;
        let frame = match self.render_next_frame(stop)? {
            Some(f) => f,
            None => return Ok(None),
        };
        let pixels = frame.pixels();
        let w = pixels.width();
        let h = pixels.rows();
        sink.begin(w, h, descriptor)
            .map_err(|e| at!(Error::InvalidInput(format!("sink begin: {e}"))))?;
        let mut dst = sink
            .provide_next_buffer(0, h, w, descriptor)
            .map_err(|e| at!(Error::InvalidInput(format!("sink provide: {e}"))))?;
        let bpp = descriptor.bytes_per_pixel();
        let row_bytes = w as usize * bpp;
        let src_bytes = pixels.as_strided_bytes();
        let src_stride = pixels.stride();
        for y in 0..h as usize {
            let src_row = &src_bytes[y * src_stride..y * src_stride + row_bytes];
            let dst_row = dst.row_mut(y as u32);
            dst_row[..row_bytes].copy_from_slice(src_row);
        }
        sink.finish()
            .map_err(|e| at!(Error::InvalidInput(format!("sink finish: {e}"))))?;
        Ok(Some(OutputInfo::full_decode(w, h, descriptor)))
    }

    fn frame_count(&self) -> Option<u32> {
        Some(self.inner.info().frame_count)
    }

    fn loop_count(&self) -> Option<u32> {
        Some(self.inner.info().loop_count)
    }
}

/// Stub when the `animation` feature is off.
#[cfg(not(feature = "animation"))]
pub struct WebpAnimationFrameDecoder {
    _marker: core::marker::PhantomData<()>,
}

#[cfg(not(feature = "animation"))]
impl zencodec::decode::AnimationFrameDecoder for WebpAnimationFrameDecoder {
    type Error = At<Error>;

    fn wrap_sink_error(_e: zencodec::decode::SinkError) -> At<Error> {
        at!(Error::InvalidConfig(
            "webpx built without `animation` feature".into(),
        ))
    }

    fn info(&self) -> &ImageInfo {
        unreachable!("animation feature not enabled");
    }

    fn render_next_frame(
        &mut self,
        _stop: Option<&dyn enough::Stop>,
    ) -> Result<Option<zencodec::decode::AnimationFrame<'_>>, At<Error>> {
        Err(at!(Error::InvalidConfig(
            "webpx built without `animation` feature".into(),
        )))
    }

    fn render_next_frame_to_sink(
        &mut self,
        _stop: Option<&dyn enough::Stop>,
        _sink: &mut dyn zencodec::decode::DecodeRowSink,
    ) -> Result<Option<OutputInfo>, At<Error>> {
        Err(at!(Error::InvalidConfig(
            "webpx built without `animation` feature".into(),
        )))
    }
}