pixels/
lib.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5mod snapshot;
6
7use std::borrow::Cow;
8use std::io::Cursor;
9use std::ops::Range;
10use std::sync::Arc;
11use std::time::Duration;
12use std::{cmp, fmt, vec};
13
14use euclid::default::{Point2D, Rect, Size2D};
15use image::codecs::{bmp, gif, ico, jpeg, png, webp};
16use image::error::ImageFormatHint;
17use image::imageops::{self, FilterType};
18use image::{
19    AnimationDecoder, DynamicImage, ImageBuffer, ImageDecoder, ImageError, ImageFormat,
20    ImageResult, Limits, Rgba,
21};
22use ipc_channel::ipc::IpcSharedMemory;
23use log::debug;
24use malloc_size_of_derive::MallocSizeOf;
25use serde::{Deserialize, Serialize};
26pub use snapshot::*;
27use webrender_api::units::DeviceIntSize;
28use webrender_api::{
29    ImageDescriptor, ImageDescriptorFlags, ImageFormat as WebRenderImageFormat, ImageKey,
30};
31
32#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
33pub enum FilterQuality {
34    /// No image interpolation (Nearest-neighbor)
35    None,
36    /// Low-quality image interpolation (Bilinear)
37    Low,
38    /// Medium-quality image interpolation (CatmullRom, Mitchell)
39    Medium,
40    /// High-quality image interpolation (Lanczos)
41    High,
42}
43
44#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
45pub enum PixelFormat {
46    /// Luminance channel only
47    K8,
48    /// Luminance + alpha
49    KA8,
50    /// RGB, 8 bits per channel
51    RGB8,
52    /// RGB + alpha, 8 bits per channel
53    RGBA8,
54    /// BGR + alpha, 8 bits per channel
55    BGRA8,
56}
57
58/// Computes image byte length, returning None if overflow occurred or the total length exceeds
59/// the maximum image allocation size.
60pub fn compute_rgba8_byte_length_if_within_limit(width: usize, height: usize) -> Option<usize> {
61    // Maximum allowed image allocation size (2^31-1 ~ 2GB).
62    const MAX_IMAGE_BYTE_LENGTH: usize = 2147483647;
63
64    // The color components of each pixel must be stored in four sequential
65    // elements in the order of red, green, blue, and then alpha.
66    4usize
67        .checked_mul(width)
68        .and_then(|v| v.checked_mul(height))
69        .filter(|v| *v <= MAX_IMAGE_BYTE_LENGTH)
70}
71
72/// Copies the rectangle of the source image to the destination image.
73pub fn copy_rgba8_image(
74    src_size: Size2D<u32>,
75    src_rect: Rect<u32>,
76    src_pixels: &[u8],
77    dest_size: Size2D<u32>,
78    dest_rect: Rect<u32>,
79    dest_pixels: &mut [u8],
80) {
81    assert!(!src_rect.is_empty());
82    assert!(!dest_rect.is_empty());
83    assert!(Rect::from_size(src_size).contains_rect(&src_rect));
84    assert!(Rect::from_size(dest_size).contains_rect(&dest_rect));
85    assert!(src_rect.size == dest_rect.size);
86    assert_eq!(src_pixels.len() % 4, 0);
87    assert_eq!(dest_pixels.len() % 4, 0);
88
89    if src_size == dest_size && src_rect == dest_rect {
90        dest_pixels.copy_from_slice(src_pixels);
91        return;
92    }
93
94    let src_first_column_start = src_rect.origin.x as usize * 4;
95    let src_row_length = src_size.width as usize * 4;
96    let src_first_row_start = src_rect.origin.y as usize * src_row_length;
97
98    let dest_first_column_start = dest_rect.origin.x as usize * 4;
99    let dest_row_length = dest_size.width as usize * 4;
100    let dest_first_row_start = dest_rect.origin.y as usize * dest_row_length;
101
102    let (chunk_length, chunk_count) = (
103        src_rect.size.width as usize * 4,
104        src_rect.size.height as usize,
105    );
106
107    for i in 0..chunk_count {
108        let src = &src_pixels[src_first_row_start + i * src_row_length..][src_first_column_start..]
109            [..chunk_length];
110        let dest = &mut dest_pixels[dest_first_row_start + i * dest_row_length..]
111            [dest_first_column_start..][..chunk_length];
112        dest.copy_from_slice(src);
113    }
114}
115
116/// Scales the source image to the required size, performing sampling filter algorithm.
117pub fn scale_rgba8_image(
118    size: Size2D<u32>,
119    pixels: &[u8],
120    required_size: Size2D<u32>,
121    quality: FilterQuality,
122) -> Option<Vec<u8>> {
123    let filter = match quality {
124        FilterQuality::None => FilterType::Nearest,
125        FilterQuality::Low => FilterType::Triangle,
126        FilterQuality::Medium => FilterType::CatmullRom,
127        FilterQuality::High => FilterType::Lanczos3,
128    };
129
130    let buffer: ImageBuffer<Rgba<u8>, &[u8]> =
131        ImageBuffer::from_raw(size.width, size.height, pixels)?;
132
133    let scaled_buffer =
134        imageops::resize(&buffer, required_size.width, required_size.height, filter);
135
136    Some(scaled_buffer.into_vec())
137}
138
139/// Flips the source image vertically in place.
140pub fn flip_y_rgba8_image_inplace(size: Size2D<u32>, pixels: &mut [u8]) {
141    assert_eq!(pixels.len() % 4, 0);
142
143    let row_length = size.width as usize * 4;
144    let half_height = (size.height / 2) as usize;
145
146    let (left, right) = pixels.split_at_mut(pixels.len() - row_length * half_height);
147
148    for i in 0..half_height {
149        let top = &mut left[i * row_length..][..row_length];
150        let bottom = &mut right[(half_height - i - 1) * row_length..][..row_length];
151        top.swap_with_slice(bottom);
152    }
153}
154
155pub fn rgba8_get_rect(pixels: &[u8], size: Size2D<u32>, rect: Rect<u32>) -> Cow<'_, [u8]> {
156    assert!(!rect.is_empty());
157    assert!(Rect::from_size(size).contains_rect(&rect));
158    assert_eq!(pixels.len() % 4, 0);
159    assert_eq!(size.area() as usize, pixels.len() / 4);
160    let area = rect.size.area() as usize;
161    let first_column_start = rect.origin.x as usize * 4;
162    let row_length = size.width as usize * 4;
163    let first_row_start = rect.origin.y as usize * row_length;
164    if rect.origin.x == 0 && rect.size.width == size.width || rect.size.height == 1 {
165        let start = first_column_start + first_row_start;
166        return Cow::Borrowed(&pixels[start..start + area * 4]);
167    }
168    let mut data = Vec::with_capacity(area * 4);
169    for row in pixels[first_row_start..]
170        .chunks(row_length)
171        .take(rect.size.height as usize)
172    {
173        data.extend_from_slice(&row[first_column_start..][..rect.size.width as usize * 4]);
174    }
175    data.into()
176}
177
178// TODO(pcwalton): Speed up with SIMD, or better yet, find some way to not do this.
179pub fn rgba8_byte_swap_colors_inplace(pixels: &mut [u8]) {
180    assert!(pixels.len() % 4 == 0);
181    for rgba in pixels.chunks_mut(4) {
182        rgba.swap(0, 2);
183    }
184}
185
186pub fn rgba8_byte_swap_and_premultiply_inplace(pixels: &mut [u8]) {
187    assert!(pixels.len() % 4 == 0);
188    for rgba in pixels.chunks_mut(4) {
189        let b = rgba[0];
190        rgba[0] = multiply_u8_color(rgba[2], rgba[3]);
191        rgba[1] = multiply_u8_color(rgba[1], rgba[3]);
192        rgba[2] = multiply_u8_color(b, rgba[3]);
193    }
194}
195
196/// Returns true if the pixels were found to be completely opaque.
197pub fn rgba8_premultiply_inplace(pixels: &mut [u8]) -> bool {
198    assert!(pixels.len() % 4 == 0);
199    let mut is_opaque = true;
200    for rgba in pixels.chunks_mut(4) {
201        rgba[0] = multiply_u8_color(rgba[0], rgba[3]);
202        rgba[1] = multiply_u8_color(rgba[1], rgba[3]);
203        rgba[2] = multiply_u8_color(rgba[2], rgba[3]);
204        is_opaque = is_opaque && rgba[3] == 255;
205    }
206    is_opaque
207}
208
209/// Returns a*b/255, rounding any fractional bits to nearest integer
210/// to reduce the loss of precision after multiple consequence alpha
211/// (un)premultiply operations.
212#[inline(always)]
213pub fn multiply_u8_color(a: u8, b: u8) -> u8 {
214    let c = a as u32 * b as u32 + 128;
215    ((c + (c >> 8)) >> 8) as u8
216}
217
218pub fn clip(
219    mut origin: Point2D<i32>,
220    mut size: Size2D<u32>,
221    surface: Size2D<u32>,
222) -> Option<Rect<u32>> {
223    if origin.x < 0 {
224        size.width = size.width.saturating_sub(-origin.x as u32);
225        origin.x = 0;
226    }
227    if origin.y < 0 {
228        size.height = size.height.saturating_sub(-origin.y as u32);
229        origin.y = 0;
230    }
231    let origin = Point2D::new(origin.x as u32, origin.y as u32);
232    Rect::new(origin, size)
233        .intersection(&Rect::from_size(surface))
234        .filter(|rect| !rect.is_empty())
235}
236
237#[derive(PartialEq)]
238pub enum EncodedImageType {
239    Png,
240    Jpeg,
241    Webp,
242}
243
244impl From<String> for EncodedImageType {
245    // From: https://html.spec.whatwg.org/multipage/#serialising-bitmaps-to-a-file
246    // User agents must support PNG ("image/png"). User agents may support other
247    // types. If the user agent does not support the requested type, then it
248    // must create the file using the PNG format.
249    // Anything different than image/jpeg or image/webp is thus treated as PNG.
250    fn from(mime_type: String) -> Self {
251        let mime = mime_type.to_lowercase();
252        if mime == "image/jpeg" {
253            Self::Jpeg
254        } else if mime == "image/webp" {
255            Self::Webp
256        } else {
257            Self::Png
258        }
259    }
260}
261
262impl EncodedImageType {
263    pub fn as_mime_type(&self) -> String {
264        match self {
265            Self::Png => "image/png",
266            Self::Jpeg => "image/jpeg",
267            Self::Webp => "image/webp",
268        }
269        .to_owned()
270    }
271}
272
273/// Whether this response passed any CORS checks, and is thus safe to read from
274/// in cross-origin environments.
275#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
276pub enum CorsStatus {
277    /// The response is either same-origin or cross-origin but passed CORS checks.
278    Safe,
279    /// The response is cross-origin and did not pass CORS checks. It is unsafe
280    /// to expose pixel data to the requesting environment.
281    Unsafe,
282}
283
284#[derive(Clone, Deserialize, MallocSizeOf, Serialize)]
285pub struct RasterImage {
286    pub metadata: ImageMetadata,
287    pub format: PixelFormat,
288    pub id: Option<ImageKey>,
289    pub cors_status: CorsStatus,
290    #[conditional_malloc_size_of]
291    pub bytes: Arc<IpcSharedMemory>,
292    pub frames: Vec<ImageFrame>,
293    /// Whether or not all of the frames of this image are opaque.
294    pub is_opaque: bool,
295}
296
297fn sensible_delay(delay: Duration) -> Duration {
298    // Very small timeout values are problematic for two reasons: we don't want
299    // to burn energy redrawing animated images extremely fast, and broken tools
300    // generate these values when they actually want a "default" value, so such
301    // images won't play back right without normalization.
302    // https://searchfox.org/firefox-main/rev/c79acad610ddbb31bd92e837e056b53716f5ccf2/image/FrameTimeout.h#35
303    if delay <= Duration::from_millis(10) {
304        Duration::from_millis(100)
305    } else {
306        delay
307    }
308}
309
310#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
311pub struct ImageFrame {
312    pub delay: Option<Duration>,
313    /// References a range of the `bytes` field from the image that this
314    /// frame belongs to.
315    pub byte_range: Range<usize>,
316    pub width: u32,
317    pub height: u32,
318}
319
320impl ImageFrame {
321    pub fn delay(&self) -> Option<Duration> {
322        self.delay.map(sensible_delay)
323    }
324}
325
326/// A non-owning reference to the data of an [ImageFrame]
327pub struct ImageFrameView<'a> {
328    pub delay: Option<Duration>,
329    pub bytes: &'a [u8],
330    pub width: u32,
331    pub height: u32,
332}
333
334impl ImageFrameView<'_> {
335    pub fn delay(&self) -> Option<Duration> {
336        self.delay.map(sensible_delay)
337    }
338}
339
340impl RasterImage {
341    pub fn should_animate(&self) -> bool {
342        self.frames.len() > 1
343    }
344
345    fn frame_view<'image>(&'image self, frame: &ImageFrame) -> ImageFrameView<'image> {
346        ImageFrameView {
347            delay: frame.delay,
348            bytes: self.bytes.get(frame.byte_range.clone()).unwrap(),
349            width: frame.width,
350            height: frame.height,
351        }
352    }
353
354    pub fn frame(&self, index: usize) -> Option<ImageFrameView<'_>> {
355        self.frames.get(index).map(|frame| self.frame_view(frame))
356    }
357
358    pub fn first_frame(&self) -> ImageFrameView<'_> {
359        self.frame(0)
360            .expect("All images should have at least one frame")
361    }
362
363    pub fn as_snapshot(&self) -> Snapshot {
364        let size = Size2D::new(self.metadata.width, self.metadata.height);
365        let format = match self.format {
366            PixelFormat::BGRA8 => SnapshotPixelFormat::BGRA,
367            PixelFormat::RGBA8 => SnapshotPixelFormat::RGBA,
368            pixel_format => {
369                unimplemented!("unsupported pixel format ({pixel_format:?})");
370            },
371        };
372
373        let alpha_mode = SnapshotAlphaMode::Transparent {
374            premultiplied: true,
375        };
376
377        Snapshot::from_shared_memory(
378            size.cast(),
379            format,
380            alpha_mode,
381            self.bytes.clone(),
382            self.frames[0].byte_range.clone(),
383        )
384    }
385
386    pub fn webrender_image_descriptor_and_data_for_frame(
387        &self,
388        frame_index: usize,
389    ) -> (ImageDescriptor, IpcSharedMemory) {
390        let frame = self
391            .frames
392            .get(frame_index)
393            .expect("Asked for a frame that did not exist: {frame_index:?}");
394
395        let (format, ipc_shared_memory) = match self.format {
396            PixelFormat::BGRA8 => (WebRenderImageFormat::BGRA8, (*self.bytes).clone()),
397            PixelFormat::RGBA8 => (WebRenderImageFormat::RGBA8, (*self.bytes).clone()),
398            PixelFormat::RGB8 => {
399                let frame_bytes = &self.bytes[frame.byte_range.clone()];
400                let mut bytes = Vec::with_capacity(frame_bytes.len() / 3 * 4);
401                for rgb in frame_bytes.chunks(3) {
402                    bytes.extend_from_slice(&[rgb[2], rgb[1], rgb[0], 0xff]);
403                }
404                (
405                    WebRenderImageFormat::BGRA8,
406                    IpcSharedMemory::from_bytes(&bytes),
407                )
408            },
409            PixelFormat::K8 | PixelFormat::KA8 => {
410                panic!("Not support by webrender yet");
411            },
412        };
413        let mut flags = ImageDescriptorFlags::ALLOW_MIPMAPS;
414        flags.set(ImageDescriptorFlags::IS_OPAQUE, self.is_opaque);
415
416        let size = DeviceIntSize::new(self.metadata.width as i32, self.metadata.height as i32);
417        let descriptor = ImageDescriptor {
418            size,
419            stride: None,
420            format,
421            offset: frame.byte_range.start as i32,
422            flags,
423        };
424        (descriptor, ipc_shared_memory)
425    }
426}
427
428impl fmt::Debug for RasterImage {
429    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
430        write!(
431            f,
432            "Image {{ width: {}, height: {}, format: {:?}, ..., id: {:?} }}",
433            self.metadata.width, self.metadata.height, self.format, self.id
434        )
435    }
436}
437
438#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
439pub struct ImageMetadata {
440    pub width: u32,
441    pub height: u32,
442}
443
444// FIXME: Images must not be copied every frame. Instead we should atomically
445// reference count them.
446
447pub fn load_from_memory(buffer: &[u8], cors_status: CorsStatus) -> Option<RasterImage> {
448    if buffer.is_empty() {
449        return None;
450    }
451
452    let image_fmt_result = detect_image_format(buffer);
453    match image_fmt_result {
454        Err(msg) => {
455            debug!("{}", msg);
456            None
457        },
458        Ok(format) => {
459            let Ok(image_decoder) = make_decoder(format, buffer) else {
460                return None;
461            };
462            match image_decoder {
463                GenericImageDecoder::Png(png_decoder) => {
464                    if png_decoder.is_apng().unwrap_or_default() {
465                        let Ok(apng_decoder) = png_decoder.apng() else {
466                            return None;
467                        };
468                        decode_animated_image(cors_status, apng_decoder)
469                    } else {
470                        decode_static_image(cors_status, *png_decoder)
471                    }
472                },
473                GenericImageDecoder::Gif(animation_decoder) => {
474                    decode_animated_image(cors_status, *animation_decoder)
475                },
476                GenericImageDecoder::Webp(webp_decoder) => {
477                    if webp_decoder.has_animation() {
478                        decode_animated_image(cors_status, *webp_decoder)
479                    } else {
480                        decode_static_image(cors_status, *webp_decoder)
481                    }
482                },
483                GenericImageDecoder::Bmp(image_decoder) => {
484                    decode_static_image(cors_status, *image_decoder)
485                },
486                GenericImageDecoder::Jpeg(image_decoder) => {
487                    decode_static_image(cors_status, *image_decoder)
488                },
489                GenericImageDecoder::Ico(image_decoder) => {
490                    decode_static_image(cors_status, *image_decoder)
491                },
492            }
493        },
494    }
495}
496
497// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img
498pub fn detect_image_format(buffer: &[u8]) -> Result<ImageFormat, &str> {
499    if is_gif(buffer) {
500        Ok(ImageFormat::Gif)
501    } else if is_jpeg(buffer) {
502        Ok(ImageFormat::Jpeg)
503    } else if is_png(buffer) {
504        Ok(ImageFormat::Png)
505    } else if is_webp(buffer) {
506        Ok(ImageFormat::WebP)
507    } else if is_bmp(buffer) {
508        Ok(ImageFormat::Bmp)
509    } else if is_ico(buffer) {
510        Ok(ImageFormat::Ico)
511    } else {
512        Err("Image Format Not Supported")
513    }
514}
515
516pub fn unmultiply_inplace<const SWAP_RB: bool>(pixels: &mut [u8]) {
517    for rgba in pixels.chunks_mut(4) {
518        let a = rgba[3] as u32;
519        let mut b = rgba[2] as u32;
520        let mut g = rgba[1] as u32;
521        let mut r = rgba[0] as u32;
522
523        if a > 0 {
524            r = r * 255 / a;
525            g = g * 255 / a;
526            b = b * 255 / a;
527
528            if SWAP_RB {
529                rgba[2] = r as u8;
530                rgba[1] = g as u8;
531                rgba[0] = b as u8;
532            } else {
533                rgba[2] = b as u8;
534                rgba[1] = g as u8;
535                rgba[0] = r as u8;
536            }
537        }
538    }
539}
540
541#[repr(u8)]
542pub enum Multiply {
543    None = 0,
544    PreMultiply = 1,
545    UnMultiply = 2,
546}
547
548pub fn transform_inplace(pixels: &mut [u8], multiply: Multiply, swap_rb: bool, clear_alpha: bool) {
549    match (multiply, swap_rb, clear_alpha) {
550        (Multiply::None, true, true) => generic_transform_inplace::<0, true, true>(pixels),
551        (Multiply::None, true, false) => generic_transform_inplace::<0, true, false>(pixels),
552        (Multiply::None, false, true) => generic_transform_inplace::<0, false, true>(pixels),
553        (Multiply::None, false, false) => generic_transform_inplace::<0, false, false>(pixels),
554        (Multiply::PreMultiply, true, true) => generic_transform_inplace::<1, true, true>(pixels),
555        (Multiply::PreMultiply, true, false) => generic_transform_inplace::<1, true, false>(pixels),
556        (Multiply::PreMultiply, false, true) => generic_transform_inplace::<1, false, true>(pixels),
557        (Multiply::PreMultiply, false, false) => {
558            generic_transform_inplace::<1, false, false>(pixels)
559        },
560        (Multiply::UnMultiply, true, true) => generic_transform_inplace::<2, true, true>(pixels),
561        (Multiply::UnMultiply, true, false) => generic_transform_inplace::<2, true, false>(pixels),
562        (Multiply::UnMultiply, false, true) => generic_transform_inplace::<2, false, true>(pixels),
563        (Multiply::UnMultiply, false, false) => {
564            generic_transform_inplace::<2, false, false>(pixels)
565        },
566    }
567}
568
569pub fn generic_transform_inplace<
570    const MULTIPLY: u8, // 1 premultiply, 2 unmultiply
571    const SWAP_RB: bool,
572    const CLEAR_ALPHA: bool,
573>(
574    pixels: &mut [u8],
575) {
576    for rgba in pixels.chunks_mut(4) {
577        match MULTIPLY {
578            1 => {
579                let a = rgba[3];
580
581                rgba[0] = multiply_u8_color(rgba[0], a);
582                rgba[1] = multiply_u8_color(rgba[1], a);
583                rgba[2] = multiply_u8_color(rgba[2], a);
584            },
585            2 => {
586                let a = rgba[3] as u32;
587
588                if a > 0 {
589                    rgba[0] = (rgba[0] as u32 * 255 / a) as u8;
590                    rgba[1] = (rgba[1] as u32 * 255 / a) as u8;
591                    rgba[2] = (rgba[2] as u32 * 255 / a) as u8;
592                }
593            },
594            _ => {},
595        }
596        if SWAP_RB {
597            rgba.swap(0, 2);
598        }
599        if CLEAR_ALPHA {
600            rgba[3] = u8::MAX;
601        }
602    }
603}
604
605fn is_gif(buffer: &[u8]) -> bool {
606    buffer.starts_with(b"GIF87a") || buffer.starts_with(b"GIF89a")
607}
608
609fn is_jpeg(buffer: &[u8]) -> bool {
610    buffer.starts_with(&[0xff, 0xd8, 0xff])
611}
612
613fn is_png(buffer: &[u8]) -> bool {
614    buffer.starts_with(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])
615}
616
617fn is_bmp(buffer: &[u8]) -> bool {
618    buffer.starts_with(&[0x42, 0x4D])
619}
620
621fn is_ico(buffer: &[u8]) -> bool {
622    buffer.starts_with(&[0x00, 0x00, 0x01, 0x00])
623}
624
625fn is_webp(buffer: &[u8]) -> bool {
626    // https://developers.google.com/speed/webp/docs/riff_container
627    // First four bytes: `RIFF`, header size 12 bytes
628    if !buffer.starts_with(b"RIFF") || buffer.len() < 12 {
629        return false;
630    }
631    let size: [u8; 4] = [buffer[4], buffer[5], buffer[6], buffer[7]];
632    // Bytes 4..8 are a little endian u32 indicating
633    // > The size of the file in bytes, starting at offset 8.
634    // > The maximum value of this field is 2^32 minus 10 bytes and thus the size
635    // > of the whole file is at most 4 GiB minus 2 bytes.
636    let len: usize = u32::from_le_bytes(size) as usize;
637    buffer[8..].len() >= len && &buffer[8..12] == b"WEBP"
638}
639
640enum GenericImageDecoder<R: std::io::BufRead + std::io::Seek> {
641    Png(Box<png::PngDecoder<R>>),
642    Gif(Box<gif::GifDecoder<R>>),
643    Webp(Box<webp::WebPDecoder<R>>),
644    Jpeg(Box<jpeg::JpegDecoder<R>>),
645    Bmp(Box<bmp::BmpDecoder<R>>),
646    Ico(Box<ico::IcoDecoder<R>>),
647}
648
649fn make_decoder(
650    format: ImageFormat,
651    buffer: &[u8],
652) -> ImageResult<GenericImageDecoder<Cursor<&[u8]>>> {
653    let limits = Limits::default();
654    let reader = Cursor::new(buffer);
655    Ok(match format {
656        ImageFormat::Png => {
657            GenericImageDecoder::Png(Box::new(png::PngDecoder::with_limits(reader, limits)?))
658        },
659        ImageFormat::Gif => GenericImageDecoder::Gif(Box::new(gif::GifDecoder::new(reader)?)),
660        ImageFormat::WebP => GenericImageDecoder::Webp(Box::new(webp::WebPDecoder::new(reader)?)),
661        ImageFormat::Jpeg => GenericImageDecoder::Jpeg(Box::new(jpeg::JpegDecoder::new(reader)?)),
662        ImageFormat::Bmp => GenericImageDecoder::Bmp(Box::new(bmp::BmpDecoder::new(reader)?)),
663        ImageFormat::Ico => GenericImageDecoder::Ico(Box::new(ico::IcoDecoder::new(reader)?)),
664        _ => {
665            return Err(ImageError::Unsupported(
666                ImageFormatHint::Exact(format).into(),
667            ));
668        },
669    })
670}
671
672fn decode_static_image(
673    cors_status: CorsStatus,
674    image_decoder: impl ImageDecoder,
675) -> Option<RasterImage> {
676    let Ok(dynamic_image) = DynamicImage::from_decoder(image_decoder) else {
677        debug!("Image decoding error");
678        return None;
679    };
680    let mut rgba = dynamic_image.into_rgba8();
681
682    // Store pre-multiplied data as that prevents having to do conversions of the data at later
683    // times. This does cause an issue with some canvas APIs. See:
684    // https://github.com/servo/servo/issues/40257
685    let is_opaque = rgba8_premultiply_inplace(&mut rgba);
686
687    let frame = ImageFrame {
688        delay: None,
689        byte_range: 0..rgba.len(),
690        width: rgba.width(),
691        height: rgba.height(),
692    };
693    Some(RasterImage {
694        metadata: ImageMetadata {
695            width: rgba.width(),
696            height: rgba.height(),
697        },
698        format: PixelFormat::RGBA8,
699        frames: vec![frame],
700        bytes: Arc::new(IpcSharedMemory::from_bytes(&rgba)),
701        id: None,
702        cors_status,
703        is_opaque,
704    })
705}
706
707fn decode_animated_image<'a, T>(
708    cors_status: CorsStatus,
709    animated_image_decoder: T,
710) -> Option<RasterImage>
711where
712    T: AnimationDecoder<'a>,
713{
714    let mut width = 0;
715    let mut height = 0;
716
717    // This uses `map_while`, because the first non-decodable frame seems to
718    // send the frame iterator into an infinite loop. See
719    // <https://github.com/image-rs/image/issues/2442>.
720    let mut frame_data = vec![];
721    let mut total_number_of_bytes = 0;
722    let mut is_opaque = true;
723    let frames: Vec<ImageFrame> = animated_image_decoder
724        .into_frames()
725        .map_while(|decoded_frame| {
726            let mut animated_frame = match decoded_frame {
727                Ok(decoded_frame) => decoded_frame,
728                Err(error) => {
729                    debug!("decode Animated frame error: {error}");
730                    return None;
731                },
732            };
733
734            // Store pre-multiplied data as that prevents having to do conversions of the data at later
735            // times. This does cause an issue with some canvas APIs. See:
736            // https://github.com/servo/servo/issues/40257
737            is_opaque = rgba8_premultiply_inplace(animated_frame.buffer_mut()) && is_opaque;
738
739            let frame_start = total_number_of_bytes;
740            total_number_of_bytes += animated_frame.buffer().len();
741
742            // The image size should be at least as large as the largest frame.
743            let frame_width = animated_frame.buffer().width();
744            let frame_height = animated_frame.buffer().height();
745            width = cmp::max(width, frame_width);
746            height = cmp::max(height, frame_height);
747
748            let frame = ImageFrame {
749                byte_range: frame_start..total_number_of_bytes,
750                delay: Some(Duration::from(animated_frame.delay())),
751                width: frame_width,
752                height: frame_height,
753            };
754
755            frame_data.push(animated_frame);
756
757            Some(frame)
758        })
759        .collect();
760
761    if frames.is_empty() {
762        debug!("Animated Image decoding error");
763        return None;
764    }
765
766    // Coalesce the frame data into one single shared memory region.
767    let mut bytes = Vec::with_capacity(total_number_of_bytes);
768    for frame in frame_data {
769        bytes.extend_from_slice(frame.buffer());
770    }
771
772    Some(RasterImage {
773        metadata: ImageMetadata { width, height },
774        cors_status,
775        frames,
776        id: None,
777        format: PixelFormat::RGBA8,
778        bytes: Arc::new(IpcSharedMemory::from_bytes(&bytes)),
779        is_opaque,
780    })
781}
782
783#[cfg(test)]
784mod test {
785    use super::detect_image_format;
786
787    #[test]
788    fn test_supported_images() {
789        let gif1 = [b'G', b'I', b'F', b'8', b'7', b'a'];
790        let gif2 = [b'G', b'I', b'F', b'8', b'9', b'a'];
791        let jpeg = [0xff, 0xd8, 0xff];
792        let png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
793        let webp = [
794            b'R', b'I', b'F', b'F', 0x04, 0x00, 0x00, 0x00, b'W', b'E', b'B', b'P',
795        ];
796        let bmp = [0x42, 0x4D];
797        let ico = [0x00, 0x00, 0x01, 0x00];
798        let junk_format = [0x01, 0x02, 0x03, 0x04, 0x05];
799
800        assert!(detect_image_format(&gif1).is_ok());
801        assert!(detect_image_format(&gif2).is_ok());
802        assert!(detect_image_format(&jpeg).is_ok());
803        assert!(detect_image_format(&png).is_ok());
804        assert!(detect_image_format(&webp).is_ok());
805        assert!(detect_image_format(&bmp).is_ok());
806        assert!(detect_image_format(&ico).is_ok());
807        assert!(detect_image_format(&junk_format).is_err());
808    }
809}