glycin-utils 5.0.0-alpha

Sandboxed image decoding
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
use std::collections::BTreeMap;
use std::io::Read;
use std::time::Duration;

use glycin_common::{MemoryFormat, MemoryFormatInfo};
use gufo_common::orientation::Orientation;
#[cfg(feature = "external")]
use zbus::zvariant::as_value::{self, optional};
#[cfg(feature = "external")]
use zbus::zvariant::{self, Optional, Type};

use crate::error::DimensionTooLargerError;
use crate::safe_math::{SafeConversion, SafeMath};
use crate::{ByteData, FungibleMemory, Limits, MemoryAllocationError, ProcessError};

pub trait LoaderImplementation: Send + Sync + Sized + 'static {
    fn load<B: ByteData, R: Read + Send + 'static>(
        stream: R,
        mime_type: String,
        details: InitializationDetails,
    ) -> Result<(Self, ImageDetails<B>), ProcessError>;

    fn specific_frame<T: ByteData>(
        &mut self,
        frame_request: FrameRequest,
    ) -> Result<Frame<T>, ProcessError>;
}

#[cfg(feature = "external")]
#[derive(serde::Deserialize, serde::Serialize, Type, Debug)]
pub struct InitRequest {
    /// Source from which the loader reads the image data
    pub fd: zvariant::OwnedFd,
    pub mime_type: String,
    pub details: InitializationDetails,
}

#[derive(Debug, Default)]
#[cfg_attr(
    feature = "external",
    derive(serde::Deserialize, serde::Serialize, Type)
)]
#[cfg_attr(feature = "external", zvariant(signature = "a{sv}"))]
#[cfg_attr(feature = "external", serde(default))]
#[non_exhaustive]
pub struct InitializationDetails {
    #[cfg_attr(
        feature = "external",
        serde(with = "optional", skip_serializing_if = "Option::is_none")
    )]
    pub base_dir: Option<std::path::PathBuf>,
    #[cfg_attr(feature = "external", serde(with = "as_value"))]
    pub limits: Limits,
}

#[cfg(feature = "external")]
const fn true_const() -> bool {
    true
}

#[derive(Debug, Clone)]
#[cfg_attr(
    feature = "external",
    derive(serde::Deserialize, serde::Serialize, Type)
)]
#[cfg_attr(feature = "external", zvariant(signature = "dict"))]
#[non_exhaustive]
pub struct FrameRequest {
    /// Scale image to these dimensions
    #[cfg_attr(
        feature = "external",
        serde(with = "optional", skip_serializing_if = "Option::is_none", default)
    )]
    pub scale: Option<(u32, u32)>,
    /// Instruction to only decode part of the image
    #[cfg_attr(
        feature = "external",
        serde(with = "optional", skip_serializing_if = "Option::is_none", default)
    )]
    pub clip: Option<(u32, u32, u32, u32)>,
    /// Get first frame, if previously selected frame was the last one
    #[cfg_attr(feature = "external", serde(with = "as_value", default = "true_const"))]
    pub loop_animation: bool,
}

impl Default for FrameRequest {
    fn default() -> Self {
        Self {
            scale: None,
            clip: None,
            loop_animation: true,
        }
    }
}

/// Various image metadata
///
/// This is returned from the initial `InitRequest` call
#[cfg(feature = "external")]
#[derive(Debug, Type, serde::Serialize, serde::Deserialize)]
#[serde(bound(
    serialize = "B: ByteData + serde::Serialize + zbus::zvariant::Type + 'static",
    deserialize = "B: ByteData + serde::de::DeserializeOwned + zbus::zvariant::Type + 'static"
))]
#[non_exhaustive]
pub struct RemoteImage<B: ByteData> {
    pub frame_request: zvariant::OwnedObjectPath,
    pub details: ImageDetails<B>,
}

#[cfg(feature = "external")]
impl<B: ByteData> RemoteImage<B> {
    pub fn new(details: ImageDetails<B>, frame_request: zvariant::OwnedObjectPath) -> Self {
        Self {
            frame_request,
            details,
        }
    }

    pub async fn initial_seal(&mut self) -> Result<(), MemoryAllocationError> {
        self.details.initial_seal().await
    }

    pub async fn final_seal(&mut self) -> Result<(), MemoryAllocationError> {
        self.details.final_seal().await
    }
}

#[derive(Debug)]
#[cfg_attr(
    feature = "external",
    derive(Type, serde::Serialize, serde::Deserialize)
)]
#[cfg_attr(feature = "external", zvariant(signature = "dict"))]
#[cfg_attr(
    feature = "external",
    serde(bound(
        serialize = "B: ByteData + serde::Serialize + zbus::zvariant::Type + 'static",
        deserialize = "B: ByteData + serde::de::DeserializeOwned + zbus::zvariant::Type + 'static"
    ))
)]
#[non_exhaustive]
pub struct ImageDetails<B: ByteData> {
    /// Early dimension information.
    ///
    /// This information is often correct. However, it should only be used for
    /// an early rendering estimates. For everything else, the specific frame
    /// information should be used.
    #[cfg_attr(feature = "external", serde(with = "as_value"))]
    pub width: u32,
    #[cfg_attr(feature = "external", serde(with = "as_value"))]
    pub height: u32,
    /// Image dimensions in inch
    #[cfg_attr(
        feature = "external",
        serde(
            with = "as_value::optional",
            skip_serializing_if = "Option::is_none",
            default
        )
    )]
    pub dimensions_inch: Option<(f64, f64)>,
    #[cfg_attr(
        feature = "external",
        serde(
            with = "as_value::optional",
            skip_serializing_if = "Option::is_none",
            default
        )
    )]
    pub info_format_name: Option<String>,
    /// Textual description of the image dimensions
    #[cfg_attr(
        feature = "external",
        serde(
            with = "as_value::optional",
            skip_serializing_if = "Option::is_none",
            default
        )
    )]
    pub info_dimensions_text: Option<String>,
    #[cfg_attr(
        feature = "external",
        serde(
            with = "as_value::optional",
            skip_serializing_if = "Option::is_none",
            default
        )
    )]
    pub metadata_exif: Option<B>,
    #[cfg_attr(
        feature = "external",
        serde(
            with = "as_value::optional",
            skip_serializing_if = "Option::is_none",
            default
        )
    )]
    pub metadata_xmp: Option<B>,
    #[cfg_attr(
        feature = "external",
        serde(
            with = "as_value::optional",
            skip_serializing_if = "Option::is_none",
            default
        )
    )]
    pub metadata_key_value: Option<BTreeMap<String, String>>,
    #[cfg_attr(feature = "external", serde(with = "as_value"))]
    pub transformation_ignore_exif: bool,
    /// Explicit orientation. If `None` check Exif or XMP.
    #[cfg_attr(
        feature = "external",
        serde(
            with = "as_value::optional",
            skip_serializing_if = "Option::is_none",
            default
        )
    )]
    pub transformation_orientation: Option<Orientation>,
}

impl<B: ByteData> ImageDetails<B> {
    pub fn new(width: u32, height: u32) -> Self {
        Self {
            width,
            height,
            dimensions_inch: None,
            info_dimensions_text: None,
            info_format_name: None,
            metadata_exif: None,
            metadata_xmp: None,
            metadata_key_value: None,
            transformation_ignore_exif: false,
            transformation_orientation: None,
        }
    }

    pub fn into_fungible(self) -> ImageDetails<FungibleMemory> {
        ImageDetails {
            width: self.width,
            height: self.height,
            dimensions_inch: self.dimensions_inch,
            info_format_name: self.info_format_name,
            info_dimensions_text: self.info_dimensions_text,
            metadata_exif: self.metadata_exif.map(B::into_fungible),
            metadata_xmp: self.metadata_xmp.map(B::into_fungible),
            metadata_key_value: self.metadata_key_value,
            transformation_ignore_exif: self.transformation_ignore_exif,
            transformation_orientation: self.transformation_orientation,
        }
    }

    pub fn into_other<O: ByteData>(self) -> Result<ImageDetails<O>, MemoryAllocationError> {
        Ok(ImageDetails {
            width: self.width,
            height: self.height,
            dimensions_inch: self.dimensions_inch,
            info_format_name: self.info_format_name,
            info_dimensions_text: self.info_dimensions_text,
            metadata_exif: self.metadata_exif.map(|x| x.into_other()).transpose()?,
            metadata_xmp: self.metadata_xmp.map(|x| x.into_other()).transpose()?,
            metadata_key_value: self.metadata_key_value,
            transformation_ignore_exif: self.transformation_ignore_exif,
            transformation_orientation: self.transformation_orientation,
        })
    }

    pub async fn initial_seal(&mut self) -> Result<(), MemoryAllocationError> {
        if let Some(metadata_exif) = &mut self.metadata_exif {
            metadata_exif.initial_seal().await?;
        }

        if let Some(metadata_xmp) = &mut self.metadata_xmp {
            metadata_xmp.initial_seal().await?;
        }

        Ok(())
    }

    pub async fn final_seal(&mut self) -> Result<(), MemoryAllocationError> {
        if let Some(metadata_exif) = &mut self.metadata_exif {
            metadata_exif.final_seal().await?;
        }

        if let Some(metadata_xmp) = &mut self.metadata_xmp {
            metadata_xmp.final_seal().await?;
        }

        Ok(())
    }
}

impl<B: ByteData> Default for FrameDetails<B> {
    fn default() -> Self {
        Self {
            color_icc_profile: None,
            color_cicp: None,
            info_bit_depth: None,
            info_alpha_channel: None,
            info_grayscale: None,
            n_frame: None,
        }
    }
}

#[cfg(not(feature = "external"))]
pub type Optional<T> = Option<T>;

#[derive(Debug)]
#[cfg_attr(feature = "external", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
    feature = "external",
    serde(bound(
        serialize = "B: ByteData + serde::Serialize + zbus::zvariant::Type + 'static",
        deserialize = "B: ByteData + serde::de::DeserializeOwned + zbus::zvariant::Type + 'static"
    ))
)]
pub struct Frame<B: ByteData> {
    pub width: u32,
    pub height: u32,
    /// Line stride
    pub stride: u32,
    pub memory_format: MemoryFormat,
    pub texture: B,
    /// Duration to show frame for animations.
    ///
    /// If the value is not set, the image is not animated.
    pub delay: Optional<Duration>,
    pub details: FrameDetails<B>,
}

#[cfg(feature = "external")]
impl<B: ByteData + zvariant::Type> zvariant::Type for Frame<B> {
    const SIGNATURE: &'static zvariant::Signature = <(
        u32,
        u32,
        u32,
        MemoryFormat,
        B,
        Optional<Duration>,
        FrameDetails<B>,
    )>::SIGNATURE;
}

impl<B: ByteData> Frame<B> {
    pub fn new(
        width: u32,
        height: u32,
        memory_format: MemoryFormat,
        texture: B,
    ) -> Result<Self, DimensionTooLargerError> {
        let stride = memory_format
            .n_bytes()
            .u32()
            .checked_mul(width)
            .ok_or(DimensionTooLargerError)?;

        Ok(Self {
            width,
            height,
            stride,
            memory_format,
            texture,
            delay: None.into(),
            details: Default::default(),
        })
    }

    pub fn n_bytes(&self) -> Result<usize, DimensionTooLargerError> {
        self.stride.try_usize()?.smul(self.height.try_usize()?)
    }

    pub fn into_fungible(self) -> Frame<FungibleMemory> {
        Frame {
            width: self.width,
            height: self.height,
            stride: self.stride,
            memory_format: self.memory_format,
            texture: self.texture.into_fungible(),
            delay: self.delay,
            details: self.details.into_fungible(),
        }
    }

    pub fn into_other<O: ByteData>(self) -> Result<Frame<O>, MemoryAllocationError> {
        Ok(Frame {
            width: self.width,
            height: self.height,
            stride: self.stride,
            memory_format: self.memory_format,
            texture: self.texture.into_other()?,
            delay: self.delay,
            details: self.details.into_other()?,
        })
    }

    pub fn desc(&self) -> String {
        format!(
            "{}x{} stride: {}, natural_stride: {}",
            self.width,
            self.height,
            self.stride,
            self.width * self.memory_format.n_bytes().u32()
        )
    }

    pub async fn initial_seal(&mut self) -> Result<(), MemoryAllocationError> {
        self.texture.initial_seal().await?;
        self.details.initial_seal().await
    }

    pub async fn final_seal(&mut self) -> Result<(), MemoryAllocationError> {
        self.texture.final_seal().await?;
        self.details.final_seal().await
    }
}

#[derive(Debug)]
#[cfg_attr(
    feature = "external",
    derive(Type, serde::Serialize, serde::Deserialize)
)]
#[cfg_attr(feature = "external", zvariant(signature = "dict"))]
#[cfg_attr(
    feature = "external",
    serde(bound(
        serialize = "B: ByteData + serde::Serialize + zbus::zvariant::Type + 'static",
        deserialize = "B: ByteData + serde::de::DeserializeOwned + zbus::zvariant::Type + 'static"
    ))
)]
//#[serde(bound(deserialize = "B: ByteData"))]
#[non_exhaustive]
/// More information about a frame
pub struct FrameDetails<B: ByteData> {
    /// ICC color profile
    #[cfg_attr(
        feature = "external",
        serde(
            with = "as_value::optional",
            skip_serializing_if = "Option::is_none",
            default
        )
    )]
    pub color_icc_profile: Option<B>,
    /// Coding-independent code points (HDR information)
    #[cfg_attr(
        feature = "external",
        serde(
            with = "as_value::optional",
            skip_serializing_if = "Option::is_none",
            default
        )
    )]
    pub color_cicp: Option<[u8; 4]>,
    /// Bit depth per channel
    ///
    /// Only set if it can differ for the format
    #[cfg_attr(
        feature = "external",
        serde(
            with = "as_value::optional",
            skip_serializing_if = "Option::is_none",
            default
        )
    )]
    pub info_bit_depth: Option<u8>,
    /// Image has alpha channel
    ///
    /// Only set if it can differ for the format
    #[cfg_attr(
        feature = "external",
        serde(
            with = "as_value::optional",
            skip_serializing_if = "Option::is_none",
            default
        )
    )]
    pub info_alpha_channel: Option<bool>,
    /// Image uses grayscale mode
    ///
    /// Only set if it can differ for the format
    #[cfg_attr(
        feature = "external",
        serde(
            with = "as_value::optional",
            skip_serializing_if = "Option::is_none",
            default
        )
    )]
    pub info_grayscale: Option<bool>,
    #[cfg_attr(
        feature = "external",
        serde(
            with = "as_value::optional",
            skip_serializing_if = "Option::is_none",
            default
        )
    )]
    pub n_frame: Option<u64>,
}

impl<B: ByteData> FrameDetails<B> {
    pub fn into_fungible(self) -> FrameDetails<FungibleMemory> {
        FrameDetails {
            color_icc_profile: self.color_icc_profile.map(B::into_fungible),
            color_cicp: self.color_cicp,
            info_bit_depth: self.info_bit_depth,
            info_alpha_channel: self.info_alpha_channel,
            info_grayscale: self.info_grayscale,
            n_frame: self.n_frame,
        }
    }

    pub fn into_other<O: ByteData>(self) -> Result<FrameDetails<O>, MemoryAllocationError> {
        Ok(FrameDetails {
            color_icc_profile: self.color_icc_profile.map(B::into_other).transpose()?,
            color_cicp: self.color_cicp,
            info_bit_depth: self.info_bit_depth,
            info_alpha_channel: self.info_alpha_channel,
            info_grayscale: self.info_grayscale,
            n_frame: self.n_frame,
        })
    }

    pub async fn initial_seal(&mut self) -> Result<(), MemoryAllocationError> {
        if let Some(color_icc_profile) = &mut self.color_icc_profile {
            color_icc_profile.initial_seal().await?;
        }

        Ok(())
    }

    pub async fn final_seal(&mut self) -> Result<(), MemoryAllocationError> {
        if let Some(color_icc_profile) = &mut self.color_icc_profile {
            color_icc_profile.final_seal().await?;
        }

        Ok(())
    }
}