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/// A version of [`RasterImage`] that can be sent across IPC channels.
285#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
286pub struct SharedRasterImage {
287    pub metadata: ImageMetadata,
288    pub format: PixelFormat,
289    pub id: Option<ImageKey>,
290    pub cors_status: CorsStatus,
291    #[conditional_malloc_size_of]
292    pub bytes: Arc<IpcSharedMemory>,
293    pub frames: Vec<ImageFrame>,
294    /// Whether or not all of the frames of this image are opaque.
295    pub is_opaque: bool,
296}
297
298#[derive(Clone, MallocSizeOf)]
299pub struct RasterImage {
300    pub metadata: ImageMetadata,
301    pub format: PixelFormat,
302    pub id: Option<ImageKey>,
303    pub cors_status: CorsStatus,
304    #[conditional_malloc_size_of]
305    pub bytes: Arc<Vec<u8>>,
306    pub frames: Vec<ImageFrame>,
307    /// Whether or not all of the frames of this image are opaque.
308    pub is_opaque: bool,
309}
310
311fn sensible_delay(delay: Duration) -> Duration {
312    // Very small timeout values are problematic for two reasons: we don't want
313    // to burn energy redrawing animated images extremely fast, and broken tools
314    // generate these values when they actually want a "default" value, so such
315    // images won't play back right without normalization.
316    // https://searchfox.org/firefox-main/rev/c79acad610ddbb31bd92e837e056b53716f5ccf2/image/FrameTimeout.h#35
317    if delay <= Duration::from_millis(10) {
318        Duration::from_millis(100)
319    } else {
320        delay
321    }
322}
323
324#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
325pub struct ImageFrame {
326    pub delay: Option<Duration>,
327    /// References a range of the `bytes` field from the image that this
328    /// frame belongs to.
329    pub byte_range: Range<usize>,
330    pub width: u32,
331    pub height: u32,
332}
333
334impl ImageFrame {
335    pub fn delay(&self) -> Option<Duration> {
336        self.delay.map(sensible_delay)
337    }
338}
339
340/// A non-owning reference to the data of an [ImageFrame]
341pub struct ImageFrameView<'a> {
342    pub delay: Option<Duration>,
343    pub bytes: &'a [u8],
344    pub width: u32,
345    pub height: u32,
346}
347
348impl ImageFrameView<'_> {
349    pub fn delay(&self) -> Option<Duration> {
350        self.delay.map(sensible_delay)
351    }
352}
353
354impl RasterImage {
355    pub fn should_animate(&self) -> bool {
356        self.frames.len() > 1
357    }
358
359    fn frame_view<'image>(&'image self, frame: &ImageFrame) -> ImageFrameView<'image> {
360        ImageFrameView {
361            delay: frame.delay,
362            bytes: self.bytes.get(frame.byte_range.clone()).unwrap(),
363            width: frame.width,
364            height: frame.height,
365        }
366    }
367
368    pub fn frame(&self, index: usize) -> Option<ImageFrameView<'_>> {
369        self.frames.get(index).map(|frame| self.frame_view(frame))
370    }
371
372    pub fn first_frame(&self) -> ImageFrameView<'_> {
373        self.frame(0)
374            .expect("All images should have at least one frame")
375    }
376
377    pub fn as_snapshot(&self) -> Snapshot {
378        let size = Size2D::new(self.metadata.width, self.metadata.height);
379        let format = match self.format {
380            PixelFormat::BGRA8 => SnapshotPixelFormat::BGRA,
381            PixelFormat::RGBA8 => SnapshotPixelFormat::RGBA,
382            pixel_format => {
383                unimplemented!("unsupported pixel format ({pixel_format:?})");
384            },
385        };
386
387        let alpha_mode = SnapshotAlphaMode::Transparent {
388            premultiplied: true,
389        };
390
391        Snapshot::from_arc_vec(
392            size.cast(),
393            format,
394            alpha_mode,
395            self.bytes.clone(),
396            self.frames[0].byte_range.clone(),
397        )
398    }
399
400    pub fn webrender_image_descriptor_and_data_for_frame(
401        &self,
402        frame_index: usize,
403    ) -> (ImageDescriptor, IpcSharedMemory) {
404        let frame = self
405            .frames
406            .get(frame_index)
407            .expect("Asked for a frame that did not exist: {frame_index:?}");
408
409        let (format, data) = match self.format {
410            PixelFormat::BGRA8 => (WebRenderImageFormat::BGRA8, (*self.bytes).clone()),
411            PixelFormat::RGBA8 => (WebRenderImageFormat::RGBA8, (*self.bytes).clone()),
412            PixelFormat::RGB8 => {
413                let frame_bytes = &self.bytes[frame.byte_range.clone()];
414                let mut bytes = Vec::with_capacity(frame_bytes.len() / 3 * 4);
415                for rgb in frame_bytes.chunks(3) {
416                    bytes.extend_from_slice(&[rgb[2], rgb[1], rgb[0], 0xff]);
417                }
418                (WebRenderImageFormat::BGRA8, bytes)
419            },
420            PixelFormat::K8 | PixelFormat::KA8 => {
421                panic!("Not support by webrender yet");
422            },
423        };
424        let mut flags = ImageDescriptorFlags::ALLOW_MIPMAPS;
425        flags.set(ImageDescriptorFlags::IS_OPAQUE, self.is_opaque);
426
427        let size = DeviceIntSize::new(self.metadata.width as i32, self.metadata.height as i32);
428        let descriptor = ImageDescriptor {
429            size,
430            stride: None,
431            format,
432            offset: frame.byte_range.start as i32,
433            flags,
434        };
435        (descriptor, IpcSharedMemory::from_bytes(&data))
436    }
437
438    pub fn to_shared(&self) -> Arc<SharedRasterImage> {
439        Arc::new(SharedRasterImage {
440            metadata: self.metadata,
441            format: self.format,
442            id: self.id,
443            cors_status: self.cors_status,
444            bytes: Arc::new(IpcSharedMemory::from_bytes(&self.bytes)),
445            frames: self.frames.clone(),
446            is_opaque: self.is_opaque,
447        })
448    }
449}
450
451impl fmt::Debug for RasterImage {
452    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
453        write!(
454            f,
455            "Image {{ width: {}, height: {}, format: {:?}, ..., id: {:?} }}",
456            self.metadata.width, self.metadata.height, self.format, self.id
457        )
458    }
459}
460
461#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
462pub struct ImageMetadata {
463    pub width: u32,
464    pub height: u32,
465}
466
467// FIXME: Images must not be copied every frame. Instead we should atomically
468// reference count them.
469
470pub fn load_from_memory(buffer: &[u8], cors_status: CorsStatus) -> Option<RasterImage> {
471    if buffer.is_empty() {
472        return None;
473    }
474
475    let image_fmt_result = detect_image_format(buffer);
476    match image_fmt_result {
477        Err(msg) => {
478            debug!("{}", msg);
479            None
480        },
481        Ok(format) => {
482            let Ok(image_decoder) = make_decoder(format, buffer) else {
483                return None;
484            };
485            match image_decoder {
486                GenericImageDecoder::Png(png_decoder) => {
487                    if png_decoder.is_apng().unwrap_or_default() {
488                        let Ok(apng_decoder) = png_decoder.apng() else {
489                            return None;
490                        };
491                        decode_animated_image(cors_status, apng_decoder)
492                    } else {
493                        decode_static_image(cors_status, *png_decoder)
494                    }
495                },
496                GenericImageDecoder::Gif(animation_decoder) => {
497                    decode_animated_image(cors_status, *animation_decoder)
498                },
499                GenericImageDecoder::Webp(webp_decoder) => {
500                    if webp_decoder.has_animation() {
501                        decode_animated_image(cors_status, *webp_decoder)
502                    } else {
503                        decode_static_image(cors_status, *webp_decoder)
504                    }
505                },
506                GenericImageDecoder::Bmp(image_decoder) => {
507                    decode_static_image(cors_status, *image_decoder)
508                },
509                GenericImageDecoder::Jpeg(image_decoder) => {
510                    decode_static_image(cors_status, *image_decoder)
511                },
512                GenericImageDecoder::Ico(image_decoder) => {
513                    decode_static_image(cors_status, *image_decoder)
514                },
515            }
516        },
517    }
518}
519
520// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img
521pub fn detect_image_format(buffer: &[u8]) -> Result<ImageFormat, &str> {
522    if is_gif(buffer) {
523        Ok(ImageFormat::Gif)
524    } else if is_jpeg(buffer) {
525        Ok(ImageFormat::Jpeg)
526    } else if is_png(buffer) {
527        Ok(ImageFormat::Png)
528    } else if is_webp(buffer) {
529        Ok(ImageFormat::WebP)
530    } else if is_bmp(buffer) {
531        Ok(ImageFormat::Bmp)
532    } else if is_ico(buffer) {
533        Ok(ImageFormat::Ico)
534    } else {
535        Err("Image Format Not Supported")
536    }
537}
538
539pub fn unmultiply_inplace<const SWAP_RB: bool>(pixels: &mut [u8]) {
540    for rgba in pixels.chunks_mut(4) {
541        let a = rgba[3] as u32;
542        let mut b = rgba[2] as u32;
543        let mut g = rgba[1] as u32;
544        let mut r = rgba[0] as u32;
545
546        if a > 0 {
547            r = r * 255 / a;
548            g = g * 255 / a;
549            b = b * 255 / a;
550
551            if SWAP_RB {
552                rgba[2] = r as u8;
553                rgba[1] = g as u8;
554                rgba[0] = b as u8;
555            } else {
556                rgba[2] = b as u8;
557                rgba[1] = g as u8;
558                rgba[0] = r as u8;
559            }
560        }
561    }
562}
563
564#[repr(u8)]
565pub enum Multiply {
566    None = 0,
567    PreMultiply = 1,
568    UnMultiply = 2,
569}
570
571pub fn transform_inplace(pixels: &mut [u8], multiply: Multiply, swap_rb: bool, clear_alpha: bool) {
572    match (multiply, swap_rb, clear_alpha) {
573        (Multiply::None, true, true) => generic_transform_inplace::<0, true, true>(pixels),
574        (Multiply::None, true, false) => generic_transform_inplace::<0, true, false>(pixels),
575        (Multiply::None, false, true) => generic_transform_inplace::<0, false, true>(pixels),
576        (Multiply::None, false, false) => generic_transform_inplace::<0, false, false>(pixels),
577        (Multiply::PreMultiply, true, true) => generic_transform_inplace::<1, true, true>(pixels),
578        (Multiply::PreMultiply, true, false) => generic_transform_inplace::<1, true, false>(pixels),
579        (Multiply::PreMultiply, false, true) => generic_transform_inplace::<1, false, true>(pixels),
580        (Multiply::PreMultiply, false, false) => {
581            generic_transform_inplace::<1, false, false>(pixels)
582        },
583        (Multiply::UnMultiply, true, true) => generic_transform_inplace::<2, true, true>(pixels),
584        (Multiply::UnMultiply, true, false) => generic_transform_inplace::<2, true, false>(pixels),
585        (Multiply::UnMultiply, false, true) => generic_transform_inplace::<2, false, true>(pixels),
586        (Multiply::UnMultiply, false, false) => {
587            generic_transform_inplace::<2, false, false>(pixels)
588        },
589    }
590}
591
592pub fn generic_transform_inplace<
593    const MULTIPLY: u8, // 1 premultiply, 2 unmultiply
594    const SWAP_RB: bool,
595    const CLEAR_ALPHA: bool,
596>(
597    pixels: &mut [u8],
598) {
599    for rgba in pixels.chunks_mut(4) {
600        match MULTIPLY {
601            1 => {
602                let a = rgba[3];
603
604                rgba[0] = multiply_u8_color(rgba[0], a);
605                rgba[1] = multiply_u8_color(rgba[1], a);
606                rgba[2] = multiply_u8_color(rgba[2], a);
607            },
608            2 => {
609                let a = rgba[3] as u32;
610
611                if a > 0 {
612                    rgba[0] = (rgba[0] as u32 * 255 / a) as u8;
613                    rgba[1] = (rgba[1] as u32 * 255 / a) as u8;
614                    rgba[2] = (rgba[2] as u32 * 255 / a) as u8;
615                }
616            },
617            _ => {},
618        }
619        if SWAP_RB {
620            rgba.swap(0, 2);
621        }
622        if CLEAR_ALPHA {
623            rgba[3] = u8::MAX;
624        }
625    }
626}
627
628fn is_gif(buffer: &[u8]) -> bool {
629    buffer.starts_with(b"GIF87a") || buffer.starts_with(b"GIF89a")
630}
631
632fn is_jpeg(buffer: &[u8]) -> bool {
633    buffer.starts_with(&[0xff, 0xd8, 0xff])
634}
635
636fn is_png(buffer: &[u8]) -> bool {
637    buffer.starts_with(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])
638}
639
640fn is_bmp(buffer: &[u8]) -> bool {
641    buffer.starts_with(&[0x42, 0x4D])
642}
643
644fn is_ico(buffer: &[u8]) -> bool {
645    buffer.starts_with(&[0x00, 0x00, 0x01, 0x00])
646}
647
648fn is_webp(buffer: &[u8]) -> bool {
649    // https://developers.google.com/speed/webp/docs/riff_container
650    // First four bytes: `RIFF`, header size 12 bytes
651    if !buffer.starts_with(b"RIFF") || buffer.len() < 12 {
652        return false;
653    }
654    let size: [u8; 4] = [buffer[4], buffer[5], buffer[6], buffer[7]];
655    // Bytes 4..8 are a little endian u32 indicating
656    // > The size of the file in bytes, starting at offset 8.
657    // > The maximum value of this field is 2^32 minus 10 bytes and thus the size
658    // > of the whole file is at most 4 GiB minus 2 bytes.
659    let len: usize = u32::from_le_bytes(size) as usize;
660    buffer[8..].len() >= len && &buffer[8..12] == b"WEBP"
661}
662
663enum GenericImageDecoder<R: std::io::BufRead + std::io::Seek> {
664    Png(Box<png::PngDecoder<R>>),
665    Gif(Box<gif::GifDecoder<R>>),
666    Webp(Box<webp::WebPDecoder<R>>),
667    Jpeg(Box<jpeg::JpegDecoder<R>>),
668    Bmp(Box<bmp::BmpDecoder<R>>),
669    Ico(Box<ico::IcoDecoder<R>>),
670}
671
672fn make_decoder(
673    format: ImageFormat,
674    buffer: &[u8],
675) -> ImageResult<GenericImageDecoder<Cursor<&[u8]>>> {
676    let limits = Limits::default();
677    let reader = Cursor::new(buffer);
678    Ok(match format {
679        ImageFormat::Png => {
680            GenericImageDecoder::Png(Box::new(png::PngDecoder::with_limits(reader, limits)?))
681        },
682        ImageFormat::Gif => GenericImageDecoder::Gif(Box::new(gif::GifDecoder::new(reader)?)),
683        ImageFormat::WebP => GenericImageDecoder::Webp(Box::new(webp::WebPDecoder::new(reader)?)),
684        ImageFormat::Jpeg => GenericImageDecoder::Jpeg(Box::new(jpeg::JpegDecoder::new(reader)?)),
685        ImageFormat::Bmp => GenericImageDecoder::Bmp(Box::new(bmp::BmpDecoder::new(reader)?)),
686        ImageFormat::Ico => GenericImageDecoder::Ico(Box::new(ico::IcoDecoder::new(reader)?)),
687        _ => {
688            return Err(ImageError::Unsupported(
689                ImageFormatHint::Exact(format).into(),
690            ));
691        },
692    })
693}
694
695fn decode_static_image(
696    cors_status: CorsStatus,
697    image_decoder: impl ImageDecoder,
698) -> Option<RasterImage> {
699    let Ok(dynamic_image) = DynamicImage::from_decoder(image_decoder) else {
700        debug!("Image decoding error");
701        return None;
702    };
703    let mut rgba = dynamic_image.into_rgba8();
704
705    // Store pre-multiplied data as that prevents having to do conversions of the data at later
706    // times. This does cause an issue with some canvas APIs. See:
707    // https://github.com/servo/servo/issues/40257
708    let is_opaque = rgba8_premultiply_inplace(&mut rgba);
709
710    let frame = ImageFrame {
711        delay: None,
712        byte_range: 0..rgba.len(),
713        width: rgba.width(),
714        height: rgba.height(),
715    };
716    Some(RasterImage {
717        metadata: ImageMetadata {
718            width: rgba.width(),
719            height: rgba.height(),
720        },
721        format: PixelFormat::RGBA8,
722        frames: vec![frame],
723        bytes: Arc::new(rgba.to_vec()),
724        id: None,
725        cors_status,
726        is_opaque,
727    })
728}
729
730fn decode_animated_image<'a, T>(
731    cors_status: CorsStatus,
732    animated_image_decoder: T,
733) -> Option<RasterImage>
734where
735    T: AnimationDecoder<'a>,
736{
737    let mut width = 0;
738    let mut height = 0;
739
740    // This uses `map_while`, because the first non-decodable frame seems to
741    // send the frame iterator into an infinite loop. See
742    // <https://github.com/image-rs/image/issues/2442>.
743    let mut frame_data = vec![];
744    let mut total_number_of_bytes = 0;
745    let mut is_opaque = true;
746    let frames: Vec<ImageFrame> = animated_image_decoder
747        .into_frames()
748        .map_while(|decoded_frame| {
749            let mut animated_frame = match decoded_frame {
750                Ok(decoded_frame) => decoded_frame,
751                Err(error) => {
752                    debug!("decode Animated frame error: {error}");
753                    return None;
754                },
755            };
756
757            // Store pre-multiplied data as that prevents having to do conversions of the data at later
758            // times. This does cause an issue with some canvas APIs. See:
759            // https://github.com/servo/servo/issues/40257
760            is_opaque = rgba8_premultiply_inplace(animated_frame.buffer_mut()) && is_opaque;
761
762            let frame_start = total_number_of_bytes;
763            total_number_of_bytes += animated_frame.buffer().len();
764
765            // The image size should be at least as large as the largest frame.
766            let frame_width = animated_frame.buffer().width();
767            let frame_height = animated_frame.buffer().height();
768            width = cmp::max(width, frame_width);
769            height = cmp::max(height, frame_height);
770
771            let frame = ImageFrame {
772                byte_range: frame_start..total_number_of_bytes,
773                delay: Some(Duration::from(animated_frame.delay())),
774                width: frame_width,
775                height: frame_height,
776            };
777
778            frame_data.push(animated_frame);
779
780            Some(frame)
781        })
782        .collect();
783
784    if frames.is_empty() {
785        debug!("Animated Image decoding error");
786        return None;
787    }
788
789    // Coalesce the frame data into one single shared memory region.
790    let mut bytes = Vec::with_capacity(total_number_of_bytes);
791    for frame in frame_data {
792        bytes.extend_from_slice(frame.buffer());
793    }
794
795    Some(RasterImage {
796        metadata: ImageMetadata { width, height },
797        cors_status,
798        frames,
799        id: None,
800        format: PixelFormat::RGBA8,
801        bytes: Arc::new(bytes),
802        is_opaque,
803    })
804}
805
806#[cfg(test)]
807mod test {
808    use super::detect_image_format;
809
810    #[test]
811    fn test_supported_images() {
812        let gif1 = [b'G', b'I', b'F', b'8', b'7', b'a'];
813        let gif2 = [b'G', b'I', b'F', b'8', b'9', b'a'];
814        let jpeg = [0xff, 0xd8, 0xff];
815        let png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
816        let webp = [
817            b'R', b'I', b'F', b'F', 0x04, 0x00, 0x00, 0x00, b'W', b'E', b'B', b'P',
818        ];
819        let bmp = [0x42, 0x4D];
820        let ico = [0x00, 0x00, 0x01, 0x00];
821        let junk_format = [0x01, 0x02, 0x03, 0x04, 0x05];
822
823        assert!(detect_image_format(&gif1).is_ok());
824        assert!(detect_image_format(&gif2).is_ok());
825        assert!(detect_image_format(&jpeg).is_ok());
826        assert!(detect_image_format(&png).is_ok());
827        assert!(detect_image_format(&webp).is_ok());
828        assert!(detect_image_format(&bmp).is_ok());
829        assert!(detect_image_format(&ico).is_ok());
830        assert!(detect_image_format(&junk_format).is_err());
831    }
832}