zenpng 0.1.0

PNG encoding and decoding with zencodec trait integration
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
//! Quantizer backend abstraction for palette generation.
//!
//! Provides a [`Quantizer`] trait with implementations for multiple backends:
//! - [`ZenquantQuantizer`] (feature `quantize`, default) — perceptual quality, metrics, joint optimization
//! - [`ImagequantQuantizer`] (feature `imagequant`) — libimagequant
//! - [`QuantetteQuantizer`] (feature `quantette`) — fast k-means / Wu
//!
//! # Runtime selection
//!
//! All backends implement the same [`Quantizer`] trait, enabling runtime dispatch:
//! ```ignore
//! let quantizer: Box<dyn Quantizer> = match name {
//!     "zenquant" => Box::new(ZenquantQuantizer::default()),
//!     "imagequant" => Box::new(ImagequantQuantizer::default()),
//!     "quantette" => Box::new(QuantetteQuantizer::default()),
//!     _ => return Err(..),
//! };
//! let output = quantizer.quantize_rgba(pixels, width, height)?;
//! ```

use alloc::boxed::Box;
use alloc::format;
use alloc::vec;
use alloc::vec::Vec;

use crate::error::PngError;

/// Output of a single-image quantization.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct QuantizeOutput {
    /// RGBA palette entries (2–256).
    pub palette_rgba: Vec<[u8; 4]>,
    /// Per-pixel palette index (row-major, length = width × height).
    pub indices: Vec<u8>,
    /// MPE quality score (lower = better). Only zenquant provides this.
    pub mpe_score: Option<f32>,
    /// Estimated SSIMULACRA2 score (0–100, higher = better). Only zenquant provides this.
    pub ssim2_estimate: Option<f32>,
    /// Estimated butteraugli distance (lower = better). Only zenquant provides this.
    pub butteraugli_estimate: Option<f32>,
}

/// Output of multi-frame quantization with a shared palette.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct MultiFrameOutput {
    /// Shared RGBA palette across all frames.
    pub palette_rgba: Vec<[u8; 4]>,
    /// Per-frame index buffers (parallel to input frames).
    pub frame_indices: Vec<Vec<u8>>,
    /// Per-frame MPE scores. Only zenquant provides these.
    pub mpe_scores: Vec<Option<f32>>,
    /// Per-frame SSIMULACRA2 estimates. Only zenquant provides these.
    pub ssim2_estimates: Vec<Option<f32>>,
    /// Per-frame butteraugli estimates. Only zenquant provides these.
    pub butteraugli_estimates: Vec<Option<f32>>,
}

/// A color quantizer that reduces RGBA8 images to ≤256 indexed colors.
///
/// Built-in implementations:
/// - [`ZenquantQuantizer`] — perceptual median-cut, quality metrics, APNG temporal consistency
/// - [`ImagequantQuantizer`] — libimagequant, high-quality dithering
/// - [`QuantetteQuantizer`] — fast k-means or Wu quantization
pub trait Quantizer: Send + Sync {
    /// Quantize RGBA8 pixels to a palette + index map.
    ///
    /// `pixels` must contain exactly `width × height` entries in row-major order.
    fn quantize_rgba(
        &self,
        pixels: &[[u8; 4]],
        width: usize,
        height: usize,
    ) -> Result<QuantizeOutput, PngError>;

    /// Quantize multiple frames with a shared palette (for APNG).
    ///
    /// Each frame in `frames` must contain exactly `width × height` RGBA pixels.
    ///
    /// Default implementation concatenates all frames vertically, quantizes as
    /// one image, then splits indices per frame. Backends with native multi-frame
    /// support (zenquant) override this for temporal consistency.
    fn quantize_multi_frame(
        &self,
        frames: &[&[[u8; 4]]],
        width: usize,
        height: usize,
    ) -> Result<MultiFrameOutput, PngError> {
        let pixels_per_frame = width * height;
        let mut concat: Vec<[u8; 4]> = Vec::with_capacity(pixels_per_frame * frames.len());
        for frame in frames {
            if frame.len() < pixels_per_frame {
                return Err(PngError::InvalidInput(format!(
                    "frame has {} pixels, expected {}",
                    frame.len(),
                    pixels_per_frame
                )));
            }
            concat.extend_from_slice(&frame[..pixels_per_frame]);
        }
        let total_height = height * frames.len();
        let result = self.quantize_rgba(&concat, width, total_height)?;
        let expected_indices = concat.len();
        if result.indices.len() < expected_indices {
            return Err(PngError::InvalidInput(format!(
                "quantize_rgba returned {} indices, expected {}",
                result.indices.len(),
                expected_indices
            )));
        }
        let n = frames.len();
        let mut frame_indices = Vec::with_capacity(n);
        for i in 0..n {
            let start = i * pixels_per_frame;
            frame_indices.push(result.indices[start..start + pixels_per_frame].to_vec());
        }
        Ok(MultiFrameOutput {
            palette_rgba: result.palette_rgba,
            frame_indices,
            mpe_scores: vec![None; n],
            ssim2_estimates: vec![None; n],
            butteraugli_estimates: vec![None; n],
        })
    }

    /// Return a version of this quantizer with quality metric computation enabled.
    ///
    /// Called by [`encode_auto`](crate::encode_auto) and [`encode_apng_auto`](crate::encode_apng_auto)
    /// when the quality gate requires metrics (`MaxMpe`, `MinSsim2`).
    ///
    /// Backends that support quality metrics (zenquant) should return a copy
    /// with metrics enabled. Returns `None` if not supported (default).
    fn with_quality_metrics(&self) -> Option<Box<dyn Quantizer>> {
        None
    }

    /// Backend name for diagnostics and logging.
    fn name(&self) -> &str;
}

/// Create a default quantizer (zenquant if available, else first enabled backend).
///
/// Quality metrics are enabled for zenquant (needed for [`QualityGate::MaxMpe`] / [`MinSsim2`]).
#[cfg(any(feature = "quantize", feature = "imagequant", feature = "quantette"))]
pub fn default_quantizer() -> Box<dyn Quantizer> {
    #[cfg(feature = "quantize")]
    {
        Box::new(ZenquantQuantizer::new().with_compute_quality_metric(true))
    }
    #[cfg(all(not(feature = "quantize"), feature = "imagequant"))]
    {
        Box::new(ImagequantQuantizer::default())
    }
    #[cfg(all(
        not(feature = "quantize"),
        not(feature = "imagequant"),
        feature = "quantette"
    ))]
    {
        Box::new(QuantetteQuantizer::default())
    }
}

/// Create a quantizer by name at runtime.
///
/// Returns an error if the named backend is not enabled via feature flags.
/// Valid names: `"zenquant"`, `"imagequant"`, `"quantette"`.
pub fn quantizer_by_name(name: &str) -> Result<Box<dyn Quantizer>, PngError> {
    match name {
        #[cfg(feature = "quantize")]
        "zenquant" => Ok(Box::new(
            ZenquantQuantizer::new().with_compute_quality_metric(true),
        )),
        #[cfg(feature = "imagequant")]
        "imagequant" => Ok(Box::new(ImagequantQuantizer::default())),
        #[cfg(feature = "quantette")]
        "quantette" => Ok(Box::new(QuantetteQuantizer::default())),
        _ => Err(PngError::InvalidInput(format!(
            "unknown or disabled quantizer backend: {name:?}. Available: {:?}",
            available_backends()
        ))),
    }
}

/// List available quantizer backend names (based on enabled features).
pub fn available_backends() -> &'static [&'static str] {
    &[
        #[cfg(feature = "quantize")]
        "zenquant",
        #[cfg(feature = "imagequant")]
        "imagequant",
        #[cfg(feature = "quantette")]
        "quantette",
    ]
}

// ── Zenquant backend ──────────────────────────────────────────────

#[cfg(feature = "quantize")]
pub use self::zenquant_backend::ZenquantQuantizer;

#[cfg(feature = "quantize")]
mod zenquant_backend {
    use super::*;

    /// zenquant quantizer — perceptual median-cut with dithering and quality metrics.
    ///
    /// Wraps a [`zenquant::QuantizeConfig`] with builder methods for common settings.
    /// For full control, use [`config_mut()`](Self::config_mut) to access the inner config.
    ///
    /// Supports joint optimization (feature `joint`) and native multi-frame APNG
    /// palette building with temporal consistency.
    #[derive(Debug, Clone)]
    pub struct ZenquantQuantizer {
        config: zenquant::QuantizeConfig,
    }

    impl Default for ZenquantQuantizer {
        fn default() -> Self {
            Self::new()
        }
    }

    impl ZenquantQuantizer {
        /// Create with default PNG-tuned settings.
        #[must_use]
        pub fn new() -> Self {
            Self {
                config: zenquant::QuantizeConfig::new(zenquant::OutputFormat::Png),
            }
        }

        /// Create for a specific output format (Png, Gif, PngJoint).
        #[must_use]
        pub fn with_format(format: zenquant::OutputFormat) -> Self {
            Self {
                config: zenquant::QuantizeConfig::new(format),
            }
        }

        /// Create from an existing zenquant config (for full control).
        #[must_use]
        pub fn from_config(config: zenquant::QuantizeConfig) -> Self {
            Self { config }
        }

        /// Set quality preset (Fast, Balanced, Best).
        #[must_use]
        pub fn with_quality(mut self, quality: zenquant::Quality) -> Self {
            self.config = self.config.with_quality(quality);
            self
        }

        /// Set maximum palette colors (2–256).
        #[must_use]
        pub fn with_max_colors(mut self, n: u16) -> Self {
            self.config = self.config.with_max_colors(n.into());
            self
        }

        /// Enable quality metric computation (MPE, SSIM2, butteraugli estimates).
        ///
        /// Required for [`QualityGate::MaxMpe`] and [`QualityGate::MinSsim2`].
        #[must_use]
        pub fn with_compute_quality_metric(mut self, compute: bool) -> Self {
            self.config = self.config.with_compute_quality_metric(compute);
            self
        }

        /// Access the underlying zenquant config.
        pub fn config(&self) -> &zenquant::QuantizeConfig {
            &self.config
        }

        /// Mutably access the underlying zenquant config for fine-tuning.
        pub fn config_mut(&mut self) -> &mut zenquant::QuantizeConfig {
            &mut self.config
        }
    }

    impl Quantizer for ZenquantQuantizer {
        fn quantize_rgba(
            &self,
            pixels: &[[u8; 4]],
            width: usize,
            height: usize,
        ) -> Result<QuantizeOutput, PngError> {
            let rgba: &[zenquant::RGBA<u8>] = bytemuck::cast_slice(pixels);
            let result = zenquant::quantize_rgba(rgba, width, height, &self.config)?;
            Ok(QuantizeOutput {
                palette_rgba: result.palette_rgba().to_vec(),
                indices: result.indices().to_vec(),
                mpe_score: result.mpe_score(),
                ssim2_estimate: result.ssimulacra2_estimate(),
                butteraugli_estimate: result.butteraugli_estimate(),
            })
        }

        fn quantize_multi_frame(
            &self,
            frames: &[&[[u8; 4]]],
            width: usize,
            height: usize,
        ) -> Result<MultiFrameOutput, PngError> {
            use imgref::ImgRef;

            let pixels_per_frame = width * height;
            let mut frame_refs: Vec<ImgRef<'_, zenquant::RGBA<u8>>> =
                Vec::with_capacity(frames.len());
            for (i, f) in frames.iter().enumerate() {
                if f.len() < pixels_per_frame {
                    return Err(PngError::InvalidInput(format!(
                        "frame {} has {} pixels, expected {}",
                        i,
                        f.len(),
                        pixels_per_frame
                    )));
                }
                let pixels: &[zenquant::RGBA<u8>] = bytemuck::cast_slice(&f[..pixels_per_frame]);
                frame_refs.push(ImgRef::new(pixels, width, height));
            }

            let palette_result = zenquant::build_palette_rgba(&frame_refs, &self.config)?;
            let palette_rgba = palette_result.palette_rgba().to_vec();

            let mut frame_indices = Vec::with_capacity(frames.len());
            let mut mpe_scores = Vec::with_capacity(frames.len());
            let mut ssim2_estimates = Vec::with_capacity(frames.len());
            let mut butteraugli_estimates = Vec::with_capacity(frames.len());
            let mut prev_indices: Option<Vec<u8>> = None;

            for frame_ref in &frame_refs {
                let (frame_buf, fw, fh) = frame_ref.to_contiguous_buf();
                let remap_result = if let Some(prev) = &prev_indices {
                    palette_result.remap_rgba_with_prev(
                        frame_buf.as_ref(),
                        fw,
                        fh,
                        &self.config,
                        prev,
                    )?
                } else {
                    palette_result.remap_rgba(frame_buf.as_ref(), fw, fh, &self.config)?
                };

                mpe_scores.push(remap_result.mpe_score());
                ssim2_estimates.push(remap_result.ssimulacra2_estimate());
                butteraugli_estimates.push(remap_result.butteraugli_estimate());
                let indices = remap_result.indices().to_vec();
                prev_indices = Some(indices.clone());
                frame_indices.push(indices);
            }

            Ok(MultiFrameOutput {
                palette_rgba,
                frame_indices,
                mpe_scores,
                ssim2_estimates,
                butteraugli_estimates,
            })
        }

        fn with_quality_metrics(&self) -> Option<Box<dyn Quantizer>> {
            Some(Box::new(self.clone().with_compute_quality_metric(true)))
        }

        fn name(&self) -> &str {
            "zenquant"
        }
    }
}

// ── Imagequant backend ────────────────────────────────────────────

#[cfg(feature = "imagequant")]
pub use self::imagequant_backend::ImagequantQuantizer;

#[cfg(feature = "imagequant")]
mod imagequant_backend {
    use super::*;

    /// imagequant quantizer — libimagequant with high-quality dithering.
    ///
    /// Pure Rust port of pngquant's quantization engine.
    #[derive(Debug, Clone)]
    pub struct ImagequantQuantizer {
        /// Processing speed (1 = slowest/best, 10 = fastest). Default: 4.
        pub speed: i32,
        /// Maximum quality (0–100). Default: 100.
        pub max_quality: u8,
        /// Dithering level (0.0 = none, 1.0 = full). Default: 1.0.
        pub dithering: f32,
        /// Maximum palette colors (2–256). Default: 256.
        pub max_colors: u16,
    }

    impl Default for ImagequantQuantizer {
        fn default() -> Self {
            Self {
                speed: 4,
                max_quality: 100,
                dithering: 1.0,
                max_colors: 256,
            }
        }
    }

    impl ImagequantQuantizer {
        #[must_use]
        pub fn with_speed(mut self, speed: i32) -> Self {
            self.speed = speed;
            self
        }

        #[must_use]
        pub fn with_max_quality(mut self, q: u8) -> Self {
            self.max_quality = q;
            self
        }

        #[must_use]
        pub fn with_dithering(mut self, d: f32) -> Self {
            self.dithering = d;
            self
        }

        #[must_use]
        pub fn with_max_colors(mut self, n: u16) -> Self {
            self.max_colors = n;
            self
        }
    }

    impl Quantizer for ImagequantQuantizer {
        fn quantize_rgba(
            &self,
            pixels: &[[u8; 4]],
            width: usize,
            height: usize,
        ) -> Result<QuantizeOutput, PngError> {
            let mut attr = imagequant::Attributes::new();
            attr.set_quality(0, self.max_quality)
                .map_err(|e| PngError::InvalidInput(format!("imagequant quality: {e}")))?;
            attr.set_speed(self.speed)
                .map_err(|e| PngError::InvalidInput(format!("imagequant speed: {e}")))?;
            attr.set_max_colors(self.max_colors as u32)
                .map_err(|e| PngError::InvalidInput(format!("imagequant max_colors: {e}")))?;

            let rgba_pixels: Vec<imagequant::RGBA> = pixels
                .iter()
                .map(|p| imagequant::RGBA::new(p[0], p[1], p[2], p[3]))
                .collect();

            let mut img = attr
                .new_image(rgba_pixels, width, height, 0.0)
                .map_err(|e| PngError::InvalidInput(format!("imagequant image: {e}")))?;
            let mut result = attr
                .quantize(&mut img)
                .map_err(|e| PngError::InvalidInput(format!("imagequant quantize: {e}")))?;
            result
                .set_dithering_level(self.dithering)
                .map_err(|e| PngError::InvalidInput(format!("imagequant dithering: {e}")))?;

            let (palette, indices) = result
                .remapped(&mut img)
                .map_err(|e| PngError::InvalidInput(format!("imagequant remap: {e}")))?;

            let palette_rgba: Vec<[u8; 4]> = palette.iter().map(|c| [c.r, c.g, c.b, c.a]).collect();

            Ok(QuantizeOutput {
                palette_rgba,
                indices,
                mpe_score: None,
                ssim2_estimate: None,
                butteraugli_estimate: None,
            })
        }

        fn name(&self) -> &str {
            "imagequant"
        }
    }
}

// ── Quantette backend ─────────────────────────────────────────────

#[cfg(feature = "quantette")]
pub use self::quantette_backend::QuantetteQuantizer;

#[cfg(feature = "quantette")]
mod quantette_backend {
    use super::*;

    /// quantette quantizer — fast k-means or Wu quantization.
    ///
    /// Operates on sRGB colors only. Images with transparent pixels (alpha < 255)
    /// will have transparency ignored — all palette entries get alpha = 255.
    /// Use zenquant or imagequant for images requiring alpha transparency.
    #[derive(Debug, Clone)]
    pub struct QuantetteQuantizer {
        /// Use k-means refinement (true) or Wu's method (false). Default: true.
        pub kmeans: bool,
        /// Enable Floyd-Steinberg dithering. Default: true.
        pub dithering: bool,
        /// Maximum palette colors (2–256). Default: 256.
        pub max_colors: u16,
        /// K-means sampling factor. Default: 1.0.
        pub sampling_factor: f32,
    }

    impl Default for QuantetteQuantizer {
        fn default() -> Self {
            Self {
                kmeans: true,
                dithering: true,
                max_colors: 256,
                sampling_factor: 1.0,
            }
        }
    }

    impl QuantetteQuantizer {
        #[must_use]
        pub fn with_kmeans(mut self, kmeans: bool) -> Self {
            self.kmeans = kmeans;
            self
        }

        #[must_use]
        pub fn with_dithering(mut self, dithering: bool) -> Self {
            self.dithering = dithering;
            self
        }

        #[must_use]
        pub fn with_max_colors(mut self, n: u16) -> Self {
            self.max_colors = n;
            self
        }

        #[must_use]
        pub fn with_sampling_factor(mut self, f: f32) -> Self {
            self.sampling_factor = f;
            self
        }
    }

    impl Quantizer for QuantetteQuantizer {
        fn quantize_rgba(
            &self,
            pixels: &[[u8; 4]],
            width: usize,
            height: usize,
        ) -> Result<QuantizeOutput, PngError> {
            use quantette::deps::palette::Srgb;
            use quantette::{ImageBuf, Pipeline, QuantizeMethod};

            // quantette works with RGB only — strip alpha
            let srgb_pixels: Vec<Srgb<u8>> =
                pixels.iter().map(|p| Srgb::new(p[0], p[1], p[2])).collect();

            let image = ImageBuf::new(width as u32, height as u32, srgb_pixels)
                .map_err(|e| PngError::InvalidInput(format!("quantette image: {e}")))?;

            let method = if self.kmeans {
                use quantette::kmeans::KmeansOptions;
                QuantizeMethod::Kmeans(KmeansOptions::new().sampling_factor(self.sampling_factor))
            } else {
                QuantizeMethod::Wu
            };

            let palette_size = self
                .max_colors
                .try_into()
                .map_err(|_| PngError::InvalidInput("max_colors out of range".into()))?;

            let mut pipeline = Pipeline::new()
                .palette_size(palette_size)
                .quantize_method(method);

            if self.dithering {
                use quantette::dither::FloydSteinberg;
                pipeline = pipeline.ditherer(Some(FloydSteinberg::new()));
            }

            let indexed = pipeline
                .input_image(image.as_ref())
                .output_srgb8_indexed_image();

            // Add alpha=255 to all palette entries (quantette doesn't handle alpha)
            let palette_rgba: Vec<[u8; 4]> = indexed
                .palette()
                .iter()
                .map(|c| [c.red, c.green, c.blue, 255])
                .collect();
            let indices = indexed.indices().to_vec();

            Ok(QuantizeOutput {
                palette_rgba,
                indices,
                mpe_score: None,
                ssim2_estimate: None,
                butteraugli_estimate: None,
            })
        }

        fn name(&self) -> &str {
            "quantette"
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── available_backends / quantizer_by_name ──────────────────────

    #[test]
    #[cfg(feature = "quantize")]
    fn available_backends_includes_zenquant() {
        let backends = available_backends();
        assert!(
            backends.contains(&"zenquant"),
            "zenquant should be available"
        );
    }

    #[test]
    #[cfg(feature = "quantize")]
    fn quantizer_by_name_zenquant() {
        let q = quantizer_by_name("zenquant").unwrap();
        assert_eq!(q.name(), "zenquant");
    }

    #[test]
    fn quantizer_by_name_unknown_fails() {
        let result = quantizer_by_name("nonexistent");
        assert!(result.is_err());
        let err = match result {
            Err(e) => e.to_string(),
            Ok(_) => panic!("expected error"),
        };
        assert!(err.contains("unknown or disabled"), "got: {err}");
    }

    // ── default_quantizer ──────────────────────────────────────────

    #[cfg(any(feature = "quantize", feature = "imagequant", feature = "quantette"))]
    #[test]
    fn default_quantizer_works() {
        let q = default_quantizer();
        assert!(!q.name().is_empty());
    }

    // ── Quantizer trait: with_quality_metrics default impl ──────────

    struct DummyQuantizer;
    impl Quantizer for DummyQuantizer {
        fn quantize_rgba(
            &self,
            pixels: &[[u8; 4]],
            _width: usize,
            _height: usize,
        ) -> Result<QuantizeOutput, crate::error::PngError> {
            Ok(QuantizeOutput {
                palette_rgba: vec![[0, 0, 0, 255], [255, 255, 255, 255]],
                indices: vec![0; pixels.len()],
                mpe_score: None,
                ssim2_estimate: None,
                butteraugli_estimate: None,
            })
        }
        fn name(&self) -> &str {
            "dummy"
        }
    }

    #[test]
    fn default_with_quality_metrics_returns_none() {
        let q = DummyQuantizer;
        assert!(q.with_quality_metrics().is_none());
    }

    #[test]
    fn default_quantize_multi_frame_splits_correctly() {
        let q = DummyQuantizer;
        let frame0: Vec<[u8; 4]> = vec![[255, 0, 0, 255]; 4];
        let frame1: Vec<[u8; 4]> = vec![[0, 255, 0, 255]; 4];
        let frames: Vec<&[[u8; 4]]> = vec![&frame0, &frame1];

        let result = q.quantize_multi_frame(&frames, 2, 2).unwrap();
        assert_eq!(result.frame_indices.len(), 2);
        assert_eq!(result.frame_indices[0].len(), 4);
        assert_eq!(result.frame_indices[1].len(), 4);
        assert_eq!(result.palette_rgba.len(), 2);
        assert_eq!(result.mpe_scores, vec![None, None]);
        assert_eq!(result.ssim2_estimates, vec![None, None]);
    }

    #[test]
    fn default_quantize_multi_frame_rejects_short_frame() {
        let q = DummyQuantizer;
        let frame0: Vec<[u8; 4]> = vec![[255, 0, 0, 255]; 2]; // too short for 2x2
        let frames: Vec<&[[u8; 4]]> = vec![&frame0];
        let result = q.quantize_multi_frame(&frames, 2, 2);
        assert!(result.is_err());
    }

    // ── ZenquantQuantizer ──────────────────────────────────────────

    #[cfg(feature = "quantize")]
    #[test]
    fn zenquant_basic_quantize() {
        let q = ZenquantQuantizer::new();
        assert_eq!(q.name(), "zenquant");
        let pixels: Vec<[u8; 4]> = (0..64)
            .map(|i| [(i * 4) as u8, (i * 3) as u8, (i * 2) as u8, 255])
            .collect();
        let result = q.quantize_rgba(&pixels, 8, 8).unwrap();
        assert!(!result.palette_rgba.is_empty());
        assert!(result.palette_rgba.len() <= 256);
        assert_eq!(result.indices.len(), 64);
    }

    #[cfg(feature = "quantize")]
    #[test]
    fn zenquant_with_quality_metrics() {
        let q = ZenquantQuantizer::new();
        let q2 = q.with_quality_metrics();
        assert!(q2.is_some(), "zenquant should support quality metrics");
        let q2 = q2.unwrap();
        assert_eq!(q2.name(), "zenquant");
    }

    #[cfg(feature = "quantize")]
    #[test]
    fn zenquant_multi_frame() {
        let q = ZenquantQuantizer::new();
        let frame0: Vec<[u8; 4]> = vec![[255, 0, 0, 255]; 16];
        let frame1: Vec<[u8; 4]> = vec![[0, 255, 0, 255]; 16];
        let frames: Vec<&[[u8; 4]]> = vec![&frame0, &frame1];
        let result = q.quantize_multi_frame(&frames, 4, 4).unwrap();
        assert_eq!(result.frame_indices.len(), 2);
        assert_eq!(result.frame_indices[0].len(), 16);
    }

    #[cfg(feature = "quantize")]
    #[test]
    fn zenquant_builder_methods() {
        let q = ZenquantQuantizer::new()
            .with_max_colors(64)
            .with_compute_quality_metric(true);
        let pixels: Vec<[u8; 4]> = (0..16).map(|i| [(i * 16) as u8, 0, 0, 255]).collect();
        let result = q.quantize_rgba(&pixels, 4, 4).unwrap();
        assert!(result.palette_rgba.len() <= 64);
        // Quality metrics should be present
        assert!(result.mpe_score.is_some());
    }

    #[cfg(feature = "quantize")]
    #[test]
    fn zenquant_config_access() {
        let mut q = ZenquantQuantizer::new();
        let _config = q.config();
        let _config_mut = q.config_mut();
    }
}