servo-pixels 0.1.0

A component of the servo web-engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use std::ops::{Bound, Deref, DerefMut, Range, RangeBounds};
use std::sync::Arc;

use euclid::default::{Rect, Size2D};
use image::codecs::jpeg::JpegEncoder;
use image::codecs::png::PngEncoder;
use image::codecs::webp::WebPEncoder;
use image::{ExtendedColorType, GenericImageView, ImageEncoder, ImageError, Rgb};
use malloc_size_of_derive::MallocSizeOf;
use serde::{Deserialize, Serialize};
use servo_base::generic_channel::GenericSharedMemory;

use crate::{EncodedImageType, Multiply, rgba8_get_rect, transform_inplace};

#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum SnapshotPixelFormat {
    #[default]
    RGBA,
    BGRA,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum Alpha {
    Premultiplied,
    NotPremultiplied,
    /// This is used for opaque textures for which the presence of alpha in the
    /// output data format does not matter.
    DontCare,
}

impl Alpha {
    pub const fn from_premultiplied(is_premultiplied: bool) -> Self {
        if is_premultiplied {
            Self::Premultiplied
        } else {
            Self::NotPremultiplied
        }
    }

    pub const fn needs_alpha_multiplication(&self) -> bool {
        match self {
            Alpha::Premultiplied => false,
            Alpha::NotPremultiplied => true,
            Alpha::DontCare => false,
        }
    }
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum SnapshotAlphaMode {
    /// Internal data is opaque (alpha is cleared to 1)
    Opaque,
    /// Internal data should be treated as opaque (does not mean it actually is)
    AsOpaque { premultiplied: bool },
    /// Data is not opaque
    Transparent { premultiplied: bool },
}

impl Default for SnapshotAlphaMode {
    fn default() -> Self {
        Self::Transparent {
            premultiplied: true,
        }
    }
}

impl SnapshotAlphaMode {
    pub const fn alpha(&self) -> Alpha {
        match self {
            SnapshotAlphaMode::Opaque => Alpha::DontCare,
            SnapshotAlphaMode::AsOpaque { premultiplied } => {
                Alpha::from_premultiplied(*premultiplied)
            },
            SnapshotAlphaMode::Transparent { premultiplied } => {
                Alpha::from_premultiplied(*premultiplied)
            },
        }
    }
}

/// The data in a [`Snapshot`]. If created via shared memory, this will be
/// the `SharedMemory` variant, but otherwise it is the `Owned` variant.
/// any attempt to mutate the [`Snapshot`] will convert it to the `Owned`
/// variant.
#[derive(Clone, Debug, MallocSizeOf)]
pub enum SnapshotData {
    SharedMemory(
        #[conditional_malloc_size_of] Arc<GenericSharedMemory>,
        Range<usize>,
    ),
    SharedVec(#[conditional_malloc_size_of] Arc<Vec<u8>>, Range<usize>),
    Owned(Vec<u8>),
}

impl SnapshotData {
    fn to_vec(&self) -> Vec<u8> {
        match &self {
            SnapshotData::SharedMemory(data, byte_range) => Vec::from(&data[byte_range.clone()]),
            SnapshotData::SharedVec(data, byte_range) => Vec::from(&data[byte_range.clone()]),
            SnapshotData::Owned(data) => data.clone(),
        }
    }
}

impl DerefMut for SnapshotData {
    fn deref_mut(&mut self) -> &mut Self::Target {
        match self {
            SnapshotData::SharedMemory(..) | SnapshotData::SharedVec(..) => {
                *self = SnapshotData::Owned(self.to_vec());
                &mut *self
            },
            SnapshotData::Owned(items) => items,
        }
    }
}

impl Deref for SnapshotData {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        match &self {
            SnapshotData::SharedMemory(data, byte_range) => &data[byte_range.clone()],
            SnapshotData::SharedVec(data, byte_range) => &data[byte_range.clone()],
            SnapshotData::Owned(items) => items,
        }
    }
}

/// Represents image bitmap with metadata, usually as snapshot of canvas
///
/// This allows us to hold off conversions (BGRA <-> RGBA, (un)premultiply)
/// to when/if they are actually needed (WebGL/WebGPU can load both BGRA and RGBA).
///
/// Inspired by snapshot for concept in WebGPU spec:
/// <https://gpuweb.github.io/gpuweb/#abstract-opdef-get-a-copy-of-the-image-contents-of-a-context>
#[derive(Clone, Debug, MallocSizeOf)]
pub struct Snapshot {
    size: Size2D<u32>,
    /// internal data (can be any format it will be converted on use if needed)
    data: SnapshotData,
    /// RGBA/BGRA (reflect internal data)
    format: SnapshotPixelFormat,
    /// How to treat alpha channel
    alpha_mode: SnapshotAlphaMode,
}

impl Snapshot {
    pub const fn size(&self) -> Size2D<u32> {
        self.size
    }

    pub const fn format(&self) -> SnapshotPixelFormat {
        self.format
    }

    pub const fn alpha_mode(&self) -> SnapshotAlphaMode {
        self.alpha_mode
    }

    pub fn empty() -> Self {
        Self {
            size: Size2D::zero(),
            data: SnapshotData::Owned(vec![]),
            format: SnapshotPixelFormat::RGBA,
            alpha_mode: SnapshotAlphaMode::Transparent {
                premultiplied: true,
            },
        }
    }

    /// Returns snapshot with provided size that is black transparent alpha
    pub fn cleared(size: Size2D<u32>) -> Self {
        Self {
            size,
            data: SnapshotData::Owned(vec![0; size.area() as usize * 4]),
            format: SnapshotPixelFormat::RGBA,
            alpha_mode: SnapshotAlphaMode::Transparent {
                premultiplied: true,
            },
        }
    }

    pub fn from_vec(
        size: Size2D<u32>,
        format: SnapshotPixelFormat,
        alpha_mode: SnapshotAlphaMode,
        data: Vec<u8>,
    ) -> Self {
        Self {
            size,
            data: SnapshotData::Owned(data),
            format,
            alpha_mode,
        }
    }

    pub fn from_arc_vec(
        size: Size2D<u32>,
        format: SnapshotPixelFormat,
        alpha_mode: SnapshotAlphaMode,
        data: Arc<Vec<u8>>,
        byte_range_bounds: impl RangeBounds<usize>,
    ) -> Self {
        let range_start = match byte_range_bounds.start_bound() {
            Bound::Included(bound) => *bound,
            Bound::Excluded(bound) => *bound + 1,
            Bound::Unbounded => 0,
        };
        let range_end = match byte_range_bounds.end_bound() {
            Bound::Included(bound) => *bound + 1,
            Bound::Excluded(bound) => *bound,
            Bound::Unbounded => data.len(),
        };
        Self {
            size,
            data: SnapshotData::SharedVec(data, range_start..range_end),
            format,
            alpha_mode,
        }
    }

    pub fn get_rect(&self, rect: Rect<u32>) -> Self {
        let data = rgba8_get_rect(self.as_raw_bytes(), self.size(), rect).to_vec();
        Self::from_vec(rect.size, self.format, self.alpha_mode, data)
    }

    /// Convert inner data of snapshot to target format and alpha mode.
    /// If data is already in target format and alpha mode no work will be done.
    pub fn transform(
        &mut self,
        target_alpha_mode: SnapshotAlphaMode,
        target_format: SnapshotPixelFormat,
    ) {
        if self.alpha_mode == target_alpha_mode && target_format == self.format {
            return;
        }

        let swap_rb = target_format != self.format;
        let multiply = match (self.alpha_mode, target_alpha_mode) {
            (SnapshotAlphaMode::Opaque, _) => Multiply::None,
            (alpha_mode, SnapshotAlphaMode::Opaque)
                if alpha_mode.alpha() == Alpha::Premultiplied =>
            {
                Multiply::UnMultiply
            },
            (_, SnapshotAlphaMode::Opaque) => Multiply::None,
            (
                SnapshotAlphaMode::Transparent { premultiplied } |
                SnapshotAlphaMode::AsOpaque { premultiplied },
                SnapshotAlphaMode::Transparent {
                    premultiplied: target_premultiplied,
                } |
                SnapshotAlphaMode::AsOpaque {
                    premultiplied: target_premultiplied,
                },
            ) => {
                if premultiplied == target_premultiplied {
                    Multiply::None
                } else if target_premultiplied {
                    Multiply::PreMultiply
                } else {
                    Multiply::UnMultiply
                }
            },
        };

        let clear_alpha = !matches!(self.alpha_mode, SnapshotAlphaMode::Opaque) &&
            matches!(target_alpha_mode, SnapshotAlphaMode::Opaque);

        if matches!(multiply, Multiply::None) && !swap_rb && !clear_alpha {
            return;
        }

        transform_inplace(self.data.deref_mut(), multiply, swap_rb, clear_alpha);
        self.alpha_mode = target_alpha_mode;
        self.format = target_format;
    }

    pub fn as_raw_bytes(&self) -> &[u8] {
        &self.data
    }

    pub fn as_raw_bytes_mut(&mut self) -> &mut [u8] {
        &mut self.data
    }

    pub fn to_shared(&self) -> SharedSnapshot {
        let (data, byte_range) = match &self.data {
            SnapshotData::SharedMemory(data, byte_range) => (data.clone(), byte_range.clone()),
            SnapshotData::SharedVec(data, byte_range) => (
                Arc::new(GenericSharedMemory::from_bytes(data)),
                byte_range.clone(),
            ),
            SnapshotData::Owned(data) => (
                Arc::new(GenericSharedMemory::from_bytes(data)),
                0..data.len(),
            ),
        };
        SharedSnapshot {
            size: self.size,
            data,
            byte_range,
            format: self.format,
            alpha_mode: self.alpha_mode,
        }
    }

    pub fn encode_for_mime_type<W: std::io::Write>(
        &mut self,
        image_type: &EncodedImageType,
        quality: Option<f64>,
        encoder: &mut W,
    ) -> Result<(), ImageError> {
        let width = self.size.width;
        let height = self.size.height;
        let alpha_mode = match image_type {
            EncodedImageType::Jpeg => SnapshotAlphaMode::AsOpaque {
                premultiplied: true,
            },
            _ => SnapshotAlphaMode::Transparent {
                premultiplied: false,
            },
        };

        self.transform(alpha_mode, SnapshotPixelFormat::RGBA);
        let data = &self.data;

        match image_type {
            EncodedImageType::Png => {
                // FIXME(nox): https://github.com/image-rs/image-png/issues/86
                // FIXME(nox): https://github.com/image-rs/image-png/issues/87
                PngEncoder::new(encoder).write_image(data, width, height, ExtendedColorType::Rgba8)
            },
            EncodedImageType::Jpeg => {
                let mut jpeg_encoder = if let Some(quality) = quality {
                    // The specification allows quality to be in [0.0..1.0] but the JPEG encoder
                    // expects it to be in [1..100]
                    if (0.0..=1.0).contains(&quality) {
                        JpegEncoder::new_with_quality(
                            encoder,
                            (quality * 100.0).round().clamp(1.0, 100.0) as u8,
                        )
                    } else {
                        JpegEncoder::new(encoder)
                    }
                } else {
                    JpegEncoder::new(encoder)
                };

                // JPEG doesn't support transparency, so simply calling jpeg_encoder.write_image fails here.
                // Instead we have to create a struct to translate from rgba to rgb.
                struct RgbaDataForJpegEncoder<'a> {
                    width: u32,
                    height: u32,
                    data: &'a [u8],
                }

                impl<'a> GenericImageView for RgbaDataForJpegEncoder<'a> {
                    type Pixel = Rgb<u8>;

                    fn dimensions(&self) -> (u32, u32) {
                        (self.width, self.height)
                    }

                    fn get_pixel(&self, x: u32, y: u32) -> Self::Pixel {
                        let offset = (self.width * y + x) as usize * 4;
                        Rgb([
                            self.data[offset],
                            self.data[offset + 1],
                            self.data[offset + 2],
                        ])
                    }
                }

                let image = RgbaDataForJpegEncoder {
                    width,
                    height,
                    data,
                };

                jpeg_encoder.encode_image(&image)
            },
            EncodedImageType::Webp => {
                // No quality support because of https://github.com/image-rs/image/issues/1984
                WebPEncoder::new_lossless(encoder).write_image(
                    data,
                    width,
                    height,
                    ExtendedColorType::Rgba8,
                )
            },
        }
    }
}

impl From<Snapshot> for Vec<u8> {
    fn from(value: Snapshot) -> Self {
        match value.data {
            SnapshotData::SharedMemory(..) => Vec::from(value.as_raw_bytes()),
            SnapshotData::SharedVec(..) => Vec::from(value.as_raw_bytes()),
            SnapshotData::Owned(data) => data,
        }
    }
}

/// A version of [`Snapshot`] that can be sent across IPC channels.
#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
pub struct SharedSnapshot {
    /// The physical size of this [`SharedSnapshot`].
    size: Size2D<u32>,
    /// The shared data of this [`SharedSnapshot`].
    #[conditional_malloc_size_of]
    data: Arc<GenericSharedMemory>,
    /// The byte range of the data within the shared memory segment. This is used to
    /// send individual image frames of animated images.
    byte_range: Range<usize>,
    /// The [`SnapshotPixelFormat`] of this [`SharedSnapshot`]
    format: SnapshotPixelFormat,
    /// The [`SnapshotAlphaMode`] of this [`SharedSnapshot`].
    alpha_mode: SnapshotAlphaMode,
}

impl SharedSnapshot {
    pub fn to_owned(&self) -> Snapshot {
        Snapshot {
            size: self.size,
            data: SnapshotData::SharedMemory(self.data.clone(), self.byte_range.clone()),
            format: self.format,
            alpha_mode: self.alpha_mode,
        }
    }

    /// Returns snapshot with provided size that is black transparent alpha
    pub fn cleared(size: Size2D<u32>) -> Self {
        let length_in_bytes = size.area() as usize * 4;
        Self {
            size,
            data: Arc::new(GenericSharedMemory::from_byte(0, length_in_bytes)),
            byte_range: 0..length_in_bytes,
            format: SnapshotPixelFormat::RGBA,
            alpha_mode: SnapshotAlphaMode::Transparent {
                premultiplied: true,
            },
        }
    }

    pub const fn size(&self) -> Size2D<u32> {
        self.size
    }

    pub const fn format(&self) -> SnapshotPixelFormat {
        self.format
    }

    pub const fn alpha_mode(&self) -> SnapshotAlphaMode {
        self.alpha_mode
    }

    pub fn data(&self) -> &[u8] {
        &(&self.data)[self.byte_range.clone()]
    }

    pub fn shared_memory(&self) -> GenericSharedMemory {
        (*self.data).clone()
    }
}