Skip to main content

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