Skip to main content

skia_rs_codec/
codec.rs

1//! Codec trait and format-specific implementations.
2//!
3//! Codecs handle encoding and decoding of images in various formats.
4
5use crate::Image;
6use std::io::{Read, Write};
7use thiserror::Error;
8
9/// Errors that can occur during codec operations.
10#[derive(Debug, Error)]
11pub enum CodecError {
12    /// I/O error.
13    #[error("I/O error: {0}")]
14    Io(#[from] std::io::Error),
15    /// Invalid or corrupt data.
16    #[error("invalid data: {0}")]
17    InvalidData(String),
18    /// Unsupported format or feature.
19    #[error("unsupported: {0}")]
20    Unsupported(String),
21    /// Encoding error.
22    #[error("encoding error: {0}")]
23    EncodingError(String),
24    /// Decoding error.
25    #[error("decoding error: {0}")]
26    DecodingError(String),
27}
28
29/// Result type for codec operations.
30pub type CodecResult<T> = Result<T, CodecError>;
31
32/// Largest per-dimension pixel extent accepted from untrusted encoded
33/// data, matching `SkCodec`'s guard against absurd sizes.
34const MAX_DIM: usize = 1 << 24;
35/// Largest total decoded-canvas byte size accepted from untrusted encoded
36/// data. A format's individual dimensions can each be within [`MAX_DIM`]
37/// yet still multiply out to tens of gigabytes, so this bounds the
38/// product as well.
39const MAX_CANVAS_BYTES: usize = 1 << 28; // 256 MiB
40
41/// Detected image format.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43pub enum ImageFormat {
44    /// PNG format.
45    Png,
46    /// JPEG format.
47    Jpeg,
48    /// GIF format.
49    Gif,
50    /// WebP format.
51    WebP,
52    /// BMP format.
53    Bmp,
54    /// ICO format.
55    Ico,
56    /// WBMP format (Wireless Bitmap).
57    Wbmp,
58    /// AVIF format (AV1 Image File Format).
59    Avif,
60    /// Camera RAW format.
61    Raw,
62    /// Unknown format.
63    Unknown,
64}
65
66impl ImageFormat {
67    /// Detect format from magic bytes.
68    #[must_use]
69    pub fn from_magic(data: &[u8]) -> Self {
70        if data.len() < 8 {
71            return Self::Unknown;
72        }
73
74        // PNG: 89 50 4E 47 0D 0A 1A 0A
75        if data.starts_with(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) {
76            return Self::Png;
77        }
78
79        // JPEG: FF D8 FF
80        if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
81            return Self::Jpeg;
82        }
83
84        // GIF: GIF87a or GIF89a
85        if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
86            return Self::Gif;
87        }
88
89        // WebP: RIFF....WEBP
90        if data.len() >= 12 && data.starts_with(b"RIFF") && &data[8..12] == b"WEBP" {
91            return Self::WebP;
92        }
93
94        // BMP: BM
95        if data.starts_with(b"BM") {
96            return Self::Bmp;
97        }
98
99        // ICO: 00 00 01 00
100        if data.starts_with(&[0x00, 0x00, 0x01, 0x00]) {
101            return Self::Ico;
102        }
103
104        // AVIF: ftyp box with 'avif' or 'avis' brand
105        // HEIF/AVIF files start with ftyp box: size (4 bytes) + "ftyp" + brand
106        if data.len() >= 12 && &data[4..8] == b"ftyp" {
107            // Check for AVIF brands
108            if &data[8..12] == b"avif" || &data[8..12] == b"avis" || &data[8..12] == b"mif1" {
109                return Self::Avif;
110            }
111        }
112
113        // WBMP: Type 0, FixHeaderField 0, followed by width/height encoded
114        // as WBMP multibyte integers (bit 7 = "more bytes follow"). Both
115        // dimensions must be non-zero for a valid WBMP. The previous check
116        // only accepted single-byte (< 128) dimensions and rejected any
117        // image wider or taller than 127 pixels.
118        if data.len() >= 4 && data[0] == 0 && data[1] == 0 {
119            let mut offset = 2;
120            if let (Some(width), Some(height)) = (
121                read_wbmp_int(data, &mut offset),
122                read_wbmp_int(data, &mut offset),
123            ) {
124                if width > 0 && height > 0 {
125                    return Self::Wbmp;
126                }
127            }
128        }
129
130        Self::Unknown
131    }
132
133    /// Get the typical file extension for this format.
134    #[must_use]
135    pub const fn extension(&self) -> &'static str {
136        match self {
137            Self::Png => "png",
138            Self::Jpeg => "jpg",
139            Self::Gif => "gif",
140            Self::WebP => "webp",
141            Self::Bmp => "bmp",
142            Self::Ico => "ico",
143            Self::Wbmp => "wbmp",
144            Self::Avif => "avif",
145            Self::Raw => "raw",
146            Self::Unknown => "",
147        }
148    }
149
150    /// Get the MIME type for this format.
151    #[must_use]
152    pub const fn mime_type(&self) -> &'static str {
153        match self {
154            Self::Png => "image/png",
155            Self::Jpeg => "image/jpeg",
156            Self::Gif => "image/gif",
157            Self::WebP => "image/webp",
158            Self::Bmp => "image/bmp",
159            Self::Ico => "image/x-icon",
160            Self::Wbmp => "image/vnd.wap.wbmp",
161            Self::Avif => "image/avif",
162            Self::Raw => "image/x-raw",
163            Self::Unknown => "application/octet-stream",
164        }
165    }
166}
167
168/// A codec that can decode images.
169pub trait ImageDecoder: Send + Sync {
170    /// Decode an image from a reader.
171    ///
172    /// # Errors
173    /// Returns [`CodecError`] if the stream cannot be read or the data is
174    /// not valid for this decoder's format.
175    fn decode<R: Read>(&self, reader: R) -> CodecResult<Image>;
176
177    /// Decode an image from bytes.
178    ///
179    /// # Errors
180    /// Returns [`CodecError`] if `data` is not valid for this decoder's
181    /// format.
182    fn decode_bytes(&self, data: &[u8]) -> CodecResult<Image> {
183        self.decode(std::io::Cursor::new(data))
184    }
185
186    /// Get the format this decoder handles.
187    fn format(&self) -> ImageFormat;
188
189    /// Check if this decoder can handle the given data.
190    fn can_decode(&self, data: &[u8]) -> bool {
191        ImageFormat::from_magic(data) == self.format()
192    }
193}
194
195/// A codec that can encode images.
196pub trait ImageEncoder: Send + Sync {
197    /// Encode an image to a writer.
198    ///
199    /// # Errors
200    /// Returns [`CodecError`] if the image cannot be encoded (e.g.
201    /// unsupported color type) or the writer fails.
202    fn encode<W: Write>(&self, image: &Image, writer: W) -> CodecResult<()>;
203
204    /// Encode an image to bytes.
205    ///
206    /// # Errors
207    /// Returns [`CodecError`] if the image cannot be encoded.
208    fn encode_bytes(&self, image: &Image) -> CodecResult<Vec<u8>> {
209        let mut buf = Vec::new();
210        self.encode(image, &mut buf)?;
211        Ok(buf)
212    }
213
214    /// Get the format this encoder produces.
215    fn format(&self) -> ImageFormat;
216}
217
218/// Quality setting for lossy encoders.
219#[derive(Debug, Clone, Copy)]
220pub struct EncoderQuality(u8);
221
222impl EncoderQuality {
223    /// Create a quality setting (0-100).
224    #[must_use]
225    pub fn new(quality: u8) -> Self {
226        Self(quality.min(100))
227    }
228
229    /// Get the quality value.
230    #[must_use]
231    pub const fn value(&self) -> u8 {
232        self.0
233    }
234
235    /// Default quality (80).
236    pub const DEFAULT: Self = Self(80);
237
238    /// High quality (95).
239    pub const HIGH: Self = Self(95);
240
241    /// Low quality (50).
242    pub const LOW: Self = Self(50);
243}
244
245impl Default for EncoderQuality {
246    fn default() -> Self {
247        Self::DEFAULT
248    }
249}
250
251/// Unpremultiply an interleaved 8-bit-per-channel buffer in place when the
252/// source image carries premultiplied pixels.
253///
254/// Image encoders must store **straight** (unpremultiplied) alpha: the PNG
255/// spec (11.2.3), BMP V3+ alpha, and WebP all define pixel samples as
256/// non-premultiplied, and JPEG discards alpha entirely so its RGB must be the
257/// unpremultiplied color. Canvas-backed images now report
258/// [`skia_rs_core::AlphaType::Premul`], so encoders call this before writing.
259///
260/// Alpha lives at byte index 3 of every 4-byte pixel in both RGBA and BGRA
261/// layouts, so this is safe to run on either ordering.
262fn unpremultiply_for_encode(image: &Image, buf: &mut [u8]) {
263    if image.alpha_type() == skia_rs_core::AlphaType::Premul {
264        skia_rs_core::unpremultiply_in_place(buf);
265    }
266}
267
268// =============================================================================
269// Simple PNG Codec (stub - would use png crate for real implementation)
270// =============================================================================
271
272/// PNG decoder.
273#[derive(Debug, Default)]
274pub struct PngDecoder;
275
276impl PngDecoder {
277    /// Create a new PNG decoder.
278    #[must_use]
279    pub const fn new() -> Self {
280        Self
281    }
282}
283
284impl ImageDecoder for PngDecoder {
285    #[cfg(feature = "png")]
286    fn decode<R: Read>(&self, reader: R) -> CodecResult<Image> {
287        let mut decoder = png::Decoder::new(reader);
288        // The `png` crate defaults to `Transformations::IDENTITY`, which
289        // hands back raw palette indices for PNG-8 and 16-bit-per-channel
290        // samples for deep images — neither of which our RGBA8 pipeline can
291        // consume. Enable EXPAND | STRIP_16 (the crate's
292        // `normalize_to_color8`) so paletted images expand to RGB(A),
293        // sub-8-bit grayscale expands to 8-bit, tRNS chunks expand to an
294        // alpha channel, and 16-bit samples are stripped to 8-bit. This
295        // matches SkPngCodec, which always decodes to an 8-bit destination.
296        decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
297        let mut png_reader = decoder
298            .read_info()
299            .map_err(|e| CodecError::DecodingError(e.to_string()))?;
300
301        // Pull the iCCP profile bytes out of the PNG info before calling
302        // next_frame (next_frame borrows the reader mutably). The `png`
303        // crate stores the raw profile bytes in `Info::icc_profile`; we
304        // feed them to `IccProfile::from_bytes` to build a real
305        // ColorSpace, falling back to None if parsing fails.
306        let icc_color_space = png_reader
307            .info()
308            .icc_profile
309            .as_ref()
310            .and_then(|bytes| skia_rs_core::IccProfile::from_bytes(bytes))
311            .map(|profile| profile.color_space().clone());
312
313        let mut buf = vec![0; png_reader.output_buffer_size()];
314        let info = png_reader
315            .next_frame(&mut buf)
316            .map_err(|e| CodecError::DecodingError(e.to_string()))?;
317
318        let width = i32::try_from(info.width)
319            .map_err(|_| CodecError::InvalidData("PNG width exceeds i32 range".into()))?;
320        let height = i32::try_from(info.height)
321            .map_err(|_| CodecError::InvalidData("PNG height exceeds i32 range".into()))?;
322        let width_usize = usize::try_from(info.width).unwrap_or(0);
323        let height_usize = usize::try_from(info.height).unwrap_or(0);
324
325        // Convert to RGBA if necessary
326        let pixels = match info.color_type {
327            png::ColorType::Rgba => buf[..info.buffer_size()].to_vec(),
328            png::ColorType::Rgb => {
329                let rgb = &buf[..info.buffer_size()];
330                let mut rgba = Vec::with_capacity(width_usize * height_usize * 4);
331                for chunk in rgb.chunks(3) {
332                    rgba.push(chunk[0]);
333                    rgba.push(chunk[1]);
334                    rgba.push(chunk[2]);
335                    rgba.push(255);
336                }
337                rgba
338            }
339            png::ColorType::GrayscaleAlpha => {
340                let ga = &buf[..info.buffer_size()];
341                let mut rgba = Vec::with_capacity(width_usize * height_usize * 4);
342                for chunk in ga.chunks(2) {
343                    rgba.push(chunk[0]);
344                    rgba.push(chunk[0]);
345                    rgba.push(chunk[0]);
346                    rgba.push(chunk[1]);
347                }
348                rgba
349            }
350            png::ColorType::Grayscale => {
351                let gray = &buf[..info.buffer_size()];
352                let mut rgba = Vec::with_capacity(width_usize * height_usize * 4);
353                for &g in gray {
354                    rgba.push(g);
355                    rgba.push(g);
356                    rgba.push(g);
357                    rgba.push(255);
358                }
359                rgba
360            }
361            png::ColorType::Indexed => {
362                return Err(CodecError::Unsupported("Unsupported PNG color type".into()));
363            }
364        };
365
366        let mut info = crate::ImageInfo::new(
367            width,
368            height,
369            skia_rs_core::ColorType::Rgba8888,
370            skia_rs_core::AlphaType::Unpremul,
371        );
372        info.color_space = icc_color_space;
373
374        Image::from_raster_data_owned(info, pixels, width_usize * 4)
375            .ok_or_else(|| CodecError::DecodingError("Failed to create image".into()))
376    }
377
378    #[cfg(not(feature = "png"))]
379    fn decode<R: Read>(&self, _reader: R) -> CodecResult<Image> {
380        Err(CodecError::Unsupported(
381            "PNG decoding requires the 'png' feature".into(),
382        ))
383    }
384
385    fn format(&self) -> ImageFormat {
386        ImageFormat::Png
387    }
388}
389
390/// PNG encoder.
391#[derive(Debug, Default)]
392pub struct PngEncoder;
393
394impl PngEncoder {
395    /// Create a new PNG encoder.
396    #[must_use]
397    pub const fn new() -> Self {
398        Self
399    }
400}
401
402impl ImageEncoder for PngEncoder {
403    #[cfg(feature = "png")]
404    fn encode<W: Write>(&self, image: &Image, writer: W) -> CodecResult<()> {
405        let mut encoder = png::Encoder::new(
406            writer,
407            u32::try_from(image.width()).unwrap_or(0),
408            u32::try_from(image.height()).unwrap_or(0),
409        );
410        encoder.set_color(png::ColorType::Rgba);
411        encoder.set_depth(png::BitDepth::Eight);
412
413        let mut png_writer = encoder
414            .write_header()
415            .map_err(|e| CodecError::EncodingError(e.to_string()))?;
416
417        let pixels = image
418            .peek_pixels()
419            .ok_or_else(|| CodecError::EncodingError("Cannot access pixels".into()))?;
420
421        // Convert to RGBA if necessary based on color type
422        let mut rgba_data = match image.color_type() {
423            skia_rs_core::ColorType::Rgba8888 => pixels.to_vec(),
424            skia_rs_core::ColorType::Bgra8888 => {
425                let mut rgba = Vec::with_capacity(pixels.len());
426                for chunk in pixels.chunks(4) {
427                    rgba.push(chunk[2]); // R
428                    rgba.push(chunk[1]); // G
429                    rgba.push(chunk[0]); // B
430                    rgba.push(chunk[3]); // A
431                }
432                rgba
433            }
434            _ => {
435                return Err(CodecError::Unsupported(
436                    "Unsupported color type for PNG encoding".into(),
437                ));
438            }
439        };
440
441        // PNG stores straight alpha; unpremultiply premultiplied input.
442        unpremultiply_for_encode(image, &mut rgba_data);
443
444        png_writer
445            .write_image_data(&rgba_data)
446            .map_err(|e| CodecError::EncodingError(e.to_string()))?;
447
448        Ok(())
449    }
450
451    #[cfg(not(feature = "png"))]
452    fn encode<W: Write>(&self, _image: &Image, _writer: W) -> CodecResult<()> {
453        Err(CodecError::Unsupported(
454            "PNG encoding requires the 'png' feature".into(),
455        ))
456    }
457
458    fn format(&self) -> ImageFormat {
459        ImageFormat::Png
460    }
461}
462
463// =============================================================================
464// JPEG Codec (stub)
465// =============================================================================
466
467/// JPEG decoder.
468#[derive(Debug, Default)]
469pub struct JpegDecoder;
470
471impl JpegDecoder {
472    /// Create a new JPEG decoder.
473    #[must_use]
474    pub const fn new() -> Self {
475        Self
476    }
477}
478
479impl ImageDecoder for JpegDecoder {
480    #[cfg(feature = "jpeg")]
481    fn decode<R: Read>(&self, reader: R) -> CodecResult<Image> {
482        let mut decoder = jpeg_decoder::Decoder::new(reader);
483        let pixels = decoder
484            .decode()
485            .map_err(|e| CodecError::DecodingError(e.to_string()))?;
486        let info = decoder
487            .info()
488            .ok_or_else(|| CodecError::DecodingError("No image info".into()))?;
489
490        // JPEG ICC profiles arrive via APP2 markers; jpeg-decoder
491        // re-assembles them and exposes a single contiguous byte slice.
492        // Parse into a ColorSpace if present and well-formed.
493        let icc_color_space = decoder
494            .icc_profile()
495            .and_then(|bytes| skia_rs_core::IccProfile::from_bytes(&bytes))
496            .map(|profile| profile.color_space().clone());
497
498        let width = i32::from(info.width);
499        let height = i32::from(info.height);
500        let width_usize = usize::from(info.width);
501        let height_usize = usize::from(info.height);
502
503        // Convert to RGBA
504        let rgba = match info.pixel_format {
505            jpeg_decoder::PixelFormat::RGB24 => {
506                let mut rgba = Vec::with_capacity(width_usize * height_usize * 4);
507                for chunk in pixels.chunks(3) {
508                    rgba.push(chunk[0]);
509                    rgba.push(chunk[1]);
510                    rgba.push(chunk[2]);
511                    rgba.push(255);
512                }
513                rgba
514            }
515            jpeg_decoder::PixelFormat::L8 => {
516                let mut rgba = Vec::with_capacity(width_usize * height_usize * 4);
517                for &g in &pixels {
518                    rgba.push(g);
519                    rgba.push(g);
520                    rgba.push(g);
521                    rgba.push(255);
522                }
523                rgba
524            }
525            _ => {
526                return Err(CodecError::Unsupported(
527                    "Unsupported JPEG pixel format".into(),
528                ));
529            }
530        };
531
532        let mut img_info = crate::ImageInfo::new(
533            width,
534            height,
535            skia_rs_core::ColorType::Rgba8888,
536            skia_rs_core::AlphaType::Opaque,
537        );
538        img_info.color_space = icc_color_space;
539
540        Image::from_raster_data_owned(img_info, rgba, width_usize * 4)
541            .ok_or_else(|| CodecError::DecodingError("Failed to create image".into()))
542    }
543
544    #[cfg(not(feature = "jpeg"))]
545    fn decode<R: Read>(&self, _reader: R) -> CodecResult<Image> {
546        Err(CodecError::Unsupported(
547            "JPEG decoding requires the 'jpeg' feature".into(),
548        ))
549    }
550
551    fn format(&self) -> ImageFormat {
552        ImageFormat::Jpeg
553    }
554}
555
556/// JPEG encoder.
557#[derive(Debug)]
558pub struct JpegEncoder {
559    quality: EncoderQuality,
560}
561
562impl JpegEncoder {
563    /// Create a new JPEG encoder with default quality.
564    #[must_use]
565    pub const fn new() -> Self {
566        Self {
567            quality: EncoderQuality::DEFAULT,
568        }
569    }
570
571    /// Create a JPEG encoder with specified quality.
572    #[must_use]
573    pub const fn with_quality(quality: EncoderQuality) -> Self {
574        Self { quality }
575    }
576
577    /// Get the quality setting.
578    #[must_use]
579    pub const fn quality(&self) -> EncoderQuality {
580        self.quality
581    }
582}
583
584impl Default for JpegEncoder {
585    fn default() -> Self {
586        Self::new()
587    }
588}
589
590impl ImageEncoder for JpegEncoder {
591    #[cfg(feature = "jpeg")]
592    fn encode<W: Write>(&self, image: &Image, mut writer: W) -> CodecResult<()> {
593        let pixels = image
594            .peek_pixels()
595            .ok_or_else(|| CodecError::EncodingError("Cannot access pixels".into()))?;
596
597        // JPEG discards alpha, so we must emit the *unpremultiplied* color.
598        // Build an RGBA buffer, unpremultiply if the source is premul, then
599        // drop the alpha channel.
600        let mut rgba = match image.color_type() {
601            skia_rs_core::ColorType::Rgba8888 => pixels.to_vec(),
602            skia_rs_core::ColorType::Bgra8888 => {
603                let mut rgba = Vec::with_capacity(pixels.len());
604                for chunk in pixels.chunks(4) {
605                    rgba.push(chunk[2]); // R
606                    rgba.push(chunk[1]); // G
607                    rgba.push(chunk[0]); // B
608                    rgba.push(chunk[3]); // A
609                }
610                rgba
611            }
612            _ => {
613                return Err(CodecError::Unsupported(
614                    "Unsupported color type for JPEG encoding".into(),
615                ));
616            }
617        };
618        unpremultiply_for_encode(image, &mut rgba);
619        let width_usize = usize::try_from(image.width()).unwrap_or(0);
620        let height_usize = usize::try_from(image.height()).unwrap_or(0);
621        let rgb_capacity = width_usize
622            .checked_mul(height_usize)
623            .and_then(|n| n.checked_mul(3))
624            .ok_or_else(|| CodecError::EncodingError("image dimensions overflow".into()))?;
625        let mut rgb = Vec::with_capacity(rgb_capacity);
626        for chunk in rgba.chunks_exact(4) {
627            rgb.push(chunk[0]);
628            rgb.push(chunk[1]);
629            rgb.push(chunk[2]);
630        }
631
632        let jpeg_width = u16::try_from(image.width())
633            .map_err(|_| CodecError::EncodingError("image width exceeds JPEG limit".into()))?;
634        let jpeg_height = u16::try_from(image.height())
635            .map_err(|_| CodecError::EncodingError("image height exceeds JPEG limit".into()))?;
636        let encoder = jpeg_encoder::Encoder::new(&mut writer, self.quality.value());
637        encoder
638            .encode(&rgb, jpeg_width, jpeg_height, jpeg_encoder::ColorType::Rgb)
639            .map_err(|e| CodecError::EncodingError(e.to_string()))?;
640
641        Ok(())
642    }
643
644    #[cfg(not(feature = "jpeg"))]
645    fn encode<W: Write>(&self, _image: &Image, _writer: W) -> CodecResult<()> {
646        Err(CodecError::Unsupported(
647            "JPEG encoding requires the 'jpeg' feature".into(),
648        ))
649    }
650
651    fn format(&self) -> ImageFormat {
652        ImageFormat::Jpeg
653    }
654}
655
656// =============================================================================
657// GIF Codec
658// =============================================================================
659
660/// GIF decoder.
661#[derive(Debug, Default)]
662pub struct GifDecoder;
663
664impl GifDecoder {
665    /// Create a new GIF decoder.
666    #[must_use]
667    pub const fn new() -> Self {
668        Self
669    }
670
671    /// Decode an animated GIF into all of its frames.
672    ///
673    /// The single-frame [`ImageDecoder::decode`] path returns only the
674    /// first frame — convenient for static GIFs but loses every
675    /// subsequent frame of an animation. `decode_animated` walks the
676    /// full frame stream, preserving per-frame delay, disposal, and
677    /// offset.
678    ///
679    /// Each frame's image is its own [`Image`] sized to the frame's
680    /// local width/height (not the canvas). The `x_offset` / `y_offset`
681    /// fields on [`crate::AnimationFrame`] place the frame inside the
682    /// animation canvas; callers performing playback composite those
683    /// frames onto the canvas according to the frame's
684    /// [`crate::DisposalMethod`] and [`crate::BlendMethod`].
685    ///
686    /// GIF delays arrive in 10ms ticks (`Frame::delay`), which this
687    /// converts to [`std::time::Duration`]. A zero delay is preserved
688    /// as `Duration::ZERO` — downstream renderers typically clamp these
689    /// to a minimum of 20ms to avoid CPU-pegging animations, but that
690    /// policy belongs to the renderer, not the codec.
691    ///
692    /// # Errors
693    /// Returns [`CodecError`] if `data` is not a valid GIF, contains no
694    /// frames, or a frame image cannot be built.
695    #[cfg(feature = "gif")]
696    pub fn decode_animated(&self, data: &[u8]) -> CodecResult<crate::AnimatedImage> {
697        let mut options = gif::DecodeOptions::new();
698        options.set_color_output(gif::ColorOutput::RGBA);
699        let mut decoder = options
700            .read_info(std::io::Cursor::new(data))
701            .map_err(|e| CodecError::DecodingError(e.to_string()))?;
702
703        // Logical-screen (canvas) dimensions. Individual frames may be
704        // smaller and are positioned via their left/top offsets.
705        let canvas_width = i32::from(decoder.width());
706        let canvas_height = i32::from(decoder.height());
707
708        let mut frames = Vec::new();
709        while let Some(frame) = decoder
710            .read_next_frame()
711            .map_err(|e| CodecError::DecodingError(e.to_string()))?
712        {
713            let width = i32::from(frame.width);
714            let height = i32::from(frame.height);
715            let info = crate::ImageInfo::new(
716                width,
717                height,
718                skia_rs_core::ColorType::Rgba8888,
719                skia_rs_core::AlphaType::Unpremul,
720            );
721            let image = Image::from_raster_data(&info, &frame.buffer, usize::from(frame.width) * 4)
722                .ok_or_else(|| CodecError::DecodingError("Failed to build frame image".into()))?;
723
724            frames.push(crate::AnimationFrame {
725                image,
726                delay: std::time::Duration::from_millis(u64::from(frame.delay) * 10),
727                dispose: frame.dispose.into(),
728                // GIF is palette/transparent-index only; it has no
729                // "blend" concept, and every renderer treats frames as
730                // alpha-blended over the canvas.
731                blend: crate::BlendMethod::Over,
732                x_offset: i32::from(frame.left),
733                y_offset: i32::from(frame.top),
734            });
735        }
736
737        if frames.is_empty() {
738            return Err(CodecError::DecodingError("No frames in GIF".into()));
739        }
740
741        Ok(crate::AnimatedImage {
742            loop_count: decoder.repeat().into(),
743            frames,
744            canvas_width,
745            canvas_height,
746        })
747    }
748
749    /// Stub for builds without the `gif` feature.
750    #[cfg(not(feature = "gif"))]
751    pub fn decode_animated(&self, _data: &[u8]) -> CodecResult<crate::AnimatedImage> {
752        Err(CodecError::Unsupported(
753            "GIF decoding requires the 'gif' feature".into(),
754        ))
755    }
756}
757
758impl ImageDecoder for GifDecoder {
759    #[cfg(feature = "gif")]
760    fn decode<R: Read>(&self, reader: R) -> CodecResult<Image> {
761        let mut decoder = gif::DecodeOptions::new();
762        decoder.set_color_output(gif::ColorOutput::RGBA);
763        let mut decoder = decoder
764            .read_info(reader)
765            .map_err(|e| CodecError::DecodingError(e.to_string()))?;
766
767        // Decode to the logical-screen canvas, not the (possibly smaller)
768        // first frame. SkGifCodec always reports the logical-screen size as
769        // the image dimensions and composites the first frame at its
770        // left/top offset over a transparent canvas.
771        let canvas_width = usize::from(decoder.width());
772        let canvas_height = usize::from(decoder.height());
773
774        // Reject absurd logical-screen sizes before allocating the canvas
775        // buffer. The GIF header's width/height are attacker-controlled u16
776        // fields (max 65535 each), so a tiny malicious file can otherwise
777        // request a ~17GB allocation, aborting the process instead of
778        // returning an error. `MAX_DIM` matches SkCodec's per-dimension
779        // guard; `MAX_CANVAS_BYTES` additionally bounds the total
780        // allocation, since GIF's u16 dimensions never individually exceed
781        // `MAX_DIM` but can still multiply out to tens of gigabytes.
782        if canvas_width > MAX_DIM || canvas_height > MAX_DIM {
783            return Err(CodecError::InvalidData(
784                "GIF logical screen dimensions too large".into(),
785            ));
786        }
787        let canvas_stride = canvas_width
788            .checked_mul(4)
789            .ok_or_else(|| CodecError::InvalidData("GIF canvas row too large".into()))?;
790        let canvas_size = canvas_stride
791            .checked_mul(canvas_height)
792            .ok_or_else(|| CodecError::InvalidData("GIF canvas too large".into()))?;
793        if canvas_size > MAX_CANVAS_BYTES {
794            return Err(CodecError::InvalidData("GIF canvas too large".into()));
795        }
796
797        let first_frame = decoder
798            .read_next_frame()
799            .map_err(|e| CodecError::DecodingError(e.to_string()))?
800            .ok_or_else(|| CodecError::DecodingError("No frames in GIF".into()))?;
801
802        let frame_width = usize::from(first_frame.width);
803        let frame_height = usize::from(first_frame.height);
804        let left = usize::from(first_frame.left);
805        let top = usize::from(first_frame.top);
806
807        // Transparent canvas; blit the frame into place, clipping any part
808        // that falls outside the logical screen.
809        let mut pixels = vec![0u8; canvas_size];
810        for row in 0..frame_height {
811            let dst_y = top + row;
812            if dst_y >= canvas_height {
813                break;
814            }
815            let copy_w = frame_width.min(canvas_width.saturating_sub(left));
816            if copy_w == 0 {
817                continue;
818            }
819            let src_off = row * frame_width * 4;
820            let dst_off = dst_y * canvas_stride + left * 4;
821            pixels[dst_off..dst_off + copy_w * 4]
822                .copy_from_slice(&first_frame.buffer[src_off..src_off + copy_w * 4]);
823        }
824
825        let info = crate::ImageInfo::new(
826            i32::try_from(canvas_width).unwrap_or(i32::MAX),
827            i32::try_from(canvas_height).unwrap_or(i32::MAX),
828            skia_rs_core::ColorType::Rgba8888,
829            skia_rs_core::AlphaType::Unpremul,
830        );
831
832        Image::from_raster_data_owned(info, pixels, canvas_stride)
833            .ok_or_else(|| CodecError::DecodingError("Failed to create image".into()))
834    }
835
836    #[cfg(not(feature = "gif"))]
837    fn decode<R: Read>(&self, _reader: R) -> CodecResult<Image> {
838        Err(CodecError::Unsupported(
839            "GIF decoding requires the 'gif' feature".into(),
840        ))
841    }
842
843    fn format(&self) -> ImageFormat {
844        ImageFormat::Gif
845    }
846}
847
848// =============================================================================
849// WebP Codec
850// =============================================================================
851
852/// WebP decoder.
853#[derive(Debug, Default)]
854pub struct WebpDecoder;
855
856impl WebpDecoder {
857    /// Create a new WebP decoder.
858    #[must_use]
859    pub const fn new() -> Self {
860        Self
861    }
862}
863
864impl ImageDecoder for WebpDecoder {
865    #[cfg(feature = "webp")]
866    fn decode<R: Read>(&self, mut reader: R) -> CodecResult<Image> {
867        let mut data = Vec::new();
868        reader.read_to_end(&mut data).map_err(CodecError::Io)?;
869
870        let decoder = webp::Decoder::new(&data);
871        let webp_image = decoder
872            .decode()
873            .ok_or_else(|| CodecError::DecodingError("Failed to decode WebP".into()))?;
874
875        let width = i32::try_from(webp_image.width())
876            .map_err(|_| CodecError::InvalidData("WebP width exceeds i32 range".into()))?;
877        let height = i32::try_from(webp_image.height())
878            .map_err(|_| CodecError::InvalidData("WebP height exceeds i32 range".into()))?;
879        let width_usize = usize::try_from(webp_image.width()).unwrap_or(0);
880        let height_usize = usize::try_from(webp_image.height()).unwrap_or(0);
881        let has_alpha = webp_image.is_alpha();
882
883        // WebP returns RGB for images without alpha and RGBA for images
884        // with alpha. Normalize to RGBA so the rest of the pipeline sees
885        // a predictable 4-byte-per-pixel layout.
886        let src = webp_image.to_vec();
887        let pixels = if has_alpha {
888            src
889        } else {
890            // Expand RGB -> RGBA with opaque alpha.
891            let mut rgba = Vec::with_capacity(width_usize * height_usize * 4);
892            for chunk in src.chunks_exact(3) {
893                rgba.push(chunk[0]);
894                rgba.push(chunk[1]);
895                rgba.push(chunk[2]);
896                rgba.push(255);
897            }
898            rgba
899        };
900
901        let info = crate::ImageInfo::new(
902            width,
903            height,
904            skia_rs_core::ColorType::Rgba8888,
905            skia_rs_core::AlphaType::Unpremul,
906        );
907
908        Image::from_raster_data_owned(info, pixels, width_usize * 4)
909            .ok_or_else(|| CodecError::DecodingError("Failed to create image".into()))
910    }
911
912    #[cfg(not(feature = "webp"))]
913    fn decode<R: Read>(&self, _reader: R) -> CodecResult<Image> {
914        Err(CodecError::Unsupported(
915            "WebP decoding requires the 'webp' feature".into(),
916        ))
917    }
918
919    fn format(&self) -> ImageFormat {
920        ImageFormat::WebP
921    }
922}
923
924/// WebP encoder.
925#[derive(Debug)]
926pub struct WebpEncoder {
927    // Only read by the feature-gated encode path; the stub keeps the type
928    // constructible so downstream code compiles without the feature.
929    #[cfg_attr(not(feature = "webp"), allow(dead_code))]
930    quality: EncoderQuality,
931    #[cfg_attr(not(feature = "webp"), allow(dead_code))]
932    lossless: bool,
933}
934
935impl WebpEncoder {
936    /// Create a new WebP encoder with default quality.
937    #[must_use]
938    pub const fn new() -> Self {
939        Self {
940            quality: EncoderQuality::DEFAULT,
941            lossless: false,
942        }
943    }
944
945    /// Create a WebP encoder with specified quality.
946    #[must_use]
947    pub const fn with_quality(quality: EncoderQuality) -> Self {
948        Self {
949            quality,
950            lossless: false,
951        }
952    }
953
954    /// Create a lossless WebP encoder.
955    #[must_use]
956    pub const fn lossless() -> Self {
957        Self {
958            quality: EncoderQuality::DEFAULT,
959            lossless: true,
960        }
961    }
962}
963
964impl Default for WebpEncoder {
965    fn default() -> Self {
966        Self::new()
967    }
968}
969
970impl ImageEncoder for WebpEncoder {
971    #[cfg(feature = "webp")]
972    fn encode<W: Write>(&self, image: &Image, mut writer: W) -> CodecResult<()> {
973        let pixels = image
974            .peek_pixels()
975            .ok_or_else(|| CodecError::EncodingError("Cannot access pixels".into()))?;
976        let width = u32::try_from(image.width()).unwrap_or(0);
977        let height = u32::try_from(image.height()).unwrap_or(0);
978
979        // Convert to RGBA if needed
980        let mut rgba = match image.color_type() {
981            skia_rs_core::ColorType::Rgba8888 => pixels.to_vec(),
982            skia_rs_core::ColorType::Bgra8888 => {
983                let mut rgba = Vec::with_capacity(pixels.len());
984                for chunk in pixels.chunks(4) {
985                    rgba.push(chunk[2]);
986                    rgba.push(chunk[1]);
987                    rgba.push(chunk[0]);
988                    rgba.push(chunk[3]);
989                }
990                rgba
991            }
992            _ => {
993                return Err(CodecError::Unsupported(
994                    "Unsupported color type for WebP encoding".into(),
995                ));
996            }
997        };
998
999        // WebP stores straight alpha; unpremultiply premultiplied input.
1000        unpremultiply_for_encode(image, &mut rgba);
1001
1002        let webp_encoder = webp::Encoder::from_rgba(&rgba, width, height);
1003        let webp_bytes = if self.lossless {
1004            webp_encoder.encode_lossless()
1005        } else {
1006            webp_encoder.encode(f32::from(self.quality.value()))
1007        };
1008
1009        writer.write_all(&webp_bytes).map_err(CodecError::Io)?;
1010        Ok(())
1011    }
1012
1013    #[cfg(not(feature = "webp"))]
1014    fn encode<W: Write>(&self, _image: &Image, _writer: W) -> CodecResult<()> {
1015        Err(CodecError::Unsupported(
1016            "WebP encoding requires the 'webp' feature".into(),
1017        ))
1018    }
1019
1020    fn format(&self) -> ImageFormat {
1021        ImageFormat::WebP
1022    }
1023}
1024
1025// =============================================================================
1026// BMP Codec
1027// =============================================================================
1028
1029/// BMP decoder.
1030#[derive(Debug, Default)]
1031pub struct BmpDecoder;
1032
1033impl BmpDecoder {
1034    /// Create a new BMP decoder.
1035    #[must_use]
1036    pub const fn new() -> Self {
1037        Self
1038    }
1039}
1040
1041impl ImageDecoder for BmpDecoder {
1042    fn decode<R: Read>(&self, mut reader: R) -> CodecResult<Image> {
1043        let mut data = Vec::new();
1044        reader.read_to_end(&mut data).map_err(CodecError::Io)?;
1045        decode_bmp(&data)
1046    }
1047
1048    fn format(&self) -> ImageFormat {
1049        ImageFormat::Bmp
1050    }
1051}
1052
1053/// BMP encoder.
1054#[derive(Debug, Default)]
1055pub struct BmpEncoder;
1056
1057impl BmpEncoder {
1058    /// Create a new BMP encoder.
1059    #[must_use]
1060    pub const fn new() -> Self {
1061        Self
1062    }
1063}
1064
1065impl ImageEncoder for BmpEncoder {
1066    fn encode<W: Write>(&self, image: &Image, mut writer: W) -> CodecResult<()> {
1067        let raw_pixels = image
1068            .peek_pixels()
1069            .ok_or_else(|| CodecError::EncodingError("Cannot access pixels".into()))?;
1070
1071        // BMP V3+ alpha is straight (unpremultiplied); unpremultiply if the
1072        // source image carries premultiplied pixels. This assumes an
1073        // RGBA/BGRA 8888 layout (the encoder always writes 32-bit BGRA).
1074        let mut pixels = raw_pixels.to_vec();
1075        unpremultiply_for_encode(image, &mut pixels);
1076        let pixels = &pixels[..];
1077
1078        let width = u32::try_from(image.width()).unwrap_or(0);
1079        let height = u32::try_from(image.height()).unwrap_or(0);
1080        let width_i32 = image.width();
1081        let height_i32 = image.height();
1082
1083        // Calculate row padding (each row must be aligned to 4 bytes)
1084        let row_size = (width * 4 + 3) & !3; // 32-bit BGRA, aligned
1085        let pixel_data_size = row_size * height;
1086        let file_size = 14 + 40 + pixel_data_size; // header + DIB header + pixels
1087
1088        // BITMAPFILEHEADER (14 bytes)
1089        writer.write_all(b"BM")?; // Signature
1090        writer.write_all(&file_size.to_le_bytes())?; // File size
1091        writer.write_all(&[0u8; 4])?; // Reserved
1092        writer.write_all(&(14u32 + 40).to_le_bytes())?; // Pixel data offset
1093
1094        // BITMAPINFOHEADER (40 bytes)
1095        writer.write_all(&40u32.to_le_bytes())?; // Header size
1096        writer.write_all(&width_i32.to_le_bytes())?; // Width
1097        writer.write_all(&height_i32.to_le_bytes())?; // Height (positive = bottom-up)
1098        writer.write_all(&1u16.to_le_bytes())?; // Planes
1099        writer.write_all(&32u16.to_le_bytes())?; // Bits per pixel (32-bit BGRA)
1100        writer.write_all(&0u32.to_le_bytes())?; // Compression (BI_RGB = none)
1101        writer.write_all(&pixel_data_size.to_le_bytes())?; // Image size
1102        writer.write_all(&2835u32.to_le_bytes())?; // X pixels per meter (~72 DPI)
1103        writer.write_all(&2835u32.to_le_bytes())?; // Y pixels per meter
1104        writer.write_all(&0u32.to_le_bytes())?; // Colors used
1105        writer.write_all(&0u32.to_le_bytes())?; // Important colors
1106
1107        // Pixel data (bottom-to-top, BGRA)
1108        let stride = usize::try_from(width).unwrap_or(0) * 4;
1109        let row_padding = usize::try_from(row_size).unwrap_or(0) - stride;
1110        let padding = vec![0u8; row_padding];
1111
1112        for y in (0..usize::try_from(height).unwrap_or(0)).rev() {
1113            let row_start = y * stride;
1114            let row = &pixels[row_start..row_start + stride];
1115
1116            // Convert RGBA to BGRA
1117            for chunk in row.chunks(4) {
1118                writer.write_all(&[chunk[2], chunk[1], chunk[0], chunk[3]])?; // BGRA
1119            }
1120
1121            if row_padding > 0 {
1122                writer.write_all(&padding)?;
1123            }
1124        }
1125
1126        Ok(())
1127    }
1128
1129    fn format(&self) -> ImageFormat {
1130        ImageFormat::Bmp
1131    }
1132}
1133
1134/// Channel masks for a `BI_BITFIELDS` BMP.
1135#[derive(Debug, Clone, Copy)]
1136struct BitfieldMasks {
1137    red: u32,
1138    green: u32,
1139    blue: u32,
1140    alpha: u32,
1141}
1142
1143impl BitfieldMasks {
1144    /// Extract `mask`'s channel out of `value` and scale it to a full 8-bit
1145    /// range (`round(raw * 255 / channel_max)`), matching `SkMasks`.
1146    fn sample(value: u32, mask: u32) -> u8 {
1147        if mask == 0 {
1148            return 0;
1149        }
1150        let shift = mask.trailing_zeros();
1151        let bits = (mask >> shift).count_ones();
1152        let raw = (value & mask) >> shift;
1153        let max = (1u32 << bits) - 1;
1154        // `raw <= max` by construction, so `(raw * 255 + max/2) / max` is
1155        // always in `0..=255`; `unwrap_or(255)` is an unreachable fallback.
1156        u8::try_from((raw * 255 + max / 2) / max).unwrap_or(255)
1157    }
1158}
1159
1160/// Decode a BMP image from bytes.
1161#[allow(
1162    clippy::too_many_lines,
1163    reason = "BMP's several bit-depth/compression paths (24/16/8-bit, BI_BITFIELDS) read \
1164    more clearly inlined in one function than split across helpers that would each need \
1165    the same header/bounds context threaded through"
1166)]
1167fn decode_bmp(data: &[u8]) -> CodecResult<Image> {
1168    if data.len() < 54 {
1169        return Err(CodecError::InvalidData("BMP too short".into()));
1170    }
1171
1172    // Validate signature
1173    if &data[0..2] != b"BM" {
1174        return Err(CodecError::InvalidData("Invalid BMP signature".into()));
1175    }
1176
1177    // Parse BITMAPFILEHEADER
1178    let pixel_offset = u32::from_le_bytes([data[10], data[11], data[12], data[13]]) as usize;
1179
1180    // Parse BITMAPINFOHEADER
1181    let header_size = u32::from_le_bytes([data[14], data[15], data[16], data[17]]);
1182    if header_size < 40 {
1183        return Err(CodecError::Unsupported(
1184            "Only BITMAPINFOHEADER and later supported".into(),
1185        ));
1186    }
1187
1188    let width = i32::from_le_bytes([data[18], data[19], data[20], data[21]]);
1189    let height = i32::from_le_bytes([data[22], data[23], data[24], data[25]]);
1190    let bits_per_pixel = u16::from_le_bytes([data[28], data[29]]);
1191    let compression = u32::from_le_bytes([data[30], data[31], data[32], data[33]]);
1192
1193    // Reject non-positive / absurd dimensions before allocating. `height`
1194    // may be `i32::MIN`, whose negation overflows, so use `unsigned_abs`.
1195    if width <= 0 || height == 0 {
1196        return Err(CodecError::InvalidData("Invalid BMP dimensions".into()));
1197    }
1198    let width = usize::try_from(width).unwrap_or(0);
1199    let (height, bottom_up) = if height < 0 {
1200        (usize::try_from(height.unsigned_abs()).unwrap_or(0), false)
1201    } else {
1202        (usize::try_from(height).unwrap_or(0), true)
1203    };
1204    if width > MAX_DIM || height > MAX_DIM || width.checked_mul(height).is_none() {
1205        return Err(CodecError::InvalidData("BMP dimensions too large".into()));
1206    }
1207
1208    // Only support uncompressed (BI_RGB) and BI_BITFIELDS.
1209    if compression != 0 && compression != 3 {
1210        return Err(CodecError::Unsupported(format!(
1211            "BMP compression {compression} not supported"
1212        )));
1213    }
1214
1215    if pixel_offset >= data.len() {
1216        return Err(CodecError::InvalidData("Invalid pixel data offset".into()));
1217    }
1218
1219    let pixel_data = &data[pixel_offset..];
1220
1221    // Row stride (padded to a 4-byte boundary) and the total number of
1222    // source bytes the pixel array must contain. A file that stops short of
1223    // this is truncated and must be reported, not silently zero-filled.
1224    let src_row_size = match bits_per_pixel {
1225        32 => width
1226            .checked_mul(4)
1227            .ok_or_else(|| CodecError::InvalidData("BMP row too large".into()))?,
1228        24 => (width * 3 + 3) & !3,
1229        16 => (width * 2 + 3) & !3,
1230        8 => (width + 3) & !3,
1231        _ => {
1232            return Err(CodecError::Unsupported(format!(
1233                "BMP {bits_per_pixel} bits per pixel not supported"
1234            )));
1235        }
1236    };
1237    let required = src_row_size
1238        .checked_mul(height)
1239        .ok_or_else(|| CodecError::InvalidData("BMP pixel array too large".into()))?;
1240    if pixel_data.len() < required {
1241        return Err(CodecError::InvalidData("BMP pixel data truncated".into()));
1242    }
1243
1244    // BI_BITFIELDS: channel masks live either inside a V4+ header or in the
1245    // 12 bytes immediately after a 40-byte BITMAPINFOHEADER (absolute offset
1246    // 54). Both land the red mask at absolute offset 54.
1247    let masks = if compression == 3 {
1248        let mask_at = |off: usize| -> u32 {
1249            if off + 4 <= data.len() {
1250                u32::from_le_bytes([data[off], data[off + 1], data[off + 2], data[off + 3]])
1251            } else {
1252                0
1253            }
1254        };
1255        let red = mask_at(54);
1256        let green = mask_at(58);
1257        let blue = mask_at(62);
1258        // Alpha mask is only present for V3+ headers (>= 56 bytes) / V4.
1259        let alpha = if header_size >= 56 { mask_at(66) } else { 0 };
1260        Some(BitfieldMasks {
1261            red,
1262            green,
1263            blue,
1264            alpha,
1265        })
1266    } else {
1267        None
1268    };
1269
1270    let mut rgba = vec![0u8; width * height * 4];
1271
1272    match bits_per_pixel {
1273        24 => {
1274            // 24-bit BGR
1275            let row_size = src_row_size;
1276            for y in 0..height {
1277                let src_y = if bottom_up { height - 1 - y } else { y };
1278                let src_row = src_y * row_size;
1279                let dst_row = y * width * 4;
1280
1281                for x in 0..width {
1282                    let src = src_row + x * 3;
1283                    let dst = dst_row + x * 4;
1284                    if src + 2 < pixel_data.len() {
1285                        rgba[dst] = pixel_data[src + 2]; // R
1286                        rgba[dst + 1] = pixel_data[src + 1]; // G
1287                        rgba[dst + 2] = pixel_data[src]; // B
1288                        rgba[dst + 3] = 255; // A
1289                    }
1290                }
1291            }
1292        }
1293        16 => {
1294            // 16-bit is always mask-based. Default to X1R5G5B5 when no
1295            // explicit bitfields are given.
1296            let m = masks.unwrap_or(BitfieldMasks {
1297                red: 0x7C00,
1298                green: 0x03E0,
1299                blue: 0x001F,
1300                alpha: 0,
1301            });
1302            let row_size = src_row_size;
1303            for y in 0..height {
1304                let src_y = if bottom_up { height - 1 - y } else { y };
1305                let src_row = src_y * row_size;
1306                let dst_row = y * width * 4;
1307                for x in 0..width {
1308                    let src = src_row + x * 2;
1309                    let dst = dst_row + x * 4;
1310                    if src + 1 < pixel_data.len() {
1311                        let value =
1312                            u32::from(u16::from_le_bytes([pixel_data[src], pixel_data[src + 1]]));
1313                        rgba[dst] = BitfieldMasks::sample(value, m.red);
1314                        rgba[dst + 1] = BitfieldMasks::sample(value, m.green);
1315                        rgba[dst + 2] = BitfieldMasks::sample(value, m.blue);
1316                        rgba[dst + 3] = if m.alpha == 0 {
1317                            255
1318                        } else {
1319                            BitfieldMasks::sample(value, m.alpha)
1320                        };
1321                    }
1322                }
1323            }
1324        }
1325        32 => {
1326            // 32-bit. For BI_RGB the fourth byte is undefined padding
1327            // (kBGRX): SkBmpCodec treats a standalone 32-bit BI_RGB image as
1328            // opaque and only honors the alpha byte for BMP-in-ICO. For
1329            // BI_BITFIELDS we apply the declared channel masks.
1330            let row_size = src_row_size;
1331            for y in 0..height {
1332                let src_y = if bottom_up { height - 1 - y } else { y };
1333                let src_row = src_y * row_size;
1334                let dst_row = y * width * 4;
1335
1336                for x in 0..width {
1337                    let src = src_row + x * 4;
1338                    let dst = dst_row + x * 4;
1339                    if src + 3 < pixel_data.len() {
1340                        if let Some(m) = masks {
1341                            let value = u32::from_le_bytes([
1342                                pixel_data[src],
1343                                pixel_data[src + 1],
1344                                pixel_data[src + 2],
1345                                pixel_data[src + 3],
1346                            ]);
1347                            rgba[dst] = BitfieldMasks::sample(value, m.red);
1348                            rgba[dst + 1] = BitfieldMasks::sample(value, m.green);
1349                            rgba[dst + 2] = BitfieldMasks::sample(value, m.blue);
1350                            rgba[dst + 3] = if m.alpha == 0 {
1351                                255
1352                            } else {
1353                                BitfieldMasks::sample(value, m.alpha)
1354                            };
1355                        } else {
1356                            rgba[dst] = pixel_data[src + 2]; // R
1357                            rgba[dst + 1] = pixel_data[src + 1]; // G
1358                            rgba[dst + 2] = pixel_data[src]; // B
1359                            // BI_RGB: 4th byte is padding, image is opaque.
1360                            rgba[dst + 3] = 255; // A
1361                        }
1362                    }
1363                }
1364            }
1365        }
1366        8 => {
1367            // 8-bit indexed (need to read color table)
1368            let colors_used = u32::from_le_bytes([data[46], data[47], data[48], data[49]]) as usize;
1369            let palette_size = if colors_used == 0 { 256 } else { colors_used };
1370            let palette_offset = 14 + header_size as usize;
1371
1372            if palette_offset + palette_size * 4 > pixel_offset {
1373                return Err(CodecError::InvalidData("Invalid palette".into()));
1374            }
1375
1376            let palette = &data[palette_offset..palette_offset + palette_size * 4];
1377            let row_size = (width + 3) & !3;
1378
1379            for y in 0..height {
1380                let src_y = if bottom_up { height - 1 - y } else { y };
1381                let src_row = src_y * row_size;
1382                let dst_row = y * width * 4;
1383
1384                for x in 0..width {
1385                    let src = src_row + x;
1386                    let dst = dst_row + x * 4;
1387                    if src < pixel_data.len() {
1388                        let index = pixel_data[src] as usize;
1389                        if index < palette_size {
1390                            let p = index * 4;
1391                            rgba[dst] = palette[p + 2]; // R
1392                            rgba[dst + 1] = palette[p + 1]; // G
1393                            rgba[dst + 2] = palette[p]; // B
1394                            rgba[dst + 3] = 255; // A
1395                        }
1396                    }
1397                }
1398            }
1399        }
1400        _ => {
1401            return Err(CodecError::Unsupported(format!(
1402                "BMP {bits_per_pixel} bits per pixel not supported"
1403            )));
1404        }
1405    }
1406
1407    let info = crate::ImageInfo::new(
1408        i32::try_from(width).unwrap_or(i32::MAX),
1409        i32::try_from(height).unwrap_or(i32::MAX),
1410        skia_rs_core::ColorType::Rgba8888,
1411        skia_rs_core::AlphaType::Unpremul,
1412    );
1413
1414    Image::from_raster_data_owned(info, rgba, width * 4)
1415        .ok_or_else(|| CodecError::DecodingError("Failed to create image".into()))
1416}
1417
1418// =============================================================================
1419// ICO Codec
1420// =============================================================================
1421
1422/// ICO decoder.
1423#[derive(Debug, Default)]
1424pub struct IcoDecoder;
1425
1426impl IcoDecoder {
1427    /// Create a new ICO decoder.
1428    #[must_use]
1429    pub const fn new() -> Self {
1430        Self
1431    }
1432}
1433
1434impl ImageDecoder for IcoDecoder {
1435    fn decode<R: Read>(&self, mut reader: R) -> CodecResult<Image> {
1436        let mut data = Vec::new();
1437        reader.read_to_end(&mut data).map_err(CodecError::Io)?;
1438        decode_ico(&data)
1439    }
1440
1441    fn format(&self) -> ImageFormat {
1442        ImageFormat::Ico
1443    }
1444}
1445
1446/// Decode an ICO image from bytes.
1447/// Returns the largest image in the icon file.
1448fn decode_ico(data: &[u8]) -> CodecResult<Image> {
1449    if data.len() < 6 {
1450        return Err(CodecError::InvalidData("ICO too short".into()));
1451    }
1452
1453    // Validate header
1454    let reserved = u16::from_le_bytes([data[0], data[1]]);
1455    let image_type = u16::from_le_bytes([data[2], data[3]]);
1456    let image_count = u16::from_le_bytes([data[4], data[5]]) as usize;
1457
1458    if reserved != 0 || image_type != 1 {
1459        return Err(CodecError::InvalidData("Invalid ICO header".into()));
1460    }
1461
1462    if image_count == 0 {
1463        return Err(CodecError::InvalidData("ICO has no images".into()));
1464    }
1465
1466    // Find the largest image. Only consider directory entries that are
1467    // fully present in the buffer — a truncated directory must not cause an
1468    // out-of-bounds read.
1469    let mut best_index: Option<usize> = None;
1470    let mut best_size = 0u32;
1471
1472    for i in 0..image_count {
1473        let entry_offset = 6 + i * 16;
1474        if entry_offset + 16 > data.len() {
1475            break;
1476        }
1477
1478        let width = if data[entry_offset] == 0 {
1479            256
1480        } else {
1481            u32::from(data[entry_offset])
1482        };
1483        let height = if data[entry_offset + 1] == 0 {
1484            256
1485        } else {
1486            u32::from(data[entry_offset + 1])
1487        };
1488
1489        let size = width * height;
1490        if best_index.is_none() || size > best_size {
1491            best_size = size;
1492            best_index = Some(i);
1493        }
1494    }
1495
1496    // Get the best entry. If no complete entry was found the directory is
1497    // truncated.
1498    let best_index =
1499        best_index.ok_or_else(|| CodecError::InvalidData("ICO directory truncated".into()))?;
1500    let entry_offset = 6 + best_index * 16;
1501    let image_offset = u32::from_le_bytes([
1502        data[entry_offset + 12],
1503        data[entry_offset + 13],
1504        data[entry_offset + 14],
1505        data[entry_offset + 15],
1506    ]) as usize;
1507    let image_size = u32::from_le_bytes([
1508        data[entry_offset + 8],
1509        data[entry_offset + 9],
1510        data[entry_offset + 10],
1511        data[entry_offset + 11],
1512    ]) as usize;
1513
1514    // Bounds-check the embedded image slice. `image_offset`/`image_size` are
1515    // u32-derived, so their sum cannot overflow usize on 64-bit, but use a
1516    // checked add for portability and reject offsets past the buffer end.
1517    let end = image_offset
1518        .checked_add(image_size)
1519        .ok_or_else(|| CodecError::InvalidData("Invalid ICO image data".into()))?;
1520    if image_size == 0 || image_offset >= data.len() || end > data.len() {
1521        return Err(CodecError::InvalidData("Invalid ICO image data".into()));
1522    }
1523
1524    let image_data = &data[image_offset..end];
1525
1526    // Check if it's PNG or BMP
1527    if image_data.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
1528        // PNG encoded
1529        PngDecoder::new().decode_bytes(image_data)
1530    } else {
1531        // BMP encoded (without file header)
1532        decode_ico_bmp(image_data)
1533    }
1534}
1535
1536/// Decode a BMP from ICO format (no BITMAPFILEHEADER).
1537#[allow(
1538    clippy::too_many_lines,
1539    reason = "ICO-embedded BMP's 32/24-bit pixel + AND-mask paths read more clearly inlined \
1540    than split across helpers that would each need the same header/bounds context threaded through"
1541)]
1542fn decode_ico_bmp(data: &[u8]) -> CodecResult<Image> {
1543    if data.len() < 40 {
1544        return Err(CodecError::InvalidData("ICO BMP too short".into()));
1545    }
1546
1547    let header_size = u32::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
1548    if header_size < 40 || header_size > data.len() {
1549        return Err(CodecError::Unsupported("Invalid ICO BMP header".into()));
1550    }
1551
1552    let width = i32::from_le_bytes([data[4], data[5], data[6], data[7]]);
1553    let height = i32::from_le_bytes([data[8], data[9], data[10], data[11]]);
1554    // Reject non-positive / absurd dimensions before allocating. The stored
1555    // height counts both the color bitmap and the AND mask, so it is halved.
1556    if width <= 0 || height <= 0 {
1557        return Err(CodecError::InvalidData("Invalid ICO BMP dimensions".into()));
1558    }
1559    let width = usize::try_from(width).unwrap_or(0);
1560    let height = usize::try_from(height).unwrap_or(0) / 2; // Height includes the mask
1561    if width == 0 || height == 0 || width > MAX_DIM || height > MAX_DIM {
1562        return Err(CodecError::InvalidData("Invalid ICO BMP dimensions".into()));
1563    }
1564    let bits_per_pixel = u16::from_le_bytes([data[14], data[15]]);
1565
1566    let pixel_offset = header_size;
1567    let pixel_data = &data[pixel_offset..];
1568
1569    // Before allocating the (width * height * 4) output buffer, verify the
1570    // file actually contains the color bitmap it claims: a tiny file with a
1571    // header claiming huge in-range dimensions must be rejected here, not
1572    // handed to the allocator.
1573    let src_row_size = match bits_per_pixel {
1574        32 => width
1575            .checked_mul(4)
1576            .ok_or_else(|| CodecError::InvalidData("ICO BMP row too large".into()))?,
1577        24 => (width * 3 + 3) & !3,
1578        _ => {
1579            return Err(CodecError::Unsupported(format!(
1580                "ICO {bits_per_pixel} bits per pixel not supported"
1581            )));
1582        }
1583    };
1584    let required = src_row_size
1585        .checked_mul(height)
1586        .ok_or_else(|| CodecError::InvalidData("ICO BMP pixel array too large".into()))?;
1587    if pixel_data.len() < required {
1588        return Err(CodecError::InvalidData(
1589            "ICO BMP pixel data truncated".into(),
1590        ));
1591    }
1592
1593    let mut rgba = vec![0u8; width * height * 4];
1594
1595    match bits_per_pixel {
1596        32 => {
1597            // 32-bit BGRA
1598            let row_size = width * 4;
1599            for y in 0..height {
1600                let src_y = height - 1 - y; // Bottom-up
1601                let src_row = src_y * row_size;
1602                let dst_row = y * width * 4;
1603
1604                for x in 0..width {
1605                    let src = src_row + x * 4;
1606                    let dst = dst_row + x * 4;
1607                    if src + 3 < pixel_data.len() {
1608                        rgba[dst] = pixel_data[src + 2]; // R
1609                        rgba[dst + 1] = pixel_data[src + 1]; // G
1610                        rgba[dst + 2] = pixel_data[src]; // B
1611                        rgba[dst + 3] = pixel_data[src + 3]; // A
1612                    }
1613                }
1614            }
1615        }
1616        24 => {
1617            // 24-bit BGR with separate alpha mask
1618            let row_size = (width * 3 + 3) & !3;
1619            let mask_row_size = width.div_ceil(32) * 4;
1620            let mask_offset = height * row_size;
1621
1622            for y in 0..height {
1623                let src_y = height - 1 - y;
1624                let src_row = src_y * row_size;
1625                let dst_row = y * width * 4;
1626                let mask_row = mask_offset + src_y * mask_row_size;
1627
1628                for x in 0..width {
1629                    let src = src_row + x * 3;
1630                    let dst = dst_row + x * 4;
1631                    if src + 2 < pixel_data.len() {
1632                        rgba[dst] = pixel_data[src + 2]; // R
1633                        rgba[dst + 1] = pixel_data[src + 1]; // G
1634                        rgba[dst + 2] = pixel_data[src]; // B
1635
1636                        // Check mask
1637                        let mask_byte = mask_row + x / 8;
1638                        let mask_bit = 7 - (x % 8);
1639                        let alpha = if mask_byte < pixel_data.len() {
1640                            if (pixel_data[mask_byte] >> mask_bit) & 1 == 0 {
1641                                255
1642                            } else {
1643                                0
1644                            }
1645                        } else {
1646                            255
1647                        };
1648                        rgba[dst + 3] = alpha;
1649                    }
1650                }
1651            }
1652        }
1653        _ => {
1654            return Err(CodecError::Unsupported(format!(
1655                "ICO {bits_per_pixel} bits per pixel not supported"
1656            )));
1657        }
1658    }
1659
1660    let info = crate::ImageInfo::new(
1661        i32::try_from(width).unwrap_or(i32::MAX),
1662        i32::try_from(height).unwrap_or(i32::MAX),
1663        skia_rs_core::ColorType::Rgba8888,
1664        skia_rs_core::AlphaType::Unpremul,
1665    );
1666
1667    Image::from_raster_data_owned(info, rgba, width * 4)
1668        .ok_or_else(|| CodecError::DecodingError("Failed to create image".into()))
1669}
1670
1671// =============================================================================
1672// WBMP Codec (Wireless Bitmap)
1673// =============================================================================
1674
1675/// WBMP decoder.
1676///
1677/// WBMP is a simple monochrome image format used in WAP applications.
1678pub struct WbmpDecoder;
1679
1680impl WbmpDecoder {
1681    /// Create a new WBMP decoder.
1682    #[must_use]
1683    pub const fn new() -> Self {
1684        Self
1685    }
1686}
1687
1688impl Default for WbmpDecoder {
1689    fn default() -> Self {
1690        Self::new()
1691    }
1692}
1693
1694impl ImageDecoder for WbmpDecoder {
1695    fn decode<R: Read>(&self, mut reader: R) -> CodecResult<Image> {
1696        let mut data = Vec::new();
1697        reader.read_to_end(&mut data).map_err(CodecError::Io)?;
1698        decode_wbmp(&data)
1699    }
1700
1701    fn format(&self) -> ImageFormat {
1702        ImageFormat::Wbmp
1703    }
1704}
1705
1706/// WBMP encoder.
1707pub struct WbmpEncoder;
1708
1709impl WbmpEncoder {
1710    /// Create a new WBMP encoder.
1711    #[must_use]
1712    pub const fn new() -> Self {
1713        Self
1714    }
1715}
1716
1717impl Default for WbmpEncoder {
1718    fn default() -> Self {
1719        Self::new()
1720    }
1721}
1722
1723impl ImageEncoder for WbmpEncoder {
1724    fn encode<W: Write>(&self, image: &Image, mut writer: W) -> CodecResult<()> {
1725        encode_wbmp(image, &mut writer)
1726    }
1727
1728    fn format(&self) -> ImageFormat {
1729        ImageFormat::Wbmp
1730    }
1731}
1732
1733/// Read a WBMP multi-byte integer.
1734/// Each byte has 7 bits of data, MSB indicates if more bytes follow.
1735fn read_wbmp_int(data: &[u8], offset: &mut usize) -> Option<u32> {
1736    let mut value = 0u32;
1737    loop {
1738        if *offset >= data.len() {
1739            return None;
1740        }
1741        let byte = data[*offset];
1742        *offset += 1;
1743        value = (value << 7) | u32::from(byte & 0x7F);
1744        if byte & 0x80 == 0 {
1745            break;
1746        }
1747        if value > 0xFFFF {
1748            return None; // Sanity check
1749        }
1750    }
1751    Some(value)
1752}
1753
1754/// Write a WBMP multi-byte integer.
1755fn write_wbmp_int<W: Write>(writer: &mut W, mut value: u32) -> CodecResult<()> {
1756    let mut bytes = Vec::new();
1757    bytes.push(u8::try_from(value & 0x7F).unwrap_or(0));
1758    value >>= 7;
1759    while value > 0 {
1760        bytes.push(0x80 | u8::try_from(value & 0x7F).unwrap_or(0));
1761        value >>= 7;
1762    }
1763    bytes.reverse();
1764    writer.write_all(&bytes).map_err(CodecError::Io)
1765}
1766
1767/// Decode a WBMP image from bytes.
1768fn decode_wbmp(data: &[u8]) -> CodecResult<Image> {
1769    if data.len() < 4 {
1770        return Err(CodecError::InvalidData("WBMP too short".into()));
1771    }
1772
1773    let mut offset = 0;
1774
1775    // Read type (should be 0 for WBMP type 0)
1776    let type_field = read_wbmp_int(data, &mut offset)
1777        .ok_or_else(|| CodecError::InvalidData("Invalid WBMP type".into()))?;
1778    if type_field != 0 {
1779        return Err(CodecError::Unsupported(format!(
1780            "WBMP type {type_field} not supported"
1781        )));
1782    }
1783
1784    // Read fixed header field (should be 0)
1785    let fix_header = read_wbmp_int(data, &mut offset)
1786        .ok_or_else(|| CodecError::InvalidData("Invalid WBMP header".into()))?;
1787    if fix_header != 0 {
1788        return Err(CodecError::Unsupported(
1789            "Extended WBMP headers not supported".into(),
1790        ));
1791    }
1792
1793    // Read width
1794    let width = read_wbmp_int(data, &mut offset)
1795        .ok_or_else(|| CodecError::InvalidData("Invalid WBMP width".into()))?;
1796
1797    // Read height
1798    let height = read_wbmp_int(data, &mut offset)
1799        .ok_or_else(|| CodecError::InvalidData("Invalid WBMP height".into()))?;
1800
1801    if width == 0 || height == 0 || width > 10000 || height > 10000 {
1802        return Err(CodecError::InvalidData("Invalid WBMP dimensions".into()));
1803    }
1804
1805    // Calculate row size (bits rounded up to bytes)
1806    let width_usize = usize::try_from(width).unwrap_or(0);
1807    let height_usize = usize::try_from(height).unwrap_or(0);
1808    let row_bytes = width_usize.div_ceil(8);
1809    let expected_size = offset + row_bytes * height_usize;
1810
1811    if data.len() < expected_size {
1812        return Err(CodecError::InvalidData("WBMP data too short".into()));
1813    }
1814
1815    // Decode pixels (1 = white, 0 = black)
1816    let mut rgba = vec![0u8; width_usize * height_usize * 4];
1817
1818    for y in 0..height_usize {
1819        let row_start = offset + y * row_bytes;
1820        for x in 0..width_usize {
1821            let byte_idx = x / 8;
1822            let bit_idx = 7 - (x % 8);
1823            let bit = (data[row_start + byte_idx] >> bit_idx) & 1;
1824
1825            let pixel_idx = (y * width_usize + x) * 4;
1826            let value = if bit == 1 { 255 } else { 0 };
1827            rgba[pixel_idx] = value; // R
1828            rgba[pixel_idx + 1] = value; // G
1829            rgba[pixel_idx + 2] = value; // B
1830            rgba[pixel_idx + 3] = 255; // A
1831        }
1832    }
1833
1834    let info = crate::ImageInfo::new(
1835        i32::try_from(width).unwrap_or(i32::MAX),
1836        i32::try_from(height).unwrap_or(i32::MAX),
1837        skia_rs_core::ColorType::Rgba8888,
1838        skia_rs_core::AlphaType::Opaque,
1839    );
1840
1841    Image::from_raster_data_owned(info, rgba, width_usize * 4)
1842        .ok_or_else(|| CodecError::DecodingError("Failed to create image".into()))
1843}
1844
1845/// Encode an image as WBMP.
1846fn encode_wbmp<W: Write>(image: &Image, writer: &mut W) -> CodecResult<()> {
1847    let width = u32::try_from(image.width()).unwrap_or(0);
1848    let height = u32::try_from(image.height()).unwrap_or(0);
1849    let width_usize = usize::try_from(width).unwrap_or(0);
1850    let height_usize = usize::try_from(height).unwrap_or(0);
1851    let pixels = image
1852        .peek_pixels()
1853        .ok_or_else(|| CodecError::EncodingError("Cannot access pixels".into()))?;
1854
1855    // Write type (0)
1856    write_wbmp_int(writer, 0)?;
1857
1858    // Write fixed header field (0)
1859    write_wbmp_int(writer, 0)?;
1860
1861    // Write width
1862    write_wbmp_int(writer, width)?;
1863
1864    // Write height
1865    write_wbmp_int(writer, height)?;
1866
1867    // Convert to 1-bit (use luminance threshold of 128)
1868    let row_bytes = width_usize.div_ceil(8);
1869
1870    for y in 0..height_usize {
1871        let mut row_data = vec![0u8; row_bytes];
1872
1873        for x in 0..width_usize {
1874            let pixel_idx = (y * width_usize + x) * 4;
1875
1876            // Calculate luminance
1877            let r = u32::from(pixels[pixel_idx]);
1878            let g = u32::from(pixels[pixel_idx + 1]);
1879            let b = u32::from(pixels[pixel_idx + 2]);
1880            let luminance = (r * 299 + g * 587 + b * 114) / 1000;
1881
1882            // Set bit if luminance > 128 (white)
1883            if luminance > 128 {
1884                let byte_idx = x / 8;
1885                let bit_idx = 7 - (x % 8);
1886                row_data[byte_idx] |= 1 << bit_idx;
1887            }
1888        }
1889
1890        writer.write_all(&row_data).map_err(CodecError::Io)?;
1891    }
1892
1893    Ok(())
1894}
1895
1896/// Get WBMP dimensions without fully decoding.
1897fn get_wbmp_dimensions(data: &[u8]) -> CodecResult<(i32, i32)> {
1898    if data.len() < 4 {
1899        return Err(CodecError::InvalidData("WBMP too short".into()));
1900    }
1901
1902    let mut offset = 0;
1903
1904    // Skip type and header
1905    let _ = read_wbmp_int(data, &mut offset)
1906        .ok_or_else(|| CodecError::InvalidData("Invalid WBMP type".into()))?;
1907    let _ = read_wbmp_int(data, &mut offset)
1908        .ok_or_else(|| CodecError::InvalidData("Invalid WBMP header".into()))?;
1909
1910    // Read dimensions
1911    let width = read_wbmp_int(data, &mut offset)
1912        .ok_or_else(|| CodecError::InvalidData("Invalid WBMP width".into()))?;
1913    let height = read_wbmp_int(data, &mut offset)
1914        .ok_or_else(|| CodecError::InvalidData("Invalid WBMP height".into()))?;
1915
1916    Ok((
1917        i32::try_from(width).unwrap_or(i32::MAX),
1918        i32::try_from(height).unwrap_or(i32::MAX),
1919    ))
1920}
1921
1922// =============================================================================
1923// AVIF Codec
1924// =============================================================================
1925
1926/// AVIF decoder.
1927///
1928/// AVIF is a modern image format based on AV1 video codec, offering
1929/// excellent compression and quality.
1930pub struct AvifDecoder;
1931
1932impl AvifDecoder {
1933    /// Create a new AVIF decoder.
1934    #[must_use]
1935    pub const fn new() -> Self {
1936        Self
1937    }
1938}
1939
1940impl Default for AvifDecoder {
1941    fn default() -> Self {
1942        Self::new()
1943    }
1944}
1945
1946impl ImageDecoder for AvifDecoder {
1947    #[cfg(feature = "avif")]
1948    fn decode<R: Read>(&self, mut reader: R) -> CodecResult<Image> {
1949        use avif_decode::{Decoder, Image as AvifImage};
1950
1951        let mut data = Vec::new();
1952        reader
1953            .read_to_end(&mut data)
1954            .map_err(|e| CodecError::Io(e))?;
1955
1956        let decoder = Decoder::from_avif(&data)
1957            .map_err(|e| CodecError::DecodingError(format!("AVIF decode error: {:?}", e)))?;
1958
1959        let decoded = decoder
1960            .to_image()
1961            .map_err(|e| CodecError::DecodingError(format!("AVIF decode error: {:?}", e)))?;
1962
1963        // Extract dimensions and pixels based on the image variant
1964        let (width, height, pixels) = match decoded {
1965            AvifImage::Rgb8(img) => {
1966                let w = img.width();
1967                let h = img.height();
1968                let rgba: Vec<u8> = img.pixels().flat_map(|p| [p.r, p.g, p.b, 255]).collect();
1969                (w as i32, h as i32, rgba)
1970            }
1971            AvifImage::Rgba8(img) => {
1972                let w = img.width();
1973                let h = img.height();
1974                let rgba: Vec<u8> = img.pixels().flat_map(|p| [p.r, p.g, p.b, p.a]).collect();
1975                (w as i32, h as i32, rgba)
1976            }
1977            AvifImage::Rgb16(img) => {
1978                let w = img.width();
1979                let h = img.height();
1980                // Convert 16-bit to 8-bit
1981                let rgba: Vec<u8> = img
1982                    .pixels()
1983                    .flat_map(|p| [(p.r >> 8) as u8, (p.g >> 8) as u8, (p.b >> 8) as u8, 255])
1984                    .collect();
1985                (w as i32, h as i32, rgba)
1986            }
1987            AvifImage::Rgba16(img) => {
1988                let w = img.width();
1989                let h = img.height();
1990                // Convert 16-bit to 8-bit
1991                let rgba: Vec<u8> = img
1992                    .pixels()
1993                    .flat_map(|p| {
1994                        [
1995                            (p.r >> 8) as u8,
1996                            (p.g >> 8) as u8,
1997                            (p.b >> 8) as u8,
1998                            (p.a >> 8) as u8,
1999                        ]
2000                    })
2001                    .collect();
2002                (w as i32, h as i32, rgba)
2003            }
2004            AvifImage::Gray8(img) => {
2005                let w = img.width();
2006                let h = img.height();
2007                let rgba: Vec<u8> = img
2008                    .pixels()
2009                    .flat_map(|g| {
2010                        let v = g.value();
2011                        [v, v, v, 255]
2012                    })
2013                    .collect();
2014                (w as i32, h as i32, rgba)
2015            }
2016            AvifImage::Gray16(img) => {
2017                let w = img.width();
2018                let h = img.height();
2019                let rgba: Vec<u8> = img
2020                    .pixels()
2021                    .flat_map(|g| {
2022                        let g8 = (g.value() >> 8) as u8;
2023                        [g8, g8, g8, 255]
2024                    })
2025                    .collect();
2026                (w as i32, h as i32, rgba)
2027            }
2028        };
2029
2030        let info = crate::ImageInfo::new(
2031            width,
2032            height,
2033            skia_rs_core::ColorType::Rgba8888,
2034            skia_rs_core::AlphaType::Unpremul,
2035        );
2036
2037        Image::from_raster_data_owned(info, pixels, width as usize * 4)
2038            .ok_or_else(|| CodecError::DecodingError("Failed to create image".into()))
2039    }
2040
2041    #[cfg(not(feature = "avif"))]
2042    fn decode<R: Read>(&self, _reader: R) -> CodecResult<Image> {
2043        Err(CodecError::Unsupported(
2044            "AVIF decoding requires the 'avif' feature".into(),
2045        ))
2046    }
2047
2048    fn format(&self) -> ImageFormat {
2049        ImageFormat::Avif
2050    }
2051}
2052
2053/// AVIF encoder.
2054///
2055/// Encodes images to AVIF format using the rav1e AV1 encoder.
2056pub struct AvifEncoder {
2057    quality: u8,
2058    speed: u8,
2059}
2060
2061impl AvifEncoder {
2062    /// Create a new AVIF encoder with default settings.
2063    #[must_use]
2064    pub const fn new() -> Self {
2065        Self {
2066            quality: 80,
2067            speed: 6, // Balance between speed and quality
2068        }
2069    }
2070
2071    /// Set the quality (0-100, higher is better quality but larger file).
2072    #[must_use]
2073    pub fn with_quality(mut self, quality: u8) -> Self {
2074        self.quality = quality.min(100);
2075        self
2076    }
2077
2078    /// Set the encoding speed (1-10, higher is faster but lower quality).
2079    #[must_use]
2080    pub fn with_speed(mut self, speed: u8) -> Self {
2081        self.speed = speed.clamp(1, 10);
2082        self
2083    }
2084}
2085
2086impl Default for AvifEncoder {
2087    fn default() -> Self {
2088        Self::new()
2089    }
2090}
2091
2092impl ImageEncoder for AvifEncoder {
2093    #[cfg(feature = "avif")]
2094    fn encode<W: Write>(&self, image: &Image, mut writer: W) -> CodecResult<()> {
2095        use ravif::RGBA8;
2096        use ravif::{Encoder, Img};
2097
2098        let width = image.width() as usize;
2099        let height = image.height() as usize;
2100
2101        let pixels = image
2102            .peek_pixels()
2103            .ok_or_else(|| CodecError::EncodingError("Failed to access pixels".into()))?;
2104
2105        // Convert to RGBA pixels for ravif
2106        let rgba_pixels: Vec<RGBA8> = pixels
2107            .chunks_exact(4)
2108            .map(|c| RGBA8::new(c[0], c[1], c[2], c[3]))
2109            .collect();
2110
2111        let img = Img::new(rgba_pixels.as_slice(), width, height);
2112
2113        let encoder = Encoder::new()
2114            .with_quality(self.quality as f32)
2115            .with_speed(self.speed);
2116
2117        let result = encoder
2118            .encode_rgba(img)
2119            .map_err(|e| CodecError::EncodingError(format!("AVIF encode error: {:?}", e)))?;
2120
2121        writer
2122            .write_all(&result.avif_file)
2123            .map_err(|e| CodecError::Io(e))?;
2124
2125        Ok(())
2126    }
2127
2128    #[cfg(not(feature = "avif"))]
2129    fn encode<W: Write>(&self, _image: &Image, _writer: W) -> CodecResult<()> {
2130        Err(CodecError::Unsupported(
2131            "AVIF encoding requires the 'avif' feature".into(),
2132        ))
2133    }
2134
2135    fn format(&self) -> ImageFormat {
2136        ImageFormat::Avif
2137    }
2138}
2139
2140/// Get AVIF dimensions from data.
2141#[cfg(feature = "avif")]
2142fn get_avif_dimensions(data: &[u8]) -> CodecResult<(i32, i32)> {
2143    use avif_decode::{Decoder, Image as AvifImage};
2144    let decoder = Decoder::from_avif(data)
2145        .map_err(|e| CodecError::DecodingError(format!("AVIF decode error: {:?}", e)))?;
2146    let image = decoder
2147        .to_image()
2148        .map_err(|e| CodecError::DecodingError(format!("AVIF decode error: {:?}", e)))?;
2149
2150    let (w, h) = match image {
2151        AvifImage::Rgb8(img) => (img.width(), img.height()),
2152        AvifImage::Rgba8(img) => (img.width(), img.height()),
2153        AvifImage::Rgb16(img) => (img.width(), img.height()),
2154        AvifImage::Rgba16(img) => (img.width(), img.height()),
2155        AvifImage::Gray8(img) => (img.width(), img.height()),
2156        AvifImage::Gray16(img) => (img.width(), img.height()),
2157    };
2158    Ok((w as i32, h as i32))
2159}
2160
2161#[cfg(not(feature = "avif"))]
2162fn get_avif_dimensions(_data: &[u8]) -> CodecResult<(i32, i32)> {
2163    Err(CodecError::Unsupported(
2164        "AVIF support requires the 'avif' feature".into(),
2165    ))
2166}
2167
2168// =============================================================================
2169// RAW Codec
2170// =============================================================================
2171
2172/// Bayer color-filter-array pattern layout for a RAW sensor image.
2173///
2174/// The four variants cover the four phase offsets of the 2x2 Bayer
2175/// mosaic. Pattern names read top-left → top-right → bottom-left →
2176/// bottom-right. `Rggb` is by far the most common.
2177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2178pub enum BayerPattern {
2179    /// Red, Green, Green, Blue (top-left order).
2180    Rggb,
2181    /// Blue, Green, Green, Red.
2182    Bggr,
2183    /// Green, Red, Blue, Green.
2184    Grbg,
2185    /// Green, Blue, Red, Green.
2186    Gbrg,
2187}
2188
2189/// Pick the channel (R=0, G=1, B=2) at position (x, y) given the
2190/// pattern's 2x2 top-left orientation.
2191#[inline]
2192fn bayer_channel_at(pattern: BayerPattern, x: usize, y: usize) -> u8 {
2193    let (r, g0, g1, b) = match pattern {
2194        BayerPattern::Rggb => (0u8, 1u8, 1u8, 2u8),
2195        BayerPattern::Bggr => (2, 1, 1, 0),
2196        BayerPattern::Grbg => (1, 0, 2, 1),
2197        BayerPattern::Gbrg => (1, 2, 0, 1),
2198    };
2199    match (x % 2, y % 2) {
2200        (0, 0) => r,
2201        (1, 0) => g0,
2202        (0, 1) => g1,
2203        (1, 1) => b,
2204        _ => unreachable!(),
2205    }
2206}
2207
2208/// Convert a pixel coordinate to `isize` for demosaic neighbor lookups,
2209/// saturating (never panicking) on the practically unreachable case of a
2210/// coordinate beyond `isize::MAX` — a buffer that large could not exist.
2211#[inline]
2212fn bayer_to_isize(v: usize) -> isize {
2213    isize::try_from(v).unwrap_or(isize::MAX)
2214}
2215
2216/// Fetch a sample at `(x, y)`, clamping out-of-range coordinates to the
2217/// nearest edge pixel.
2218#[inline]
2219fn bayer_clamp_fetch(raw: &[u16], x: isize, y: isize, w: usize, h: usize) -> u32 {
2220    let max_x = bayer_to_isize(w) - 1;
2221    let max_y = bayer_to_isize(h) - 1;
2222    let cx = usize::try_from(x.clamp(0, max_x)).unwrap_or(0);
2223    let cy = usize::try_from(y.clamp(0, max_y)).unwrap_or(0);
2224    u32::from(raw[cy * w + cx])
2225}
2226
2227/// Bilinear demosaic a 16-bit Bayer-pattern single-channel sensor image
2228/// into an 8-bit RGB buffer.
2229///
2230/// Each output pixel holds the sensor's directly-sampled channel at its
2231/// Bayer position, plus bilinearly-interpolated values for the two
2232/// missing channels:
2233///
2234/// - R/B pixels: green is the 4-neighbor cross average (N/S/E/W); the
2235///   other-color channel is the 4-neighbor diagonal average (NW/NE/SW/SE).
2236/// - G pixels: the two missing channels come from the two direct
2237///   neighbors that carry them — one pair horizontal, one pair vertical
2238///   (which axis carries which channel depends on the row parity).
2239///
2240/// This is a baseline demosaic — far less sophisticated than
2241/// Malvar-He-Cutler, VNG, or AHD — but correct for uniform patches, well
2242/// behaved at edges of the frame (clamped neighborhood), and produces a
2243/// predictable linear-light RGB image. Proprietary RAW file parsing
2244/// (CR2, NEF, ARW) is outside the scope of this helper; feed already-
2245/// parsed sensor samples in.
2246///
2247/// The output is 8-bit per channel: the high byte of each 16-bit
2248/// intermediate value. Input values are treated as linear (no white
2249/// balance or color matrix applied). `width * height` must equal
2250/// `raw.len()`.
2251///
2252/// Returns an empty vector if the input length does not match
2253/// `width * height` — this keeps the helper safe to call without
2254/// propagating `Result` through every RAW pipeline.
2255#[must_use]
2256#[allow(
2257    clippy::many_single_char_names,
2258    reason = "r/g/b/c/v name Bayer color-plane samples; matches the RGB/channel-index \
2259    convention used throughout the demosaic literature and is clearer than verbose aliases"
2260)]
2261pub fn demosaic_bayer(raw: &[u16], width: usize, height: usize, pattern: BayerPattern) -> Vec<u8> {
2262    if width == 0 || height == 0 || raw.len() != width * height {
2263        return Vec::new();
2264    }
2265
2266    let mut out = vec![0u8; width * height * 3];
2267
2268    for y in 0..height {
2269        let yi = bayer_to_isize(y);
2270        for x in 0..width {
2271            let xi = bayer_to_isize(x);
2272            let c = bayer_channel_at(pattern, x, y);
2273            let v = u32::from(raw[y * width + x]);
2274
2275            // Cross = direct N/S/E/W neighbors; diag = NW/NE/SW/SE.
2276            let cross = (bayer_clamp_fetch(raw, xi - 1, yi, width, height)
2277                + bayer_clamp_fetch(raw, xi + 1, yi, width, height)
2278                + bayer_clamp_fetch(raw, xi, yi - 1, width, height)
2279                + bayer_clamp_fetch(raw, xi, yi + 1, width, height))
2280                / 4;
2281            let diag = (bayer_clamp_fetch(raw, xi - 1, yi - 1, width, height)
2282                + bayer_clamp_fetch(raw, xi + 1, yi - 1, width, height)
2283                + bayer_clamp_fetch(raw, xi - 1, yi + 1, width, height)
2284                + bayer_clamp_fetch(raw, xi + 1, yi + 1, width, height))
2285                / 4;
2286            let horiz = u32::midpoint(
2287                bayer_clamp_fetch(raw, xi - 1, yi, width, height),
2288                bayer_clamp_fetch(raw, xi + 1, yi, width, height),
2289            );
2290            let vert = u32::midpoint(
2291                bayer_clamp_fetch(raw, xi, yi - 1, width, height),
2292                bayer_clamp_fetch(raw, xi, yi + 1, width, height),
2293            );
2294
2295            // Determine the green-axis layout: which of the two G
2296            // neighbor directions carries R vs B. The horizontal and
2297            // vertical neighbors of a green pixel lie one step in each
2298            // axis, which always lands at a pixel of the opposite
2299            // Bayer parity — use pattern phase math (x ^ 1, y ^ 1)
2300            // directly so this is independent of image bounds (the
2301            // clamp-to-edge happens inside horiz/vert via clamp_fetch).
2302            let (r, g, b) = if c == 1 {
2303                let horiz_ch = bayer_channel_at(pattern, x ^ 1, y);
2304                let vert_ch = bayer_channel_at(pattern, x, y ^ 1);
2305                let mut r = 0u32;
2306                let mut b = 0u32;
2307                if horiz_ch == 0 {
2308                    r = horiz;
2309                } else if horiz_ch == 2 {
2310                    b = horiz;
2311                }
2312                if vert_ch == 0 {
2313                    r = vert;
2314                } else if vert_ch == 2 {
2315                    b = vert;
2316                }
2317                (r, v, b)
2318            } else if c == 0 {
2319                // Red pixel: G = cross, B = diag, R = direct.
2320                (v, cross, diag)
2321            } else {
2322                // Blue pixel: G = cross, R = diag, B = direct.
2323                (diag, cross, v)
2324            };
2325
2326            // High byte of 16-bit intermediate; u32 arithmetic saturates
2327            // to 65535 in practice because no neighbor can exceed u16.
2328            let idx = (y * width + x) * 3;
2329            out[idx] = u8::try_from(r.min(0xFFFF) >> 8).unwrap_or(0xFF);
2330            out[idx + 1] = u8::try_from(g.min(0xFFFF) >> 8).unwrap_or(0xFF);
2331            out[idx + 2] = u8::try_from(b.min(0xFFFF) >> 8).unwrap_or(0xFF);
2332        }
2333    }
2334
2335    out
2336}
2337
2338/// Convenience: [`demosaic_bayer`] with the most common [`BayerPattern::Rggb`]
2339/// pattern.
2340#[inline]
2341#[must_use]
2342pub fn demosaic_bayer_rggb(raw: &[u16], width: usize, height: usize) -> Vec<u8> {
2343    demosaic_bayer(raw, width, height, BayerPattern::Rggb)
2344}
2345
2346/// Camera RAW decoder.
2347///
2348/// Decodes camera RAW formats from various manufacturers including
2349/// Canon, Nikon, Sony, Fuji, and many others.
2350pub struct RawDecoder;
2351
2352impl RawDecoder {
2353    /// Create a new RAW decoder.
2354    #[must_use]
2355    pub const fn new() -> Self {
2356        Self
2357    }
2358}
2359
2360impl Default for RawDecoder {
2361    fn default() -> Self {
2362        Self::new()
2363    }
2364}
2365
2366impl ImageDecoder for RawDecoder {
2367    #[cfg(feature = "raw")]
2368    fn decode<R: Read>(&self, mut reader: R) -> CodecResult<Image> {
2369        use std::io::Cursor;
2370
2371        let mut data = Vec::new();
2372        reader
2373            .read_to_end(&mut data)
2374            .map_err(|e| CodecError::Io(e))?;
2375
2376        let mut cursor = Cursor::new(&data);
2377        let raw_image = rawloader::decode(&mut cursor)
2378            .map_err(|e| CodecError::DecodingError(format!("RAW decode error: {:?}", e)))?;
2379
2380        // Get dimensions
2381        let width = raw_image.width as i32;
2382        let height = raw_image.height as i32;
2383
2384        // Convert RAW data to RGB
2385        // RAW images are typically in a Bayer pattern, we need to demosaic
2386        let pixels = demosaic_raw(&raw_image)?;
2387
2388        let info = crate::ImageInfo::new(
2389            width,
2390            height,
2391            skia_rs_core::ColorType::Rgba8888,
2392            skia_rs_core::AlphaType::Opaque,
2393        );
2394
2395        Image::from_raster_data_owned(info, pixels, width as usize * 4)
2396            .ok_or_else(|| CodecError::DecodingError("Failed to create image".into()))
2397    }
2398
2399    #[cfg(not(feature = "raw"))]
2400    fn decode<R: Read>(&self, _reader: R) -> CodecResult<Image> {
2401        Err(CodecError::Unsupported(
2402            "RAW decoding requires the 'raw' feature".into(),
2403        ))
2404    }
2405
2406    fn format(&self) -> ImageFormat {
2407        ImageFormat::Raw
2408    }
2409}
2410
2411/// Try to detect one of the four canonical Bayer patterns from the
2412/// `rawloader::CFA` 2x2 layout. Returns `None` for non-Bayer CFAs such
2413/// as X-Trans or monochrome.
2414#[cfg(feature = "raw")]
2415fn detect_bayer_pattern(cfa: &rawloader::CFA) -> Option<BayerPattern> {
2416    // rawloader::CFA::color_at(row, col) returns 0=R, 1=G, 2=B.
2417    let tl = cfa.color_at(0, 0);
2418    let tr = cfa.color_at(0, 1);
2419    let bl = cfa.color_at(1, 0);
2420    let br = cfa.color_at(1, 1);
2421    match (tl, tr, bl, br) {
2422        (0, 1, 1, 2) => Some(BayerPattern::Rggb),
2423        (2, 1, 1, 0) => Some(BayerPattern::Bggr),
2424        (1, 0, 2, 1) => Some(BayerPattern::Grbg),
2425        (1, 2, 0, 1) => Some(BayerPattern::Gbrg),
2426        _ => None,
2427    }
2428}
2429
2430/// Demosaic a RAW image to RGBA.
2431///
2432/// For Bayer-pattern sensors this routes through the generic
2433/// [`demosaic_bayer`] helper after black-level subtraction and white-
2434/// level normalization to 16-bit range. For non-Bayer CFAs (X-Trans,
2435/// etc.) it falls back to the legacy per-channel neighbor-average path
2436/// so unusual sensors still decode rather than erroring.
2437#[cfg(feature = "raw")]
2438fn demosaic_raw(raw: &rawloader::RawImage) -> CodecResult<Vec<u8>> {
2439    let width = raw.width;
2440    let height = raw.height;
2441
2442    // Get the raw data
2443    let data = match &raw.data {
2444        rawloader::RawImageData::Integer(d) => d,
2445        rawloader::RawImageData::Float(_) => {
2446            return Err(CodecError::Unsupported(
2447                "Float RAW data not yet supported".into(),
2448            ));
2449        }
2450    };
2451
2452    if let Some(pattern) = detect_bayer_pattern(&raw.cfa) {
2453        // Fast path: bilinear demosaic via the public helper. Produces
2454        // an RGB buffer we expand to RGBA with opaque alpha. Normalize
2455        // each sample into the 0..65535 range first so the demosaic
2456        // helper sees a consistent scale regardless of the sensor's
2457        // native bit depth.
2458        let black = raw.blacklevels[0] as f32;
2459        let white = raw.whitelevels[0] as f32;
2460        let range = if white > black {
2461            white - black
2462        } else {
2463            65535.0
2464        };
2465        let normalized: Vec<u16> = data
2466            .iter()
2467            .map(|&v| (((v as f32 - black) / range * 65535.0).clamp(0.0, 65535.0)) as u16)
2468            .collect();
2469        let rgb = demosaic_bayer(&normalized, width, height, pattern);
2470        if rgb.len() != width * height * 3 {
2471            return Err(CodecError::DecodingError(
2472                "Bayer demosaic produced unexpected buffer size".into(),
2473            ));
2474        }
2475        let mut output = vec![0u8; width * height * 4];
2476        for i in 0..(width * height) {
2477            output[i * 4] = rgb[i * 3];
2478            output[i * 4 + 1] = rgb[i * 3 + 1];
2479            output[i * 4 + 2] = rgb[i * 3 + 2];
2480            output[i * 4 + 3] = 255;
2481        }
2482        return Ok(output);
2483    }
2484
2485    // Fallback: unknown CFA layout. Sample direct channel + 3x3
2486    // neighbor average for the two missing channels — this is the
2487    // legacy path that predates the bilinear helper.
2488    let mut output = vec![0u8; width * height * 4];
2489
2490    // Simple demosaicing - convert to grayscale for simplicity
2491    // A full implementation would do proper Bayer demosaicing
2492    let cfa = &raw.cfa;
2493    let black = raw.blacklevels[0] as f32;
2494    let white = raw.whitelevels[0] as f32;
2495    let range = if white > black {
2496        white - black
2497    } else {
2498        65535.0
2499    };
2500
2501    // Color indices: 0=Red, 1=Green, 2=Blue
2502    const RED: usize = 0;
2503    const GREEN: usize = 1;
2504    const BLUE: usize = 2;
2505
2506    for y in 0..height {
2507        for x in 0..width {
2508            let idx = y * width + x;
2509            let out_idx = idx * 4;
2510
2511            // Get color index at this position (returns 0, 1, or 2)
2512            let color = cfa.color_at(y, x);
2513
2514            // Get raw value normalized to 0-255
2515            let raw_val = data[idx] as f32;
2516            let normalized = ((raw_val - black) / range * 255.0).clamp(0.0, 255.0) as u8;
2517
2518            // Simple nearest-neighbor for demo purposes
2519            match color {
2520                RED => {
2521                    output[out_idx] = normalized;
2522                    output[out_idx + 1] = get_neighbor_avg_by_color(
2523                        data, x, y, width, height, cfa, GREEN, black, range,
2524                    );
2525                    output[out_idx + 2] = get_neighbor_avg_by_color(
2526                        data, x, y, width, height, cfa, BLUE, black, range,
2527                    );
2528                }
2529                GREEN => {
2530                    output[out_idx] = get_neighbor_avg_by_color(
2531                        data, x, y, width, height, cfa, RED, black, range,
2532                    );
2533                    output[out_idx + 1] = normalized;
2534                    output[out_idx + 2] = get_neighbor_avg_by_color(
2535                        data, x, y, width, height, cfa, BLUE, black, range,
2536                    );
2537                }
2538                BLUE => {
2539                    output[out_idx] = get_neighbor_avg_by_color(
2540                        data, x, y, width, height, cfa, RED, black, range,
2541                    );
2542                    output[out_idx + 1] = get_neighbor_avg_by_color(
2543                        data, x, y, width, height, cfa, GREEN, black, range,
2544                    );
2545                    output[out_idx + 2] = normalized;
2546                }
2547                _ => {
2548                    // Unknown CFA pattern, just use grayscale
2549                    output[out_idx] = normalized;
2550                    output[out_idx + 1] = normalized;
2551                    output[out_idx + 2] = normalized;
2552                }
2553            }
2554            output[out_idx + 3] = 255; // Alpha
2555        }
2556    }
2557
2558    Ok(output)
2559}
2560
2561/// Get average of neighboring pixels of a specific color index.
2562#[cfg(feature = "raw")]
2563fn get_neighbor_avg_by_color(
2564    data: &[u16],
2565    x: usize,
2566    y: usize,
2567    width: usize,
2568    height: usize,
2569    cfa: &rawloader::CFA,
2570    target_color: usize,
2571    black: f32,
2572    range: f32,
2573) -> u8 {
2574    let mut sum = 0.0;
2575    let mut count = 0;
2576
2577    // Check 3x3 neighborhood
2578    for dy in -1i32..=1 {
2579        for dx in -1i32..=1 {
2580            let nx = x as i32 + dx;
2581            let ny = y as i32 + dy;
2582
2583            if nx >= 0 && nx < width as i32 && ny >= 0 && ny < height as i32 {
2584                let nx = nx as usize;
2585                let ny = ny as usize;
2586
2587                if cfa.color_at(ny, nx) == target_color {
2588                    let idx = ny * width + nx;
2589                    let raw_val = data[idx] as f32;
2590                    sum += (raw_val - black) / range * 255.0;
2591                    count += 1;
2592                }
2593            }
2594        }
2595    }
2596
2597    if count > 0 {
2598        (sum / count as f32).clamp(0.0, 255.0) as u8
2599    } else {
2600        128 // Fallback if no neighbors found
2601    }
2602}
2603
2604/// Get RAW dimensions from data.
2605#[cfg(feature = "raw")]
2606fn get_raw_dimensions(data: &[u8]) -> CodecResult<(i32, i32)> {
2607    use std::io::Cursor;
2608    let mut cursor = Cursor::new(data);
2609    let raw = rawloader::decode(&mut cursor)
2610        .map_err(|e| CodecError::DecodingError(format!("RAW decode error: {:?}", e)))?;
2611    Ok((raw.width as i32, raw.height as i32))
2612}
2613
2614#[cfg(not(feature = "raw"))]
2615fn get_raw_dimensions(_data: &[u8]) -> CodecResult<(i32, i32)> {
2616    Err(CodecError::Unsupported(
2617        "RAW support requires the 'raw' feature".into(),
2618    ))
2619}
2620
2621// =============================================================================
2622// Utility Functions
2623// =============================================================================
2624
2625/// Decode an image from bytes, auto-detecting the format.
2626///
2627/// # Errors
2628/// Returns [`CodecError::Unsupported`] if the format cannot be detected
2629/// from `data`, or the detected format's decoder error otherwise.
2630pub fn decode_image(data: &[u8]) -> CodecResult<Image> {
2631    let format = ImageFormat::from_magic(data);
2632
2633    match format {
2634        ImageFormat::Png => PngDecoder::new().decode_bytes(data),
2635        ImageFormat::Jpeg => JpegDecoder::new().decode_bytes(data),
2636        ImageFormat::Gif => GifDecoder::new().decode_bytes(data),
2637        ImageFormat::WebP => WebpDecoder::new().decode_bytes(data),
2638        ImageFormat::Bmp => BmpDecoder::new().decode_bytes(data),
2639        ImageFormat::Ico => IcoDecoder::new().decode_bytes(data),
2640        ImageFormat::Wbmp => WbmpDecoder::new().decode_bytes(data),
2641        ImageFormat::Avif => AvifDecoder::new().decode_bytes(data),
2642        ImageFormat::Raw => RawDecoder::new().decode_bytes(data),
2643        ImageFormat::Unknown => Err(CodecError::Unsupported(format!(
2644            "Format {format:?} not supported"
2645        ))),
2646    }
2647}
2648
2649/// Get the image dimensions without fully decoding.
2650///
2651/// # Errors
2652/// Returns [`CodecError::Unsupported`] if the format cannot be detected
2653/// or has no dimension probe, or the detected format's probe error
2654/// otherwise.
2655pub fn get_image_dimensions(data: &[u8]) -> CodecResult<(i32, i32)> {
2656    let format = ImageFormat::from_magic(data);
2657
2658    match format {
2659        ImageFormat::Png => get_png_dimensions(data),
2660        ImageFormat::Jpeg => get_jpeg_dimensions(data),
2661        ImageFormat::Bmp => get_bmp_dimensions(data),
2662        ImageFormat::Ico => get_ico_dimensions(data),
2663        ImageFormat::Wbmp => get_wbmp_dimensions(data),
2664        ImageFormat::Avif => get_avif_dimensions(data),
2665        ImageFormat::Raw => get_raw_dimensions(data),
2666        _ => Err(CodecError::Unsupported(format!(
2667            "Format {format:?} not supported"
2668        ))),
2669    }
2670}
2671
2672fn get_png_dimensions(data: &[u8]) -> CodecResult<(i32, i32)> {
2673    // PNG IHDR chunk starts at byte 8, width at offset 16, height at offset 20
2674    if data.len() < 24 {
2675        return Err(CodecError::InvalidData("PNG too short".into()));
2676    }
2677
2678    let width = i32::try_from(u32::from_be_bytes([data[16], data[17], data[18], data[19]]))
2679        .map_err(|_| CodecError::InvalidData("PNG width exceeds i32 range".into()))?;
2680    let height = i32::try_from(u32::from_be_bytes([data[20], data[21], data[22], data[23]]))
2681        .map_err(|_| CodecError::InvalidData("PNG height exceeds i32 range".into()))?;
2682
2683    Ok((width, height))
2684}
2685
2686/// Returns true if `marker` is a Start-Of-Frame marker that carries frame
2687/// dimensions. SOF markers span C0-CF *except* C4 (DHT), C8 (JPG), and CC
2688/// (DAC), which are not frame headers.
2689const fn is_jpeg_sof_marker(marker: u8) -> bool {
2690    matches!(marker,
2691        0xC0..=0xC3 | 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF)
2692}
2693
2694fn get_jpeg_dimensions(data: &[u8]) -> CodecResult<(i32, i32)> {
2695    // Walk the marker stream looking for any SOF header. Each marker is
2696    // `0xFF` followed by a marker byte; multiple `0xFF` fill bytes may
2697    // precede the marker byte.
2698    let mut i = 2;
2699    while i + 1 < data.len() {
2700        if data[i] != 0xFF {
2701            i += 1;
2702            continue;
2703        }
2704        // Consume any run of 0xFF fill bytes.
2705        let mut marker = data[i + 1];
2706        let mut j = i + 1;
2707        while marker == 0xFF && j + 1 < data.len() {
2708            j += 1;
2709            marker = data[j];
2710        }
2711
2712        // Standalone markers have no length payload: TEM (0x01) and
2713        // SOI/EOI/RST0-7 (0xD0-0xD9). Also skip padding 0x00.
2714        if marker == 0x00 || marker == 0x01 || (0xD0..=0xD9).contains(&marker) {
2715            i = j + 1;
2716            continue;
2717        }
2718
2719        // All remaining markers carry a 2-byte big-endian segment length
2720        // (which includes the length field itself).
2721        if j + 3 >= data.len() {
2722            break;
2723        }
2724        let len = u16::from_be_bytes([data[j + 1], data[j + 2]]) as usize;
2725
2726        if is_jpeg_sof_marker(marker) {
2727            // Layout from the marker byte at `j`: length(2) at j+1..j+3,
2728            // then the SOF payload precision(1) height(2) width(2).
2729            if j + 7 < data.len() {
2730                let height = i32::from(u16::from_be_bytes([data[j + 4], data[j + 5]]));
2731                let width = i32::from(u16::from_be_bytes([data[j + 6], data[j + 7]]));
2732                return Ok((width, height));
2733            }
2734            break;
2735        }
2736
2737        if len < 2 {
2738            break;
2739        }
2740        i = j + 1 + len;
2741    }
2742
2743    Err(CodecError::InvalidData(
2744        "Could not find JPEG dimensions".into(),
2745    ))
2746}
2747
2748fn get_bmp_dimensions(data: &[u8]) -> CodecResult<(i32, i32)> {
2749    if data.len() < 26 {
2750        return Err(CodecError::InvalidData("BMP too short".into()));
2751    }
2752
2753    let width = i32::from_le_bytes([data[18], data[19], data[20], data[21]]);
2754    // Height is signed (negative = top-down). Use `unsigned_abs` so
2755    // `i32::MIN` does not panic (`.abs()` would overflow); its magnitude
2756    // (2^31) doesn't fit back in `i32`, so saturate to `i32::MAX` rather
2757    // than wrapping back to a negative value.
2758    let height_abs = i32::from_le_bytes([data[22], data[23], data[24], data[25]]).unsigned_abs();
2759    let height = i32::try_from(height_abs).unwrap_or(i32::MAX);
2760
2761    Ok((width, height))
2762}
2763
2764fn get_ico_dimensions(data: &[u8]) -> CodecResult<(i32, i32)> {
2765    if data.len() < 22 {
2766        return Err(CodecError::InvalidData("ICO too short".into()));
2767    }
2768
2769    let image_count = u16::from_le_bytes([data[4], data[5]]) as usize;
2770    if image_count == 0 {
2771        return Err(CodecError::InvalidData("ICO has no images".into()));
2772    }
2773
2774    // Return the largest image dimensions
2775    let mut best_width = 0i32;
2776    let mut best_height = 0i32;
2777
2778    for i in 0..image_count {
2779        let entry_offset = 6 + i * 16;
2780        if entry_offset + 8 > data.len() {
2781            break;
2782        }
2783
2784        let width = if data[entry_offset] == 0 {
2785            256
2786        } else {
2787            i32::from(data[entry_offset])
2788        };
2789        let height = if data[entry_offset + 1] == 0 {
2790            256
2791        } else {
2792            i32::from(data[entry_offset + 1])
2793        };
2794
2795        if width * height > best_width * best_height {
2796            best_width = width;
2797            best_height = height;
2798        }
2799    }
2800
2801    Ok((best_width, best_height))
2802}
2803
2804#[cfg(test)]
2805mod tests {
2806    use super::*;
2807
2808    #[test]
2809    fn test_format_detection() {
2810        // PNG magic bytes
2811        let png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
2812        assert_eq!(ImageFormat::from_magic(&png), ImageFormat::Png);
2813
2814        // JPEG magic bytes (need at least 8 bytes for magic detection)
2815        let jpeg = [0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46];
2816        assert_eq!(ImageFormat::from_magic(&jpeg), ImageFormat::Jpeg);
2817
2818        // GIF magic bytes (need at least 8 bytes)
2819        let gif = b"GIF89a\x00\x00";
2820        assert_eq!(ImageFormat::from_magic(gif), ImageFormat::Gif);
2821
2822        // WebP magic bytes
2823        let webp = b"RIFF\x00\x00\x00\x00WEBP";
2824        assert_eq!(ImageFormat::from_magic(webp), ImageFormat::WebP);
2825
2826        // BMP magic bytes
2827        let bmp = b"BM\x00\x00\x00\x00\x00\x00";
2828        assert_eq!(ImageFormat::from_magic(bmp), ImageFormat::Bmp);
2829
2830        // ICO magic bytes
2831        let ico = [0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x10];
2832        assert_eq!(ImageFormat::from_magic(&ico), ImageFormat::Ico);
2833
2834        // Unknown (need at least 8 bytes to test)
2835        let unknown = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
2836        assert_eq!(ImageFormat::from_magic(&unknown), ImageFormat::Unknown);
2837    }
2838
2839    #[test]
2840    fn test_format_extensions() {
2841        assert_eq!(ImageFormat::Png.extension(), "png");
2842        assert_eq!(ImageFormat::Jpeg.extension(), "jpg");
2843        assert_eq!(ImageFormat::Gif.extension(), "gif");
2844        assert_eq!(ImageFormat::Bmp.extension(), "bmp");
2845        assert_eq!(ImageFormat::Ico.extension(), "ico");
2846    }
2847
2848    #[test]
2849    fn test_format_mime_types() {
2850        assert_eq!(ImageFormat::Png.mime_type(), "image/png");
2851        assert_eq!(ImageFormat::Jpeg.mime_type(), "image/jpeg");
2852        assert_eq!(ImageFormat::Bmp.mime_type(), "image/bmp");
2853        assert_eq!(ImageFormat::Ico.mime_type(), "image/x-icon");
2854    }
2855
2856    #[test]
2857    fn test_encoder_quality() {
2858        let q = EncoderQuality::new(75);
2859        assert_eq!(q.value(), 75);
2860
2861        let q_over = EncoderQuality::new(150);
2862        assert_eq!(q_over.value(), 100);
2863    }
2864
2865    #[test]
2866    fn test_bmp_encode_decode_roundtrip() {
2867        // Create a simple 2x2 image
2868        let info = crate::ImageInfo::new(
2869            2,
2870            2,
2871            skia_rs_core::ColorType::Rgba8888,
2872            skia_rs_core::AlphaType::Unpremul,
2873        );
2874        let pixels = vec![
2875            255, 0, 0, 255, // Red
2876            0, 255, 0, 255, // Green
2877            0, 0, 255, 255, // Blue
2878            255, 255, 0, 255, // Yellow
2879        ];
2880        let image = Image::from_raster_data_owned(info, pixels, 8).unwrap();
2881
2882        // Encode to BMP
2883        let encoder = BmpEncoder::new();
2884        let bmp_bytes = encoder.encode_bytes(&image).unwrap();
2885
2886        // Verify format detection
2887        assert_eq!(ImageFormat::from_magic(&bmp_bytes), ImageFormat::Bmp);
2888
2889        // Decode back
2890        let decoder = BmpDecoder::new();
2891        let round_tripped = decoder.decode_bytes(&bmp_bytes).unwrap();
2892
2893        // Verify dimensions
2894        assert_eq!(round_tripped.width(), 2);
2895        assert_eq!(round_tripped.height(), 2);
2896    }
2897
2898    #[test]
2899    fn test_bmp_dimensions() {
2900        // Create a simple BMP header for a 100x50 image
2901        let mut bmp = vec![0u8; 54];
2902        bmp[0] = b'B';
2903        bmp[1] = b'M';
2904        // Width at offset 18-21
2905        bmp[18..22].copy_from_slice(&100i32.to_le_bytes());
2906        // Height at offset 22-25
2907        bmp[22..26].copy_from_slice(&50i32.to_le_bytes());
2908
2909        let dims = get_bmp_dimensions(&bmp).unwrap();
2910        assert_eq!(dims, (100, 50));
2911    }
2912
2913    /// Build a small checkerboard Image for round-trip tests.
2914    fn test_checkerboard(w: i32, h: i32) -> Image {
2915        let info = crate::ImageInfo::new(
2916            w,
2917            h,
2918            skia_rs_core::ColorType::Rgba8888,
2919            skia_rs_core::AlphaType::Unpremul,
2920        );
2921        let w_usize = usize::try_from(w).unwrap();
2922        let h_usize = usize::try_from(h).unwrap();
2923        let row_bytes = w_usize * 4;
2924        let mut pixels = vec![0u8; h_usize * row_bytes];
2925        for y in 0..h_usize {
2926            for x in 0..w_usize {
2927                let off = y * row_bytes + x * 4;
2928                let on = ((x + y) & 1) == 0;
2929                pixels[off] = if on { 255 } else { 0 };
2930                pixels[off + 1] = if on { 0 } else { 255 };
2931                pixels[off + 2] = 0;
2932                pixels[off + 3] = 255;
2933            }
2934        }
2935        Image::from_raster_data_owned(info, pixels, row_bytes).unwrap()
2936    }
2937
2938    #[cfg(feature = "png")]
2939    #[test]
2940    fn test_png_encode_decode_roundtrip() {
2941        let image = test_checkerboard(4, 4);
2942        let encoded = PngEncoder::new().encode_bytes(&image).unwrap();
2943        assert_eq!(ImageFormat::from_magic(&encoded), ImageFormat::Png);
2944
2945        let decoded = PngDecoder::new().decode_bytes(&encoded).unwrap();
2946        assert_eq!(decoded.dimensions(), (4, 4));
2947
2948        // PNG is lossless; pixel values should survive exactly. Alpha
2949        // interpretation may differ, so compare RGB channels per pixel.
2950        let src_pixels = image.peek_pixels().unwrap();
2951        let dst_pixels = decoded.peek_pixels().unwrap();
2952        for y in 0..4 {
2953            for x in 0..4 {
2954                let src_off = (y * 4 + x) * 4;
2955                let dst_off = (y * 4 + x) * 4;
2956                assert_eq!(
2957                    src_pixels[src_off..src_off + 3],
2958                    dst_pixels[dst_off..dst_off + 3],
2959                    "pixel mismatch at ({x}, {y})"
2960                );
2961            }
2962        }
2963    }
2964
2965    #[cfg(feature = "jpeg")]
2966    #[test]
2967    fn test_jpeg_encode_decode_roundtrip() {
2968        // JPEG is lossy, but round-trip should preserve dimensions and
2969        // yield a reasonable approximation. Use a larger, smoother source
2970        // so quantization noise stays bounded.
2971        let image = test_checkerboard(16, 16);
2972        let encoded = JpegEncoder::new().encode_bytes(&image).unwrap();
2973        assert_eq!(ImageFormat::from_magic(&encoded), ImageFormat::Jpeg);
2974
2975        let decoded = JpegDecoder::new().decode_bytes(&encoded).unwrap();
2976        assert_eq!(decoded.dimensions(), (16, 16));
2977    }
2978
2979    #[cfg(feature = "webp")]
2980    #[test]
2981    fn test_webp_encode_decode_roundtrip() {
2982        let image = test_checkerboard(8, 8);
2983        let encoded = WebpEncoder::lossless().encode_bytes(&image).unwrap();
2984        assert_eq!(ImageFormat::from_magic(&encoded), ImageFormat::WebP);
2985
2986        let decoded = WebpDecoder::new().decode_bytes(&encoded).unwrap();
2987        assert_eq!(decoded.dimensions(), (8, 8));
2988    }
2989
2990    #[cfg(feature = "webp")]
2991    #[test]
2992    fn test_webp_lossy_roundtrip_dimensions() {
2993        let image = test_checkerboard(16, 16);
2994        let encoded = WebpEncoder::new().encode_bytes(&image).unwrap();
2995        assert_eq!(ImageFormat::from_magic(&encoded), ImageFormat::WebP);
2996
2997        let decoded = WebpDecoder::new().decode_bytes(&encoded).unwrap();
2998        assert_eq!(decoded.dimensions(), (16, 16));
2999    }
3000
3001    #[test]
3002    fn test_wbmp_encode_decode_roundtrip() {
3003        // WBMP only supports 1-bit monochrome; feed a black/white pattern.
3004        let image = test_checkerboard(4, 4);
3005        let mut buf = Vec::new();
3006        WbmpEncoder::new().encode(&image, &mut buf).unwrap();
3007        let decoded = WbmpDecoder::new().decode_bytes(&buf).unwrap();
3008        assert_eq!(decoded.dimensions(), (4, 4));
3009    }
3010
3011    #[test]
3012    fn test_demosaic_bayer_uniform_saturated() {
3013        // All-white Bayer input → every output pixel should be close to
3014        // white in all three channels after bilinear interpolation.
3015        let raw = vec![0xFFFFu16; 4 * 4];
3016        let rgb = demosaic_bayer_rggb(&raw, 4, 4);
3017        assert_eq!(rgb.len(), 4 * 4 * 3);
3018        for (i, chunk) in rgb.chunks_exact(3).enumerate() {
3019            assert!(chunk[0] > 200, "r too dim at pixel {}: {}", i, chunk[0]);
3020            assert!(chunk[1] > 200, "g too dim at pixel {}: {}", i, chunk[1]);
3021            assert!(chunk[2] > 200, "b too dim at pixel {}: {}", i, chunk[2]);
3022        }
3023    }
3024
3025    #[test]
3026    fn test_demosaic_bayer_zero_input() {
3027        // All-black Bayer input should produce an all-black RGB buffer.
3028        let raw = vec![0u16; 4 * 4];
3029        let rgb = demosaic_bayer_rggb(&raw, 4, 4);
3030        assert!(rgb.iter().all(|&v| v == 0), "zero input should be black");
3031    }
3032
3033    #[test]
3034    fn test_demosaic_bayer_preserves_direct_channel() {
3035        // RGGB layout on a 6x6 canvas: (even, even)=R, (odd, even)=G,
3036        // (even, odd)=G, (odd, odd)=B. Put 0xFF00 at every R position,
3037        // 0 elsewhere. Pick an interior R pixel (2, 2) so clamp-to-edge
3038        // artifacts at the border do not pollute the assertion.
3039        let w = 6;
3040        let h = 6;
3041        let mut raw = vec![0u16; w * h];
3042        for y in 0..h {
3043            for x in 0..w {
3044                if x % 2 == 0 && y % 2 == 0 {
3045                    raw[y * w + x] = 0xFF00;
3046                }
3047            }
3048        }
3049        let rgb = demosaic_bayer_rggb(&raw, w, h);
3050
3051        // Interior R pixel at (2, 2).
3052        let off = (2 * w + 2) * 3;
3053        // Direct R sample survives: 0xFF00 >> 8 = 0xFF.
3054        assert_eq!(rgb[off], 0xFF);
3055        // At an R pixel, G comes from the four N/S/E/W neighbors — all
3056        // G positions, which are zero.
3057        assert_eq!(rgb[off + 1], 0);
3058        // B comes from the four diagonal neighbors — all B positions,
3059        // also zero.
3060        assert_eq!(rgb[off + 2], 0);
3061
3062        // An interior G pixel at (3, 2): its direct sample is 0 (G
3063        // positions hold 0). Horizontal neighbors (2, 2) and (4, 2) are
3064        // R-positions with 0xFF00, vertical neighbors (3, 1) and (3, 3)
3065        // are B positions with 0. So R should be ~0xFF and B should be 0.
3066        let goff = (2 * w + 3) * 3;
3067        assert!(rgb[goff] > 0xF0, "G pixel R should be close to 0xFF");
3068        assert_eq!(rgb[goff + 1], 0);
3069        assert_eq!(rgb[goff + 2], 0);
3070    }
3071
3072    #[test]
3073    fn test_demosaic_bayer_mismatched_length_returns_empty() {
3074        // Mismatched size is a pre-condition violation; return empty
3075        // rather than panicking.
3076        let raw = vec![0u16; 10];
3077        let rgb = demosaic_bayer_rggb(&raw, 4, 4);
3078        assert!(rgb.is_empty());
3079    }
3080
3081    #[cfg(feature = "gif")]
3082    #[test]
3083    fn test_gif_decode_animated_returns_multiple_frames() {
3084        // Build a minimal 2-frame GIF in memory using the gif encoder.
3085        let mut buf: Vec<u8> = Vec::new();
3086        {
3087            use gif::{Encoder, Frame, Repeat};
3088            let palette = [0, 0, 0, 255, 255, 255]; // black, white
3089            let mut encoder = Encoder::new(&mut buf, 2, 2, &palette).unwrap();
3090            encoder.set_repeat(Repeat::Infinite).unwrap();
3091
3092            // Frame 0: all-black, 50ms.
3093            let f0 = Frame {
3094                width: 2,
3095                height: 2,
3096                buffer: std::borrow::Cow::Borrowed(&[0u8; 4]),
3097                delay: 5, // 5 * 10ms = 50ms
3098                ..Frame::default()
3099            };
3100            encoder.write_frame(&f0).unwrap();
3101
3102            // Frame 1: all-white, 100ms.
3103            let f1 = Frame {
3104                width: 2,
3105                height: 2,
3106                buffer: std::borrow::Cow::Borrowed(&[1u8; 4]),
3107                delay: 10,
3108                ..Frame::default()
3109            };
3110            encoder.write_frame(&f1).unwrap();
3111        }
3112
3113        let animated = GifDecoder::new().decode_animated(&buf).unwrap();
3114        assert_eq!(animated.frame_count(), 2);
3115        assert_eq!(animated.loop_count, crate::LoopCount::Infinite);
3116        assert_eq!(animated.frames[0].delay.as_millis(), 50);
3117        assert_eq!(animated.frames[1].delay.as_millis(), 100);
3118        assert_eq!(animated.total_duration().as_millis(), 150);
3119    }
3120
3121    #[cfg(feature = "png")]
3122    #[test]
3123    fn test_png_without_iccp_chunk_has_no_color_space() {
3124        // PngEncoder does not emit an iCCP chunk, so a round-tripped
3125        // image must have `color_space == None`.
3126        let image = test_checkerboard(4, 4);
3127        let encoded = PngEncoder::new().encode_bytes(&image).unwrap();
3128        let decoded = PngDecoder::new().decode_bytes(&encoded).unwrap();
3129        assert!(decoded.color_space().is_none());
3130    }
3131
3132    #[cfg(feature = "png")]
3133    #[test]
3134    fn test_png_with_iccp_chunk_populates_color_space() {
3135        // Build a valid ICC profile (sRGB, 128-byte header with "acsp"
3136        // signature) and inject it via the png crate's encoder.
3137        let mut icc = vec![0u8; 128];
3138        // Signature at bytes 36..40.
3139        icc[36..40].copy_from_slice(b"acsp");
3140        // Profile class 'mntr' (display) at bytes 12..16.
3141        icc[12..16].copy_from_slice(b"mntr");
3142        // Color space 'RGB ' at bytes 16..20.
3143        icc[16..20].copy_from_slice(b"RGB ");
3144        // PCS 'XYZ ' at bytes 20..24.
3145        icc[20..24].copy_from_slice(b"XYZ ");
3146
3147        // Encode a 2x2 PNG with the synthetic iCCP profile. The png
3148        // crate's encoder does not expose a setter for the iCCP chunk,
3149        // but the underlying `Info` struct carries a public
3150        // `icc_profile` field that the encoder writes through. Build an
3151        // `Info` with the profile attached and hand it to `with_info`.
3152        let mut out: Vec<u8> = Vec::new();
3153        {
3154            let mut info = png::Info::with_size(2, 2);
3155            info.color_type = png::ColorType::Rgba;
3156            info.bit_depth = png::BitDepth::Eight;
3157            info.icc_profile = Some(std::borrow::Cow::Owned(icc));
3158            let encoder = png::Encoder::with_info(&mut out, info).unwrap();
3159            let mut writer = encoder.write_header().unwrap();
3160            writer.write_image_data(&[0u8; 16]).unwrap();
3161        }
3162
3163        let decoded = PngDecoder::new().decode_bytes(&out).unwrap();
3164        // IccProfile::from_bytes falls back to sRGB when the tag table
3165        // is unparseable (our synthetic profile has no tags), so the
3166        // ColorSpace itself is present and equals sRGB. The salient
3167        // check is that `color_space.is_some()` — i.e. the codec did
3168        // read the chunk and route it through the parser.
3169        assert!(
3170            decoded.color_space().is_some(),
3171            "iCCP chunk should populate ImageInfo.color_space"
3172        );
3173    }
3174
3175    // ---- PNG palette / bit-depth decode (EXPAND | STRIP_16) --------------
3176
3177    /// Encode a paletted PNG-8 fixture in memory: a 2x2 image whose four
3178    /// pixels index four distinct palette colors. With the default
3179    /// `IDENTITY` transform the decoder would hand back raw indices
3180    /// (single-channel); EXPAND must turn these into RGB.
3181    #[cfg(feature = "png")]
3182    #[test]
3183    fn test_png_palette8_decodes_to_rgb() {
3184        let palette = vec![
3185            255, 0, 0, // 0 red
3186            0, 255, 0, // 1 green
3187            0, 0, 255, // 2 blue
3188            255, 255, 0, // 3 yellow
3189        ];
3190        let mut out: Vec<u8> = Vec::new();
3191        {
3192            let mut encoder = png::Encoder::new(&mut out, 2, 2);
3193            encoder.set_color(png::ColorType::Indexed);
3194            encoder.set_depth(png::BitDepth::Eight);
3195            encoder.set_palette(palette);
3196            let mut w = encoder.write_header().unwrap();
3197            // Indices: (0,0)=0 (1,0)=1 / (0,1)=2 (1,1)=3
3198            w.write_image_data(&[0, 1, 2, 3]).unwrap();
3199        }
3200
3201        let decoded = PngDecoder::new().decode_bytes(&out).unwrap();
3202        assert_eq!(decoded.dimensions(), (2, 2));
3203        let px = decoded.peek_pixels().unwrap();
3204        assert_eq!(&px[0..4], &[255, 0, 0, 255], "index 0 -> red");
3205        assert_eq!(&px[4..8], &[0, 255, 0, 255], "index 1 -> green");
3206        assert_eq!(&px[8..12], &[0, 0, 255, 255], "index 2 -> blue");
3207        assert_eq!(&px[12..16], &[255, 255, 0, 255], "index 3 -> yellow");
3208    }
3209
3210    /// A 16-bit-per-channel RGB PNG must decode via `STRIP_16` to the high
3211    /// byte of each sample. Without the transform, the `png` crate yields a
3212    /// 6-byte-per-pixel buffer our RGBA8 path cannot interpret.
3213    #[cfg(feature = "png")]
3214    #[test]
3215    fn test_png_rgb16_strips_to_high_byte() {
3216        let mut out: Vec<u8> = Vec::new();
3217        {
3218            let mut encoder = png::Encoder::new(&mut out, 1, 1);
3219            encoder.set_color(png::ColorType::Rgb);
3220            encoder.set_depth(png::BitDepth::Sixteen);
3221            let mut w = encoder.write_header().unwrap();
3222            // One pixel, big-endian 16-bit R=0x1234 G=0x5678 B=0x9ABC.
3223            w.write_image_data(&[0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC])
3224                .unwrap();
3225        }
3226
3227        let decoded = PngDecoder::new().decode_bytes(&out).unwrap();
3228        let px = decoded.peek_pixels().unwrap();
3229        // STRIP_16 keeps the most-significant byte of each channel.
3230        assert_eq!(&px[0..4], &[0x12, 0x56, 0x9A, 255]);
3231    }
3232
3233    /// A 4-bit grayscale PNG must expand to 8-bit gray. The `png` crate
3234    /// scales sub-8-bit samples by `255 / (2^depth - 1)` (= 17 for 4-bit),
3235    /// so index 0 -> 0, 15 -> 255, 8 -> 136.
3236    #[cfg(feature = "png")]
3237    #[test]
3238    fn test_png_gray4_expands_to_8bit() {
3239        let mut out: Vec<u8> = Vec::new();
3240        {
3241            let mut encoder = png::Encoder::new(&mut out, 2, 1);
3242            encoder.set_color(png::ColorType::Grayscale);
3243            encoder.set_depth(png::BitDepth::Four);
3244            let mut w = encoder.write_header().unwrap();
3245            // Two 4-bit samples packed into one byte: 0x0F -> (0, 15).
3246            w.write_image_data(&[0x0F]).unwrap();
3247        }
3248
3249        let decoded = PngDecoder::new().decode_bytes(&out).unwrap();
3250        assert_eq!(decoded.dimensions(), (2, 1));
3251        let px = decoded.peek_pixels().unwrap();
3252        assert_eq!(&px[0..4], &[0, 0, 0, 255], "gray 0 -> black");
3253        assert_eq!(&px[4..8], &[255, 255, 255, 255], "gray 15 -> white");
3254    }
3255
3256    // ---- Encoder unpremultiplication ------------------------------------
3257
3258    /// Encoders must store straight (unpremultiplied) alpha. A premultiplied
3259    /// source (50% red stored as r==a==128) must round-trip through PNG back
3260    /// to unpremultiplied red (255, 0, 0, 128).
3261    #[cfg(feature = "png")]
3262    #[test]
3263    fn test_png_encode_unpremultiplies() {
3264        // Premultiplied 50% red: r = premul(255, a=128) = 128.
3265        let info = crate::ImageInfo::new(
3266            1,
3267            1,
3268            skia_rs_core::ColorType::Rgba8888,
3269            skia_rs_core::AlphaType::Premul,
3270        );
3271        let image = Image::from_raster_data_owned(info, vec![128, 0, 0, 128], 4).unwrap();
3272
3273        let encoded = PngEncoder::new().encode_bytes(&image).unwrap();
3274        let decoded = PngDecoder::new().decode_bytes(&encoded).unwrap();
3275        let px = decoded.peek_pixels().unwrap();
3276        // Unpremultiplying 128 with alpha 128 restores ~255.
3277        assert!(
3278            px[0] >= 253,
3279            "R should unpremultiply back to ~255, got {}",
3280            px[0]
3281        );
3282        assert_eq!(px[3], 128, "alpha preserved");
3283    }
3284
3285    /// Differential check for the shared premul rounding landed in core:
3286    /// premul(200, a=130) must round to 102 (`SkMulDiv255Round`), not truncate
3287    /// to 101.
3288    #[test]
3289    fn test_premul_rounding_matches_skia() {
3290        let mut px = vec![200u8, 200, 200, 130];
3291        skia_rs_core::premultiply_in_place(&mut px);
3292        assert_eq!(px[0], 102, "premul(200, 130) rounds to 102");
3293    }
3294
3295    // ---- BMP 32-bit alpha / bitfields -----------------------------------
3296
3297    /// Build a standalone 32-bit `BI_RGB` BMP by hand (BITMAPINFOHEADER). The
3298    /// stored 4th byte is 0 (padding), but `SkBmpCodec` treats standalone
3299    /// 32-bit `BI_RGB` as opaque (kBGRX), so decoded alpha must be 255.
3300    #[test]
3301    fn test_bmp_32bit_bi_rgb_is_opaque() {
3302        let mut bmp = build_bmp_header(1, 1, 32, 0);
3303        // One pixel: B=10 G=20 R=30 X=0.
3304        bmp.extend_from_slice(&[10, 20, 30, 0]);
3305
3306        let decoded = decode_bmp(&bmp).unwrap();
3307        let px = decoded.peek_pixels().unwrap();
3308        assert_eq!(
3309            &px[0..4],
3310            &[30, 20, 10, 255],
3311            "BI_RGB 4th byte ignored -> opaque"
3312        );
3313    }
3314
3315    /// A 32-bit `BI_BITFIELDS` BMP with explicit RGBA masks must honor them.
3316    #[test]
3317    fn test_bmp_32bit_bitfields_applies_masks() {
3318        // Masks: R=0x00FF0000 G=0x0000FF00 B=0x000000FF A=0xFF000000.
3319        // Header size 56 (V3) so an alpha mask is recognized. The 16 mask
3320        // bytes fill the header out to the pixel offset (14 + 56 = 70).
3321        let mut bmp = build_bmp_header_ex(1, 1, 32, 3, 56);
3322        bmp.extend_from_slice(&0x00FF_0000_u32.to_le_bytes()); // red mask @54
3323        bmp.extend_from_slice(&0x0000_FF00_u32.to_le_bytes()); // green mask @58
3324        bmp.extend_from_slice(&0x0000_00FF_u32.to_le_bytes()); // blue mask @62
3325        bmp.extend_from_slice(&0xFF00_0000_u32.to_le_bytes()); // alpha mask @66
3326        // Pixel value 0xAABBCCDD (little-endian bytes DD CC BB AA):
3327        //   A=0xAA R=0xBB G=0xCC B=0xDD
3328        bmp.extend_from_slice(&[0xDD, 0xCC, 0xBB, 0xAA]);
3329        let decoded = decode_bmp(&bmp).unwrap();
3330        let px = decoded.peek_pixels().unwrap();
3331        assert_eq!(px[0], 0xBB, "red from mask");
3332        assert_eq!(px[1], 0xCC, "green from mask");
3333        assert_eq!(px[2], 0xDD, "blue from mask");
3334        assert_eq!(px[3], 0xAA, "alpha from mask");
3335    }
3336
3337    /// A BMP whose pixel array is shorter than width*height*stride is
3338    /// truncated and must be reported, not silently zero-filled.
3339    #[test]
3340    fn test_bmp_truncated_reports_error() {
3341        let mut bmp = build_bmp_header(4, 4, 24, 0);
3342        // Only supply a few bytes instead of 4 rows * padded stride.
3343        bmp.extend_from_slice(&[0u8; 8]);
3344        assert!(decode_bmp(&bmp).is_err(), "truncated BMP must error");
3345    }
3346
3347    /// Absurd / non-positive dimensions must be rejected before allocation.
3348    #[test]
3349    fn test_bmp_absurd_dimensions_rejected() {
3350        // width = i32::MAX, height = i32::MAX would overflow the allocation.
3351        let mut bmp = build_bmp_header(i32::MAX, i32::MAX, 32, 0);
3352        bmp.extend_from_slice(&[0u8; 16]);
3353        assert!(decode_bmp(&bmp).is_err(), "huge BMP dims must error");
3354
3355        let zero = build_bmp_header(0, 1, 32, 0);
3356        assert!(decode_bmp(&zero).is_err(), "zero width must error");
3357    }
3358
3359    /// `get_bmp_dimensions` must not panic on a top-down BMP whose height is
3360    /// `i32::MIN` (`.abs()` would overflow), and must not silently wrap the
3361    /// magnitude back to a negative value either (`2^31` doesn't fit in
3362    /// `i32`, so it saturates to `i32::MAX`).
3363    #[test]
3364    fn test_bmp_dimensions_i32_min_height() {
3365        let mut bmp = vec![0u8; 54];
3366        bmp[0] = b'B';
3367        bmp[1] = b'M';
3368        bmp[18..22].copy_from_slice(&100i32.to_le_bytes());
3369        bmp[22..26].copy_from_slice(&i32::MIN.to_le_bytes());
3370        let (w, h) = get_bmp_dimensions(&bmp).unwrap();
3371        assert_eq!(w, 100);
3372        assert_eq!(h, i32::MAX);
3373    }
3374
3375    /// Helper: build a minimal BITMAPFILEHEADER + BITMAPINFOHEADER for a
3376    /// standalone BMP with the given dims/bpp/compression. Pixel data is
3377    /// appended by the caller. Uses a 40-byte core header.
3378    fn build_bmp_header(width: i32, height: i32, bpp: u16, compression: u32) -> Vec<u8> {
3379        build_bmp_header_ex(width, height, bpp, compression, 40)
3380    }
3381
3382    fn build_bmp_header_ex(
3383        width: i32,
3384        height: i32,
3385        bpp: u16,
3386        compression: u32,
3387        header_size: u32,
3388    ) -> Vec<u8> {
3389        let mut bmp = Vec::new();
3390        let pixel_offset = 14 + header_size;
3391        // BITMAPFILEHEADER
3392        bmp.extend_from_slice(b"BM");
3393        bmp.extend_from_slice(&0u32.to_le_bytes()); // file size (unused)
3394        bmp.extend_from_slice(&0u32.to_le_bytes()); // reserved
3395        bmp.extend_from_slice(&pixel_offset.to_le_bytes()); // pixel data offset
3396        // BITMAPINFOHEADER (always write 40 core bytes)
3397        bmp.extend_from_slice(&header_size.to_le_bytes());
3398        bmp.extend_from_slice(&width.to_le_bytes());
3399        bmp.extend_from_slice(&height.to_le_bytes());
3400        bmp.extend_from_slice(&1u16.to_le_bytes()); // planes
3401        bmp.extend_from_slice(&bpp.to_le_bytes());
3402        bmp.extend_from_slice(&compression.to_le_bytes());
3403        bmp.extend_from_slice(&0u32.to_le_bytes()); // image size
3404        bmp.extend_from_slice(&0u32.to_le_bytes()); // x ppm
3405        bmp.extend_from_slice(&0u32.to_le_bytes()); // y ppm
3406        bmp.extend_from_slice(&0u32.to_le_bytes()); // colors used
3407        bmp.extend_from_slice(&0u32.to_le_bytes()); // important colors
3408        // Pad the header out to `header_size` (for V3/V4 the extra bytes hold
3409        // the channel masks, which the caller appends).
3410        bmp
3411    }
3412
3413    // ---- Malformed ICO robustness ---------------------------------------
3414
3415    /// A truncated ICO directory (claims one image, but the entry is cut
3416    /// off) must error, not panic with an out-of-bounds read.
3417    #[test]
3418    fn test_ico_truncated_directory_errors() {
3419        // reserved=0, type=1, count=1, then only 4 of the 16 entry bytes.
3420        let data = vec![0, 0, 1, 0, 1, 0, 16, 16, 0, 0];
3421        assert!(decode_ico(&data).is_err());
3422    }
3423
3424    /// An ICO-embedded BMP whose header claims huge (per-dimension in-range)
3425    /// dimensions but supplies no pixel data must error *before* allocating
3426    /// the output buffer — width*height*4 for 16M x 8M would be ~0.5 PB.
3427    #[test]
3428    fn test_ico_bmp_absurd_dims_rejected_before_alloc() {
3429        // BITMAPINFOHEADER (40 bytes), no pixel data.
3430        let mut bmp = vec![0u8; 40];
3431        bmp[0..4].copy_from_slice(&40u32.to_le_bytes()); // header size
3432        bmp[4..8].copy_from_slice(&((1i32 << 24) - 2).to_le_bytes()); // width
3433        // Stored height counts color+mask, so this decodes to height/2.
3434        bmp[8..12].copy_from_slice(&((1i32 << 24) - 2).to_le_bytes()); // height
3435        bmp[14..16].copy_from_slice(&32u16.to_le_bytes()); // bpp
3436        assert!(
3437            decode_ico_bmp(&bmp).is_err(),
3438            "absurd ICO BMP dims with no data must error, not allocate"
3439        );
3440    }
3441
3442    /// An ICO entry whose image offset/size point past the buffer must
3443    /// error.
3444    #[test]
3445    fn test_ico_bad_offset_errors() {
3446        let mut data = vec![0u8; 6 + 16];
3447        data[2] = 1; // type
3448        data[4] = 1; // count
3449        data[6] = 16; // width
3450        data[7] = 16; // height
3451        // image_size at +8, image_offset at +12 point way past the buffer.
3452        data[6 + 8..6 + 12].copy_from_slice(&1000u32.to_le_bytes());
3453        data[6 + 12..6 + 16].copy_from_slice(&1000u32.to_le_bytes());
3454        assert!(decode_ico(&data).is_err());
3455    }
3456
3457    // ---- WBMP multibyte sniffing ----------------------------------------
3458
3459    /// WBMP sniffing must accept multibyte width/height integers (dimensions
3460    /// larger than 127), not just single-byte ones.
3461    #[test]
3462    fn test_wbmp_sniff_multibyte_dimensions() {
3463        // type=0, fix=0, width=200 (multibyte: 0x81 0x48), height=200.
3464        let data = [0u8, 0, 0x81, 0x48, 0x81, 0x48, 0, 0];
3465        assert_eq!(ImageFormat::from_magic(&data), ImageFormat::Wbmp);
3466    }
3467
3468    // ---- JPEG SOF / RST marker scan -------------------------------------
3469
3470    /// `get_jpeg_dimensions` must skip standalone RST markers (no length
3471    /// payload) and read dimensions from a progressive SOF2 header.
3472    #[test]
3473    fn test_jpeg_dimensions_sof2_after_rst() {
3474        // SOI, RST0 (standalone), then SOF2 with height=0x0064 width=0x00C8.
3475        let data = [
3476            0xFF, 0xD8, // SOI
3477            0xFF, 0xD0, // RST0 (standalone, no length)
3478            0xFF, 0xC2, // SOF2
3479            0x00, 0x11, // length = 17
3480            0x08, // precision
3481            0x00, 0x64, // height = 100
3482            0x00, 0xC8, // width = 200
3483            0x03, // component count (padding for the scan)
3484            0, 0, 0, 0, 0, 0, 0, 0,
3485        ];
3486        let (w, h) = get_jpeg_dimensions(&data).unwrap();
3487        assert_eq!((w, h), (200, 100));
3488    }
3489
3490    // ---- GIF canvas compositing -----------------------------------------
3491
3492    /// A GIF whose first frame is smaller than the logical screen and is
3493    /// placed at an offset must decode to the *canvas* size, compositing the
3494    /// frame at its left/top over a transparent background.
3495    #[cfg(feature = "gif")]
3496    #[test]
3497    fn test_gif_decode_composites_first_frame_on_canvas() {
3498        let mut buf: Vec<u8> = Vec::new();
3499        {
3500            use gif::{Encoder, Frame, Repeat};
3501            // 4x4 logical screen; global palette black/white.
3502            let palette = [0, 0, 0, 255, 255, 255];
3503            let mut encoder = Encoder::new(&mut buf, 4, 4, &palette).unwrap();
3504            encoder.set_repeat(Repeat::Infinite).unwrap();
3505            // A 2x2 opaque-white frame placed at (1,1).
3506            let f = Frame {
3507                width: 2,
3508                height: 2,
3509                left: 1,
3510                top: 1,
3511                buffer: std::borrow::Cow::Borrowed(&[1u8; 4]),
3512                ..Frame::default()
3513            };
3514            encoder.write_frame(&f).unwrap();
3515        }
3516
3517        let decoded = GifDecoder::new().decode_bytes(&buf).unwrap();
3518        assert_eq!(decoded.dimensions(), (4, 4), "decodes to logical screen");
3519        let px = decoded.peek_pixels().unwrap();
3520        // Pixel (0,0) is outside the frame -> transparent.
3521        assert_eq!(&px[0..4], &[0, 0, 0, 0], "corner is transparent");
3522        // Pixel (1,1) is the frame's top-left -> white opaque.
3523        let off = (4 + 1) * 4;
3524        assert_eq!(
3525            &px[off..off + 4],
3526            &[255, 255, 255, 255],
3527            "frame composited at offset"
3528        );
3529    }
3530
3531    /// `decode_animated` must report the logical-screen canvas dimensions.
3532    #[cfg(feature = "gif")]
3533    #[test]
3534    fn test_gif_animated_carries_canvas_dimensions() {
3535        let mut buf: Vec<u8> = Vec::new();
3536        {
3537            use gif::{Encoder, Frame};
3538            let palette = [0, 0, 0, 255, 255, 255];
3539            let mut encoder = Encoder::new(&mut buf, 6, 5, &palette).unwrap();
3540            let f = Frame {
3541                width: 2,
3542                height: 2,
3543                buffer: std::borrow::Cow::Borrowed(&[0u8; 4]),
3544                ..Frame::default()
3545            };
3546            encoder.write_frame(&f).unwrap();
3547        }
3548        let anim = GifDecoder::new().decode_animated(&buf).unwrap();
3549        assert_eq!(anim.canvas_dimensions(), (6, 5));
3550    }
3551
3552    /// A GIF declaring an absurd logical-screen size (65535x65535, the max
3553    /// representable in the format's u16 header fields) must be rejected
3554    /// with an error rather than attempting a ~17GB canvas allocation,
3555    /// which would abort the process instead of returning `Err`.
3556    #[cfg(feature = "gif")]
3557    #[test]
3558    fn test_gif_decode_rejects_oversized_canvas() {
3559        let mut buf: Vec<u8> = Vec::new();
3560        {
3561            use gif::{Encoder, Frame};
3562            let palette = [0, 0, 0, 255, 255, 255];
3563            // Logical screen at the format's maximum (u16::MAX x u16::MAX)
3564            // would require ~17GB for an RGBA canvas; a tiny 1x1 frame keeps
3565            // the encoded file itself small.
3566            let mut encoder = Encoder::new(&mut buf, u16::MAX, u16::MAX, &palette).unwrap();
3567            let f = Frame {
3568                width: 1,
3569                height: 1,
3570                buffer: std::borrow::Cow::Borrowed(&[0u8]),
3571                ..Frame::default()
3572            };
3573            encoder.write_frame(&f).unwrap();
3574        }
3575
3576        let result = GifDecoder::new().decode_bytes(&buf);
3577        assert!(
3578            result.is_err(),
3579            "oversized GIF canvas must be rejected, not allocated"
3580        );
3581    }
3582}