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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
//! Image types.
use bitflags::bitflags;
use serde::{Deserialize, Serialize};
use zng_task::channel::IpcBytes;
use zng_txt::Txt;
use zng_unit::{Px, PxDensity2d, PxSize};
use crate::api_extension::{ApiExtensionId, ApiExtensionPayload};
crate::declare_id! {
/// Id of a decoded image in the cache.
///
/// The View Process defines the ID.
pub struct ImageId(_);
/// Id of an image loaded in a renderer.
///
/// The View Process defines the ID.
pub struct ImageTextureId(_);
/// Id of an image encode task.
///
/// The View Process defines the ID.
pub struct ImageEncodeId(_);
}
/// Defines how the A8 image mask pixels are to be derived from a source mask image.
#[derive(Debug, Copy, Clone, Serialize, PartialEq, Eq, Hash, Deserialize, Default)]
#[non_exhaustive]
pub enum ImageMaskMode {
/// Alpha channel.
///
/// If the image has no alpha channel masks by `Luminance`.
#[default]
A,
/// Blue channel.
///
/// If the image has no color channel fallback to monochrome channel, or `A`.
B,
/// Green channel.
///
/// If the image has no color channel fallback to monochrome channel, or `A`.
G,
/// Red channel.
///
/// If the image has no color channel fallback to monochrome channel, or `A`.
R,
/// Relative luminance.
///
/// If the image has no color channel fallback to monochrome channel, or `A`.
Luminance,
}
bitflags! {
/// Defines what images are decoded from multi image containers.
///
/// These flags represent the different [`ImageEntryKind`].
#[derive(Copy, Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)]
pub struct ImageEntriesMode: u8 {
/// Decodes all pages.
const PAGES = 0b0001;
/// Decodes reduced alternates of the selected pages.
const REDUCED = 0b0010;
/// Decodes only the first page, or the page explicitly marked as primary by the container format.
///
/// Note that this is 0, empty.
const PRIMARY = 0;
/// Decodes any other images that are not considered pages nor reduced alternates.
const OTHER = 0b1000;
}
}
#[cfg(feature = "var")]
zng_var::impl_from_and_into_var! {
fn from(kind: ImageEntryKind) -> ImageEntriesMode {
match kind {
ImageEntryKind::Page => ImageEntriesMode::PAGES,
ImageEntryKind::Reduced { .. } => ImageEntriesMode::REDUCED,
ImageEntryKind::Other { .. } => ImageEntriesMode::OTHER,
}
}
}
/// Represent a image load/decode request.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ImageRequest<D> {
/// Image data format.
pub format: ImageDataFormat,
/// Image data.
///
/// Bytes layout depends on the `format`, data structure is [`IpcBytes`] or [`IpcReceiver<IpcBytes>`] in the view API.
///
/// [`IpcReceiver<IpcBytes>`]: crate::IpcReceiver
pub data: D,
/// Maximum allowed decoded size.
///
/// View-process will avoid decoding and return an error if the image decoded to BGRA (4 bytes) exceeds this size.
/// This limit applies to the image before the `downscale`.
pub max_decoded_len: u64,
/// A size constraints to apply after the image is decoded. The image is resized to fit or fill the given size.
/// Optionally generate multiple reduced entries.
///
/// If the image contains multiple images selects the nearest *reduced alternate* that can be downscaled.
///
/// If `entries` requests `REDUCED` only the alternates smaller than the requested downscale are included.
pub downscale: Option<ImageDownscaleMode>,
/// Convert or decode the image into a single channel mask (R8).
pub mask: Option<ImageMaskMode>,
/// Defines what images are decoded from multi image containers.
pub entries: ImageEntriesMode,
/// Image is an entry (or subtree) of this other image.
///
/// This value is now used by the view-process, it is just returned with the metadata. This is useful when
/// an already decoded image is requested after a respawn to maintain the original container structure.
pub parent: Option<ImageEntryMetadata>,
}
impl<D> ImageRequest<D> {
/// New request.
pub fn new(
format: ImageDataFormat,
data: D,
max_decoded_len: u64,
downscale: Option<ImageDownscaleMode>,
mask: Option<ImageMaskMode>,
) -> Self {
Self {
format,
data,
max_decoded_len,
downscale,
mask,
entries: ImageEntriesMode::PRIMARY,
parent: None,
}
}
}
/// Defines how an image is downscaled after decoding.
///
/// The image aspect ratio is preserved in all modes. The image is never upscaled. If the image container
/// contains reduced alternative the nearest to the requested size is used as source.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ImageDownscaleMode {
/// Image is downscaled so that both dimensions fit inside the size.
Fit(PxSize),
/// Image is downscaled so that at least one dimension fits inside the size. The image is not clipped.
Fill(PxSize),
/// Generate synthetic [`ImageEntryKind::Reduced`] entries each half the size of the image until the sample that is
/// nearest `min_size` and greater or equal to it. If the image container already has alternates that are equal to
/// or *near* a mip size that size is used instead.
MipMap {
/// Minimum sample size.
min_size: PxSize,
/// Maximum `Fill` size.
max_size: PxSize,
},
/// Generate multiple synthetic [`ImageEntryKind::Reduced`] entries. The entry sizes are sorted by largest first,
/// if the image full size already fits in the largest downscale requested the full image is returned and any
/// downscale actually smaller becomes a synthetic entry. If the image is larger than all requested sizes it is downscaled as well.
Entries(Vec<ImageDownscaleMode>),
}
impl From<PxSize> for ImageDownscaleMode {
/// Fit
fn from(fit: PxSize) -> Self {
ImageDownscaleMode::Fit(fit)
}
}
impl From<Px> for ImageDownscaleMode {
/// Fit splat
fn from(fit: Px) -> Self {
ImageDownscaleMode::Fit(PxSize::splat(fit))
}
}
#[cfg(feature = "var")]
zng_var::impl_from_and_into_var! {
fn from(fit: PxSize) -> ImageDownscaleMode;
fn from(fit: Px) -> ImageDownscaleMode;
fn from(some: ImageDownscaleMode) -> Option<ImageDownscaleMode>;
}
impl ImageDownscaleMode {
/// Default mipmap min/max when the objective of the mipmap is optimizing dynamically resizing massive images.
pub fn mip_map() -> Self {
Self::MipMap {
min_size: PxSize::splat(Px(512)),
max_size: PxSize::splat(Px::MAX),
}
}
/// Append entry downscale request.
pub fn with_entry(self, other: impl Into<ImageDownscaleMode>) -> Self {
self.with_impl(other.into())
}
fn with_impl(self, other: Self) -> Self {
let mut v = match self {
Self::Entries(e) => e,
s => vec![s],
};
match other {
Self::Entries(o) => v.extend(o),
o => v.push(o),
}
Self::Entries(v)
}
/// Get downscale sizes that need to be generated.
///
/// The `page_size` is the image full size, the `reduced_sizes` are
/// sizes of reduced alternates that are already provided by the image container.
///
/// Returns the downscale for the image full size, if needed and a list of reduced entries that must be synthesized,
/// sorted largest to smallest.
pub fn sizes(&self, page_size: PxSize, reduced_sizes: &[PxSize]) -> (Option<PxSize>, Vec<PxSize>) {
match self {
ImageDownscaleMode::Fit(s) => (fit_fill(page_size, *s, false), vec![]),
ImageDownscaleMode::Fill(s) => (fit_fill(page_size, *s, true), vec![]),
ImageDownscaleMode::MipMap { min_size, max_size } => Self::collect_mip_map(page_size, reduced_sizes, &[], *min_size, *max_size),
ImageDownscaleMode::Entries(modes) => {
let mut include_full_size = false;
let mut sizes = vec![];
let mut mip_map = None;
for m in modes {
m.collect_entries(page_size, &mut sizes, &mut mip_map, &mut include_full_size);
}
if let Some([min_size, max_size]) = mip_map {
let (first, mips) = Self::collect_mip_map(page_size, reduced_sizes, &sizes, min_size, max_size);
include_full_size |= first.is_some();
sizes.extend(first);
sizes.extend(mips);
}
sizes.sort_by_key(|s| s.width.0 * s.height.0);
sizes.dedup();
let full_downscale = if include_full_size { None } else { sizes.pop() };
sizes.reverse();
(full_downscale, sizes)
}
}
}
fn collect_mip_map(
page_size: PxSize,
reduced_sizes: &[PxSize],
entry_sizes: &[PxSize],
min_size: PxSize,
max_size: PxSize,
) -> (Option<PxSize>, Vec<PxSize>) {
let page_downscale = fit_fill(page_size, max_size, true);
let mut size = page_downscale.unwrap_or(page_size) / Px(2);
let mut entries = vec![];
while min_size.width < size.width && min_size.height < size.height {
if let Some(entry) = fit_fill(page_size, size, true)
&& !reduced_sizes.iter().any(|s| Self::near(entry, *s))
&& !entry_sizes.iter().any(|s| Self::near(entry, *s))
{
entries.push(entry);
}
size /= Px(2);
}
(page_downscale, entries)
}
fn near(candidate: PxSize, existing: PxSize) -> bool {
let dist = (candidate - existing).abs();
dist.width < Px(10) && dist.height <= Px(10)
}
fn collect_entries(&self, page_size: PxSize, sizes: &mut Vec<PxSize>, mip_map: &mut Option<[PxSize; 2]>, include_full_size: &mut bool) {
match self {
ImageDownscaleMode::Fit(s) => match fit_fill(page_size, *s, false) {
Some(s) => sizes.push(s),
None => *include_full_size = true,
},
ImageDownscaleMode::Fill(s) => match fit_fill(page_size, *s, true) {
Some(s) => sizes.push(s),
None => *include_full_size = true,
},
ImageDownscaleMode::MipMap { min_size, max_size } => {
*include_full_size = true;
if let Some([min, max]) = mip_map {
*min = min.min(*min_size);
*max = max.min(*min_size);
} else {
*mip_map = Some([*min_size, *max_size]);
}
}
ImageDownscaleMode::Entries(modes) => {
for m in modes {
m.collect_entries(page_size, sizes, mip_map, include_full_size);
}
}
}
}
}
fn fit_fill(source_size: PxSize, new_size: PxSize, fill: bool) -> Option<PxSize> {
let source_size = source_size.cast::<f64>();
let new_size = new_size.cast::<f64>();
let w_ratio = new_size.width / source_size.width;
let h_ratio = new_size.height / source_size.height;
let ratio = if fill {
f64::max(w_ratio, h_ratio)
} else {
f64::min(w_ratio, h_ratio)
};
if ratio >= 1.0 {
return None;
}
let nw = u64::max((source_size.width * ratio).round() as _, 1);
let nh = u64::max((source_size.height * ratio).round() as _, 1);
const MAX: u64 = Px::MAX.0 as _;
let r = if nw > MAX {
let ratio = MAX as f64 / source_size.width;
(Px::MAX, Px(i32::max((source_size.height * ratio).round() as _, 1)))
} else if nh > MAX {
let ratio = MAX as f64 / source_size.height;
(Px(i32::max((source_size.width * ratio).round() as _, 1)), Px::MAX)
} else {
(Px(nw as _), Px(nh as _))
}
.into();
Some(r)
}
/// Format of the image bytes.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ImageDataFormat {
/// Decoded BGRA8.
///
/// This is the internal image format, it indicates the image data
/// is already decoded and color managed (to sRGB).
Bgra8 {
/// Size in pixels.
size: PxSize,
/// Pixel density of the image.
density: Option<PxDensity2d>,
/// Original color type of the image.
original_color_type: ColorType,
},
/// Decoded A8.
///
/// This is the internal mask format it indicates the mask data
/// is already decoded.
A8 {
/// Size in pixels.
size: PxSize,
},
/// The image is encoded.
///
/// This file extension maybe identifies the format. Fallback to `Unknown` handling if the file extension
/// is unknown or the file header does not match.
FileExtension(Txt),
/// The image is encoded.
///
/// This MIME type maybe identifies the format. Fallback to `Unknown` handling if the file extension
/// is unknown or the file header does not match.
MimeType(Txt),
/// The image is encoded.
///
/// A decoder will be selected using the "magic number" at the start of the bytes buffer.
Unknown,
}
impl From<Txt> for ImageDataFormat {
fn from(ext_or_mime: Txt) -> Self {
if ext_or_mime.contains('/') {
ImageDataFormat::MimeType(ext_or_mime)
} else {
ImageDataFormat::FileExtension(ext_or_mime)
}
}
}
impl From<&str> for ImageDataFormat {
fn from(ext_or_mime: &str) -> Self {
Txt::from_str(ext_or_mime).into()
}
}
impl From<PxSize> for ImageDataFormat {
fn from(bgra8_size: PxSize) -> Self {
ImageDataFormat::Bgra8 {
size: bgra8_size,
density: None,
original_color_type: ColorType::BGRA8,
}
}
}
impl PartialEq for ImageDataFormat {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::FileExtension(l0), Self::FileExtension(r0)) => l0 == r0,
(Self::MimeType(l0), Self::MimeType(r0)) => l0 == r0,
(
Self::Bgra8 {
size: s0,
density: p0,
original_color_type: oc0,
},
Self::Bgra8 {
size: s1,
density: p1,
original_color_type: oc1,
},
) => s0 == s1 && density_key(*p0) == density_key(*p1) && oc0 == oc1,
(Self::Unknown, Self::Unknown) => true,
_ => false,
}
}
}
impl Eq for ImageDataFormat {}
impl std::hash::Hash for ImageDataFormat {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
core::mem::discriminant(self).hash(state);
match self {
ImageDataFormat::Bgra8 {
size,
density,
original_color_type,
} => {
size.hash(state);
density_key(*density).hash(state);
original_color_type.hash(state)
}
ImageDataFormat::A8 { size } => {
size.hash(state);
}
ImageDataFormat::FileExtension(ext) => ext.hash(state),
ImageDataFormat::MimeType(mt) => mt.hash(state),
ImageDataFormat::Unknown => {}
}
}
}
fn density_key(density: Option<PxDensity2d>) -> Option<(u16, u16)> {
density.map(|s| ((s.width.ppcm() * 3.0) as u16, (s.height.ppcm() * 3.0) as u16))
}
/// Represents decoded header metadata about an image position in a container represented by another image.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ImageEntryMetadata {
/// Image this one belongs too.
///
/// The view-process always sends the parent image metadata first, so this id should be known by the app-process.
pub parent: ImageId,
/// Sort index of the image in the list of entries.
pub index: usize,
/// Kind of entry.
pub kind: ImageEntryKind,
}
impl ImageEntryMetadata {
/// New.
pub fn new(parent: ImageId, index: usize, kind: ImageEntryKind) -> Self {
Self { parent, index, kind }
}
}
/// Represents decoded header metadata about an image.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ImageMetadata {
/// Image ID.
pub id: ImageId,
/// Pixel size.
pub size: PxSize,
/// Pixel density metadata.
pub density: Option<PxDensity2d>,
/// If the `pixels` are in a single channel (A8).
pub is_mask: bool,
/// Image color type before it was converted to BGRA8 or A8.
pub original_color_type: ColorType,
/// The [`ImageFormat::display_name`] that was decoded or the [`ColorType::name`] if the image was not decoded.
pub format_name: Txt,
/// Extra metadata if this image is an entry in another image.
///
/// When this is `None` the is the first [`ImageEntryKind::Page`] in the container, usually the only page.
pub parent: Option<ImageEntryMetadata>,
/// Custom metadata.
pub extensions: Vec<(ApiExtensionId, ApiExtensionPayload)>,
}
impl ImageMetadata {
/// New.
pub fn new(id: ImageId, size: PxSize, is_mask: bool, original_color_type: ColorType) -> Self {
Self {
id,
size,
density: None,
is_mask,
original_color_type,
parent: None,
extensions: vec![],
format_name: Txt::default(),
}
}
}
impl Default for ImageMetadata {
fn default() -> Self {
Self {
id: ImageId::INVALID,
size: Default::default(),
density: Default::default(),
is_mask: Default::default(),
original_color_type: ColorType::BGRA8,
parent: Default::default(),
extensions: vec![],
format_name: Txt::default(),
}
}
}
/// Kind of image container entry an image was decoded from.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub enum ImageEntryKind {
/// Full sized image in the container.
Page,
/// Reduced resolution alternate of the other image.
///
/// Can be mip levels, a thumbnail or a smaller symbolic alternative designed to be more readable at smaller scale.
Reduced {
/// If reduced image was generated, not part of the image container file.
synthetic: bool,
},
/// Custom kind identifier.
Other {
/// Custom identifier.
///
/// This is an implementation specific value that can be parsed.
kind: Txt,
},
}
impl ImageEntryKind {
fn discriminant(&self) -> u8 {
match self {
ImageEntryKind::Page => 0,
ImageEntryKind::Reduced { .. } => 1,
ImageEntryKind::Other { .. } => 2,
}
}
}
impl std::cmp::Ord for ImageEntryKind {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.discriminant().cmp(&other.discriminant())
}
}
impl std::cmp::PartialOrd for ImageEntryKind {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
/// Represents a partial or fully decoded image.
///
/// See [`Event::ImageDecoded`] for more details.
///
/// [`Event::ImageDecoded`]: crate::Event::ImageDecoded
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ImageDecoded {
/// Image metadata.
pub meta: ImageMetadata,
/// If the [`pixels`] only represent a partial image.
///
/// When this is `None` the image has fully loaded.
///
/// [`pixels`]: Self::pixels
pub partial: Option<PartialImageKind>,
/// Decoded pixels.
///
/// Is BGRA8 pre-multiplied if `!is_mask` or is `A8` if `is_mask`.
pub pixels: IpcBytes,
/// If all pixels have an alpha value of 255.
pub is_opaque: bool,
}
impl Default for ImageDecoded {
fn default() -> Self {
Self {
meta: Default::default(),
partial: Default::default(),
pixels: Default::default(),
is_opaque: true,
}
}
}
impl ImageDecoded {
/// New.
pub fn new(meta: ImageMetadata, pixels: IpcBytes, is_opaque: bool) -> Self {
Self {
meta,
partial: None,
pixels,
is_opaque,
}
}
}
/// Represents what kind of partial data was decoded.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum PartialImageKind {
/// The [`pixels`] are a placeholder image that must fill the actual image size.
///
/// [`pixels`]: ImageDecoded::pixels
Placeholder {
/// The placeholder size.
pixel_size: PxSize,
},
/// The [`pixels`] is an image with the image full width but with only `height`.
///
/// [`pixels`]: ImageDecoded::pixels
Rows {
/// Offset of the decoded rows.
///
/// This is 0 if the image decodes from top to bottom or is `actual_height - height` if it decodes bottom to top.
y: Px,
/// The actual height of the pixels.
height: Px,
},
}
bitflags! {
/// Capabilities of an [`ImageFormat`] implementation.
///
/// Note that `DECODE` capability is omitted because the view-process can always decode formats.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ImageFormatCapability: u32 {
/// View-process can encode images in this format.
const ENCODE = 1 << 0;
/// View-process can decode multiple containers of the format with multiple image entries.
const DECODE_ENTRIES = 1 << 1;
/// View-process can encode multiple images into a single container of the format.
const ENCODE_ENTRIES = (1 << 2) | ImageFormatCapability::ENCODE.bits();
/// View-process can decode pixels as they are received.
///
/// Note that the view-process can always handle progressive data by accumulating it and then decoding.
/// The decoder can also decode the metadata before receiving all data, that does not count as progressive decoding either.
const DECODE_PROGRESSIVE = 1 << 3;
}
}
/// Represents an image codec capability.
///
/// This type will be used in the next breaking release of the view API.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ImageFormat {
/// Display name of the format.
pub display_name: Txt,
/// Media types (MIME) associated with the format.
///
/// Lowercase, without `"image/"` prefix, comma separated if there is more than one.
pub media_type_suffixes: Txt,
/// Common file extensions associated with the format.
///
/// Lowercase, without dot, comma separated if there is more than one.
pub file_extensions: Txt,
/// Identifier file prefixes.
///
/// Lower case ASCII hexadecimals, comma separated if there is more than one, `"xx"` matches any byte.
pub magic_numbers: Txt,
/// Capabilities of this format.
pub capabilities: ImageFormatCapability,
}
impl ImageFormat {
/// From static str.
///
/// # Panics
///
/// Panics if `media_type_suffixes` not ASCII.
#[deprecated = "use `from_static2`, it will replace this function next breaking release"]
pub const fn from_static(
display_name: &'static str,
media_type_suffixes: &'static str,
file_extensions: &'static str,
capabilities: ImageFormatCapability,
) -> Self {
assert!(media_type_suffixes.is_ascii());
Self {
display_name: Txt::from_static(display_name),
media_type_suffixes: Txt::from_static(media_type_suffixes),
file_extensions: Txt::from_static(file_extensions),
magic_numbers: Txt::from_static(""),
capabilities,
}
}
/// From static strings.
///
/// # Panics
///
/// Panics if `media_type_suffixes` or `magic_numbers` are not ASCII.
pub const fn from_static2(
display_name: &'static str,
media_type_suffixes: &'static str,
file_extensions: &'static str,
magic_numbers: &'static str,
capabilities: ImageFormatCapability,
) -> Self {
assert!(media_type_suffixes.is_ascii());
assert!(magic_numbers.is_ascii());
Self {
display_name: Txt::from_static(display_name),
media_type_suffixes: Txt::from_static(media_type_suffixes),
file_extensions: Txt::from_static(file_extensions),
magic_numbers: Txt::from_static(magic_numbers),
capabilities,
}
}
/// Iterate over media type suffixes.
pub fn media_type_suffixes_iter(&self) -> impl Iterator<Item = &str> {
self.media_type_suffixes.split(',').map(|e| e.trim())
}
/// Iterate over full media types, with `"image/"` prefix.
pub fn media_types(&self) -> impl Iterator<Item = Txt> {
self.media_type_suffixes_iter().map(Txt::from_str)
}
/// Iterate over extensions.
pub fn file_extensions_iter(&self) -> impl Iterator<Item = &str> {
self.file_extensions.split(',').map(|e| e.trim())
}
/// Checks if `f` matches any of the mime types or any of the file extensions.
///
/// File extensions comparison ignores dot and ASCII case.
pub fn matches(&self, f: &str) -> bool {
let f = f.strip_prefix('.').unwrap_or(f);
let f = f.strip_prefix("image/").unwrap_or(f);
self.media_type_suffixes_iter().any(|e| e.eq_ignore_ascii_case(f)) || self.file_extensions_iter().any(|e| e.eq_ignore_ascii_case(f))
}
/// Check if `file_prefix` matches any magic numbers.
///
/// A good size for `file_prefix` is 24 bytes, it should cover all image formats.
pub fn matches_magic(&self, file_prefix: &[u8]) -> bool {
'search: for magic in self.magic_numbers.split(',') {
if magic.is_empty() || magic.len() > file_prefix.len() * 2 {
continue 'search;
}
'm: for (c, b) in magic.as_bytes().chunks_exact(2).zip(file_prefix) {
if c == b"xx" {
continue 'm;
}
fn decode(c: u8) -> u8 {
if c >= b'a' { c - b'a' + 10 } else { c - b'0' }
}
let c = (decode(c[0]) << 4) | decode(c[1]);
if c != *b {
continue 'search;
}
}
return true;
}
false
}
}
/// Basic info about a color model.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ColorType {
/// Color model name.
pub name: Txt,
/// Bits per channel.
pub bits: u8,
/// Channels per pixel.
pub channels: u8,
}
impl ColorType {
/// New.
pub const fn new(name: Txt, bits: u8, channels: u8) -> Self {
Self { name, bits, channels }
}
/// Bit length of a pixel.
pub fn bits_per_pixel(&self) -> u16 {
self.bits as u16 * self.channels as u16
}
/// Byte length of a pixel.
pub fn bytes_per_pixel(&self) -> u16 {
self.bits_per_pixel() / 8
}
}
impl ColorType {
/// BGRA8
pub const BGRA8: ColorType = ColorType::new(Txt::from_static("BGRA8"), 8, 4);
/// RGBA8
pub const RGBA8: ColorType = ColorType::new(Txt::from_static("RGBA8"), 8, 4);
/// A8
pub const A8: ColorType = ColorType::new(Txt::from_static("A8"), 8, 4);
}
/// Represent a image encode request.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ImageEncodeRequest {
/// Image to encode.
pub id: ImageId,
/// Optional entries to also encode.
///
/// If set encodes the `id` as the first *page* followed by each entry in the order given.
pub entries: Vec<(ImageId, ImageEntryKind)>,
/// Format query, view-process uses [`ImageFormat::matches`] to find the format.
pub format: Txt,
}
impl ImageEncodeRequest {
/// New.
pub fn new(id: ImageId, format: Txt) -> Self {
Self {
id,
entries: vec![],
format,
}
}
}