1use crate::Image;
6use std::io::{Read, Write};
7use thiserror::Error;
8
9#[derive(Debug, Error)]
11pub enum CodecError {
12 #[error("I/O error: {0}")]
14 Io(#[from] std::io::Error),
15 #[error("invalid data: {0}")]
17 InvalidData(String),
18 #[error("unsupported: {0}")]
20 Unsupported(String),
21 #[error("encoding error: {0}")]
23 EncodingError(String),
24 #[error("decoding error: {0}")]
26 DecodingError(String),
27}
28
29pub type CodecResult<T> = Result<T, CodecError>;
31
32const MAX_DIM: usize = 1 << 24;
35const MAX_CANVAS_BYTES: usize = 1 << 28; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43pub enum ImageFormat {
44 Png,
46 Jpeg,
48 Gif,
50 WebP,
52 Bmp,
54 Ico,
56 Wbmp,
58 Avif,
60 Raw,
62 Unknown,
64}
65
66impl ImageFormat {
67 #[must_use]
69 pub fn from_magic(data: &[u8]) -> Self {
70 if data.len() < 8 {
71 return Self::Unknown;
72 }
73
74 if data.starts_with(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) {
76 return Self::Png;
77 }
78
79 if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
81 return Self::Jpeg;
82 }
83
84 if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
86 return Self::Gif;
87 }
88
89 if data.len() >= 12 && data.starts_with(b"RIFF") && &data[8..12] == b"WEBP" {
91 return Self::WebP;
92 }
93
94 if data.starts_with(b"BM") {
96 return Self::Bmp;
97 }
98
99 if data.starts_with(&[0x00, 0x00, 0x01, 0x00]) {
101 return Self::Ico;
102 }
103
104 if data.len() >= 12 && &data[4..8] == b"ftyp" {
107 if &data[8..12] == b"avif" || &data[8..12] == b"avis" || &data[8..12] == b"mif1" {
109 return Self::Avif;
110 }
111 }
112
113 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 #[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 #[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
168pub trait ImageDecoder: Send + Sync {
170 fn decode<R: Read>(&self, reader: R) -> CodecResult<Image>;
176
177 fn decode_bytes(&self, data: &[u8]) -> CodecResult<Image> {
183 self.decode(std::io::Cursor::new(data))
184 }
185
186 fn format(&self) -> ImageFormat;
188
189 fn can_decode(&self, data: &[u8]) -> bool {
191 ImageFormat::from_magic(data) == self.format()
192 }
193}
194
195pub trait ImageEncoder: Send + Sync {
197 fn encode<W: Write>(&self, image: &Image, writer: W) -> CodecResult<()>;
203
204 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 fn format(&self) -> ImageFormat;
216}
217
218#[derive(Debug, Clone, Copy)]
220pub struct EncoderQuality(u8);
221
222impl EncoderQuality {
223 #[must_use]
225 pub fn new(quality: u8) -> Self {
226 Self(quality.min(100))
227 }
228
229 #[must_use]
231 pub const fn value(&self) -> u8 {
232 self.0
233 }
234
235 pub const DEFAULT: Self = Self(80);
237
238 pub const HIGH: Self = Self(95);
240
241 pub const LOW: Self = Self(50);
243}
244
245impl Default for EncoderQuality {
246 fn default() -> Self {
247 Self::DEFAULT
248 }
249}
250
251fn 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#[derive(Debug, Default)]
274pub struct PngDecoder;
275
276impl PngDecoder {
277 #[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 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 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 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#[derive(Debug, Default)]
392pub struct PngEncoder;
393
394impl PngEncoder {
395 #[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 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]); rgba.push(chunk[1]); rgba.push(chunk[0]); rgba.push(chunk[3]); }
432 rgba
433 }
434 _ => {
435 return Err(CodecError::Unsupported(
436 "Unsupported color type for PNG encoding".into(),
437 ));
438 }
439 };
440
441 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#[derive(Debug, Default)]
469pub struct JpegDecoder;
470
471impl JpegDecoder {
472 #[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 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 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#[derive(Debug)]
558pub struct JpegEncoder {
559 quality: EncoderQuality,
560}
561
562impl JpegEncoder {
563 #[must_use]
565 pub const fn new() -> Self {
566 Self {
567 quality: EncoderQuality::DEFAULT,
568 }
569 }
570
571 #[must_use]
573 pub const fn with_quality(quality: EncoderQuality) -> Self {
574 Self { quality }
575 }
576
577 #[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 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]); rgba.push(chunk[1]); rgba.push(chunk[0]); rgba.push(chunk[3]); }
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#[derive(Debug, Default)]
662pub struct GifDecoder;
663
664impl GifDecoder {
665 #[must_use]
667 pub const fn new() -> Self {
668 Self
669 }
670
671 #[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 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 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 #[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 let canvas_width = usize::from(decoder.width());
772 let canvas_height = usize::from(decoder.height());
773
774 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 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#[derive(Debug, Default)]
854pub struct WebpDecoder;
855
856impl WebpDecoder {
857 #[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 let src = webp_image.to_vec();
887 let pixels = if has_alpha {
888 src
889 } else {
890 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#[derive(Debug)]
926pub struct WebpEncoder {
927 #[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 #[must_use]
938 pub const fn new() -> Self {
939 Self {
940 quality: EncoderQuality::DEFAULT,
941 lossless: false,
942 }
943 }
944
945 #[must_use]
947 pub const fn with_quality(quality: EncoderQuality) -> Self {
948 Self {
949 quality,
950 lossless: false,
951 }
952 }
953
954 #[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 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 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#[derive(Debug, Default)]
1031pub struct BmpDecoder;
1032
1033impl BmpDecoder {
1034 #[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#[derive(Debug, Default)]
1055pub struct BmpEncoder;
1056
1057impl BmpEncoder {
1058 #[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 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 let row_size = (width * 4 + 3) & !3; let pixel_data_size = row_size * height;
1086 let file_size = 14 + 40 + pixel_data_size; writer.write_all(b"BM")?; writer.write_all(&file_size.to_le_bytes())?; writer.write_all(&[0u8; 4])?; writer.write_all(&(14u32 + 40).to_le_bytes())?; writer.write_all(&40u32.to_le_bytes())?; writer.write_all(&width_i32.to_le_bytes())?; writer.write_all(&height_i32.to_le_bytes())?; writer.write_all(&1u16.to_le_bytes())?; writer.write_all(&32u16.to_le_bytes())?; writer.write_all(&0u32.to_le_bytes())?; writer.write_all(&pixel_data_size.to_le_bytes())?; writer.write_all(&2835u32.to_le_bytes())?; writer.write_all(&2835u32.to_le_bytes())?; writer.write_all(&0u32.to_le_bytes())?; writer.write_all(&0u32.to_le_bytes())?; 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 for chunk in row.chunks(4) {
1118 writer.write_all(&[chunk[2], chunk[1], chunk[0], chunk[3]])?; }
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#[derive(Debug, Clone, Copy)]
1136struct BitfieldMasks {
1137 red: u32,
1138 green: u32,
1139 blue: u32,
1140 alpha: u32,
1141}
1142
1143impl BitfieldMasks {
1144 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 u8::try_from((raw * 255 + max / 2) / max).unwrap_or(255)
1157 }
1158}
1159
1160#[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 if &data[0..2] != b"BM" {
1174 return Err(CodecError::InvalidData("Invalid BMP signature".into()));
1175 }
1176
1177 let pixel_offset = u32::from_le_bytes([data[10], data[11], data[12], data[13]]) as usize;
1179
1180 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 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 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 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 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 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 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]; rgba[dst + 1] = pixel_data[src + 1]; rgba[dst + 2] = pixel_data[src]; rgba[dst + 3] = 255; }
1290 }
1291 }
1292 }
1293 16 => {
1294 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 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]; rgba[dst + 1] = pixel_data[src + 1]; rgba[dst + 2] = pixel_data[src]; rgba[dst + 3] = 255; }
1362 }
1363 }
1364 }
1365 }
1366 8 => {
1367 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]; rgba[dst + 1] = palette[p + 1]; rgba[dst + 2] = palette[p]; rgba[dst + 3] = 255; }
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#[derive(Debug, Default)]
1424pub struct IcoDecoder;
1425
1426impl IcoDecoder {
1427 #[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
1446fn decode_ico(data: &[u8]) -> CodecResult<Image> {
1449 if data.len() < 6 {
1450 return Err(CodecError::InvalidData("ICO too short".into()));
1451 }
1452
1453 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 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 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 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 if image_data.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
1528 PngDecoder::new().decode_bytes(image_data)
1530 } else {
1531 decode_ico_bmp(image_data)
1533 }
1534}
1535
1536#[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 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; 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 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 let row_size = width * 4;
1599 for y in 0..height {
1600 let src_y = height - 1 - y; 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]; rgba[dst + 1] = pixel_data[src + 1]; rgba[dst + 2] = pixel_data[src]; rgba[dst + 3] = pixel_data[src + 3]; }
1613 }
1614 }
1615 }
1616 24 => {
1617 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]; rgba[dst + 1] = pixel_data[src + 1]; rgba[dst + 2] = pixel_data[src]; 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
1671pub struct WbmpDecoder;
1679
1680impl WbmpDecoder {
1681 #[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
1706pub struct WbmpEncoder;
1708
1709impl WbmpEncoder {
1710 #[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
1733fn 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; }
1750 }
1751 Some(value)
1752}
1753
1754fn 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
1767fn 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 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 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 let width = read_wbmp_int(data, &mut offset)
1795 .ok_or_else(|| CodecError::InvalidData("Invalid WBMP width".into()))?;
1796
1797 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 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 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; rgba[pixel_idx + 1] = value; rgba[pixel_idx + 2] = value; rgba[pixel_idx + 3] = 255; }
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
1845fn 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_wbmp_int(writer, 0)?;
1857
1858 write_wbmp_int(writer, 0)?;
1860
1861 write_wbmp_int(writer, width)?;
1863
1864 write_wbmp_int(writer, height)?;
1866
1867 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 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 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
1896fn 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 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 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
1922pub struct AvifDecoder;
1931
1932impl AvifDecoder {
1933 #[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 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 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 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
2053pub struct AvifEncoder {
2057 quality: u8,
2058 speed: u8,
2059}
2060
2061impl AvifEncoder {
2062 #[must_use]
2064 pub const fn new() -> Self {
2065 Self {
2066 quality: 80,
2067 speed: 6, }
2069 }
2070
2071 #[must_use]
2073 pub fn with_quality(mut self, quality: u8) -> Self {
2074 self.quality = quality.min(100);
2075 self
2076 }
2077
2078 #[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 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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2178pub enum BayerPattern {
2179 Rggb,
2181 Bggr,
2183 Grbg,
2185 Gbrg,
2187}
2188
2189#[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#[inline]
2212fn bayer_to_isize(v: usize) -> isize {
2213 isize::try_from(v).unwrap_or(isize::MAX)
2214}
2215
2216#[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#[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 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 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 (v, cross, diag)
2321 } else {
2322 (diag, cross, v)
2324 };
2325
2326 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#[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
2346pub struct RawDecoder;
2351
2352impl RawDecoder {
2353 #[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 let width = raw_image.width as i32;
2382 let height = raw_image.height as i32;
2383
2384 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#[cfg(feature = "raw")]
2415fn detect_bayer_pattern(cfa: &rawloader::CFA) -> Option<BayerPattern> {
2416 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#[cfg(feature = "raw")]
2438fn demosaic_raw(raw: &rawloader::RawImage) -> CodecResult<Vec<u8>> {
2439 let width = raw.width;
2440 let height = raw.height;
2441
2442 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 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 let mut output = vec![0u8; width * height * 4];
2489
2490 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 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 let color = cfa.color_at(y, x);
2513
2514 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 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 output[out_idx] = normalized;
2550 output[out_idx + 1] = normalized;
2551 output[out_idx + 2] = normalized;
2552 }
2553 }
2554 output[out_idx + 3] = 255; }
2556 }
2557
2558 Ok(output)
2559}
2560
2561#[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 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 }
2602}
2603
2604#[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
2621pub 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
2649pub 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 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
2686const 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 let mut i = 2;
2699 while i + 1 < data.len() {
2700 if data[i] != 0xFF {
2701 i += 1;
2702 continue;
2703 }
2704 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 if marker == 0x00 || marker == 0x01 || (0xD0..=0xD9).contains(&marker) {
2715 i = j + 1;
2716 continue;
2717 }
2718
2719 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 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 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 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 let png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
2812 assert_eq!(ImageFormat::from_magic(&png), ImageFormat::Png);
2813
2814 let jpeg = [0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46];
2816 assert_eq!(ImageFormat::from_magic(&jpeg), ImageFormat::Jpeg);
2817
2818 let gif = b"GIF89a\x00\x00";
2820 assert_eq!(ImageFormat::from_magic(gif), ImageFormat::Gif);
2821
2822 let webp = b"RIFF\x00\x00\x00\x00WEBP";
2824 assert_eq!(ImageFormat::from_magic(webp), ImageFormat::WebP);
2825
2826 let bmp = b"BM\x00\x00\x00\x00\x00\x00";
2828 assert_eq!(ImageFormat::from_magic(bmp), ImageFormat::Bmp);
2829
2830 let ico = [0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x10];
2832 assert_eq!(ImageFormat::from_magic(&ico), ImageFormat::Ico);
2833
2834 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 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, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 0, 255, ];
2880 let image = Image::from_raster_data_owned(info, pixels, 8).unwrap();
2881
2882 let encoder = BmpEncoder::new();
2884 let bmp_bytes = encoder.encode_bytes(&image).unwrap();
2885
2886 assert_eq!(ImageFormat::from_magic(&bmp_bytes), ImageFormat::Bmp);
2888
2889 let decoder = BmpDecoder::new();
2891 let round_tripped = decoder.decode_bytes(&bmp_bytes).unwrap();
2892
2893 assert_eq!(round_tripped.width(), 2);
2895 assert_eq!(round_tripped.height(), 2);
2896 }
2897
2898 #[test]
2899 fn test_bmp_dimensions() {
2900 let mut bmp = vec![0u8; 54];
2902 bmp[0] = b'B';
2903 bmp[1] = b'M';
2904 bmp[18..22].copy_from_slice(&100i32.to_le_bytes());
2906 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 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 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 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 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 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 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 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 let off = (2 * w + 2) * 3;
3053 assert_eq!(rgb[off], 0xFF);
3055 assert_eq!(rgb[off + 1], 0);
3058 assert_eq!(rgb[off + 2], 0);
3061
3062 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 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 let mut buf: Vec<u8> = Vec::new();
3086 {
3087 use gif::{Encoder, Frame, Repeat};
3088 let palette = [0, 0, 0, 255, 255, 255]; let mut encoder = Encoder::new(&mut buf, 2, 2, &palette).unwrap();
3090 encoder.set_repeat(Repeat::Infinite).unwrap();
3091
3092 let f0 = Frame {
3094 width: 2,
3095 height: 2,
3096 buffer: std::borrow::Cow::Borrowed(&[0u8; 4]),
3097 delay: 5, ..Frame::default()
3099 };
3100 encoder.write_frame(&f0).unwrap();
3101
3102 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 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 let mut icc = vec![0u8; 128];
3138 icc[36..40].copy_from_slice(b"acsp");
3140 icc[12..16].copy_from_slice(b"mntr");
3142 icc[16..20].copy_from_slice(b"RGB ");
3144 icc[20..24].copy_from_slice(b"XYZ ");
3146
3147 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 assert!(
3170 decoded.color_space().is_some(),
3171 "iCCP chunk should populate ImageInfo.color_space"
3172 );
3173 }
3174
3175 #[cfg(feature = "png")]
3182 #[test]
3183 fn test_png_palette8_decodes_to_rgb() {
3184 let palette = vec![
3185 255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 0, ];
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 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 #[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 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 assert_eq!(&px[0..4], &[0x12, 0x56, 0x9A, 255]);
3231 }
3232
3233 #[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 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 #[cfg(feature = "png")]
3262 #[test]
3263 fn test_png_encode_unpremultiplies() {
3264 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 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 #[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 #[test]
3301 fn test_bmp_32bit_bi_rgb_is_opaque() {
3302 let mut bmp = build_bmp_header(1, 1, 32, 0);
3303 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 #[test]
3317 fn test_bmp_32bit_bitfields_applies_masks() {
3318 let mut bmp = build_bmp_header_ex(1, 1, 32, 3, 56);
3322 bmp.extend_from_slice(&0x00FF_0000_u32.to_le_bytes()); bmp.extend_from_slice(&0x0000_FF00_u32.to_le_bytes()); bmp.extend_from_slice(&0x0000_00FF_u32.to_le_bytes()); bmp.extend_from_slice(&0xFF00_0000_u32.to_le_bytes()); 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 #[test]
3340 fn test_bmp_truncated_reports_error() {
3341 let mut bmp = build_bmp_header(4, 4, 24, 0);
3342 bmp.extend_from_slice(&[0u8; 8]);
3344 assert!(decode_bmp(&bmp).is_err(), "truncated BMP must error");
3345 }
3346
3347 #[test]
3349 fn test_bmp_absurd_dimensions_rejected() {
3350 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 #[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 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 bmp.extend_from_slice(b"BM");
3393 bmp.extend_from_slice(&0u32.to_le_bytes()); bmp.extend_from_slice(&0u32.to_le_bytes()); bmp.extend_from_slice(&pixel_offset.to_le_bytes()); 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()); 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()); bmp.extend_from_slice(&0u32.to_le_bytes()); bmp.extend_from_slice(&0u32.to_le_bytes()); bmp.extend_from_slice(&0u32.to_le_bytes()); bmp.extend_from_slice(&0u32.to_le_bytes()); bmp
3411 }
3412
3413 #[test]
3418 fn test_ico_truncated_directory_errors() {
3419 let data = vec![0, 0, 1, 0, 1, 0, 16, 16, 0, 0];
3421 assert!(decode_ico(&data).is_err());
3422 }
3423
3424 #[test]
3428 fn test_ico_bmp_absurd_dims_rejected_before_alloc() {
3429 let mut bmp = vec![0u8; 40];
3431 bmp[0..4].copy_from_slice(&40u32.to_le_bytes()); bmp[4..8].copy_from_slice(&((1i32 << 24) - 2).to_le_bytes()); bmp[8..12].copy_from_slice(&((1i32 << 24) - 2).to_le_bytes()); bmp[14..16].copy_from_slice(&32u16.to_le_bytes()); assert!(
3437 decode_ico_bmp(&bmp).is_err(),
3438 "absurd ICO BMP dims with no data must error, not allocate"
3439 );
3440 }
3441
3442 #[test]
3445 fn test_ico_bad_offset_errors() {
3446 let mut data = vec![0u8; 6 + 16];
3447 data[2] = 1; data[4] = 1; data[6] = 16; data[7] = 16; 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 #[test]
3462 fn test_wbmp_sniff_multibyte_dimensions() {
3463 let data = [0u8, 0, 0x81, 0x48, 0x81, 0x48, 0, 0];
3465 assert_eq!(ImageFormat::from_magic(&data), ImageFormat::Wbmp);
3466 }
3467
3468 #[test]
3473 fn test_jpeg_dimensions_sof2_after_rst() {
3474 let data = [
3476 0xFF, 0xD8, 0xFF, 0xD0, 0xFF, 0xC2, 0x00, 0x11, 0x08, 0x00, 0x64, 0x00, 0xC8, 0x03, 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 #[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 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 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 assert_eq!(&px[0..4], &[0, 0, 0, 0], "corner is transparent");
3522 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 #[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 #[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 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}