1use bytes::Bytes;
32use image_slash_star::{
33 Decoded, DecodedImage, EncodedImage, ImageFormat, ImageInfo, ImageMode, ImagePalette,
34};
35use std::borrow::Cow;
36use std::sync::{Arc, OnceLock};
37
38use crate::checked_dims::CheckedDims;
39use crate::color::color_type_to_mode;
40use crate::error::PilError;
41use crate::format::parse_format_str;
42use crate::pipeline::{
43 ColorMode, PipelineOp, PixelMode, ResampleFilter, TransformMethod, TransposeMethod,
44};
45use crate::raster::{DynamicImage, GenericImageView};
46
47#[path = "image/encode.rs"]
48mod encode;
49#[path = "image/pipeline_admission.rs"]
50mod pipeline_admission;
51
52#[derive(Debug, Clone)]
61pub struct PipelineOps {
62 chain: Arc<PipelineOpChain>,
63 prefix_cache: Option<PipelinePrefixCache>,
64}
65
66#[derive(Debug)]
67struct PipelineOpChain {
68 parent: Option<Arc<PipelineOpChain>>,
69 op: Option<PipelineOp>,
70 len: usize,
71 mode_preserving: bool,
72 flattened: OnceLock<Arc<[PipelineOp]>>,
73}
74
75impl PipelineOps {
76 pub(crate) fn empty() -> Self {
77 Self {
78 chain: Arc::new(PipelineOpChain {
79 parent: None,
80 op: None,
81 len: 0,
82 mode_preserving: true,
83 flattened: OnceLock::new(),
84 }),
85 prefix_cache: None,
86 }
87 }
88
89 pub(crate) fn one(op: PipelineOp) -> Self {
90 let mode_preserving = op_preserves_mode(&op);
91 Self {
92 chain: Arc::new(PipelineOpChain {
93 parent: None,
94 op: Some(op),
95 len: 1,
96 mode_preserving,
97 flattened: OnceLock::new(),
98 }),
99 prefix_cache: None,
100 }
101 }
102
103 pub(crate) fn append(&self, op: PipelineOp) -> Self {
104 Self {
105 chain: Arc::new(PipelineOpChain {
106 parent: Some(Arc::clone(&self.chain)),
107 mode_preserving: self.chain.mode_preserving && op_preserves_mode(&op),
108 op: Some(op),
109 len: self.chain.len + 1,
110 flattened: OnceLock::new(),
111 }),
112 prefix_cache: self.prefix_cache.clone(),
113 }
114 }
115
116 pub(crate) fn from_vec(ops: Vec<PipelineOp>) -> Self {
117 ops.into_iter()
118 .fold(Self::empty(), |pipeline, op| pipeline.append(op))
119 }
120
121 pub(crate) fn as_slice(&self) -> &[PipelineOp] {
122 self.chain
123 .flattened
124 .get_or_init(|| {
125 let mut reversed = Vec::with_capacity(self.chain.len);
126 let mut cursor = Some(Arc::clone(&self.chain));
127 while let Some(node) = cursor {
128 if let Some(op) = node.op.as_ref() {
129 reversed.push(op.clone());
130 }
131 cursor = node.parent.as_ref().map(Arc::clone);
132 }
133 reversed.reverse();
134 Arc::<[PipelineOp]>::from(reversed)
135 })
136 .as_ref()
137 }
138
139 pub(crate) fn to_vec(&self) -> Vec<PipelineOp> {
140 self.as_slice().to_vec()
141 }
142
143 pub(crate) fn mode_preserving(&self) -> bool {
144 self.chain.mode_preserving
145 }
146
147 pub(crate) fn len(&self) -> usize {
148 self.chain.len
149 }
150
151 pub(crate) fn prefix_cache(&self) -> Option<&PipelinePrefixCache> {
152 self.prefix_cache.as_ref()
153 }
154
155 fn with_prefix_cache(mut self, prefix_cache: Option<PipelinePrefixCache>) -> Self {
156 self.prefix_cache = prefix_cache;
157 self
158 }
159}
160
161fn op_preserves_mode(op: &PipelineOp) -> bool {
169 matches!(
170 op,
171 PipelineOp::Resize { .. }
172 | PipelineOp::ResizeBoxed { .. }
173 | PipelineOp::Crop { .. }
174 | PipelineOp::Rotate { .. }
175 | PipelineOp::Transpose { .. }
176 | PipelineOp::Thumbnail { .. }
177 | PipelineOp::Reduce { .. }
178 | PipelineOp::Filter3x3 { .. }
179 | PipelineOp::Filter5x5 { .. }
180 | PipelineOp::GaussianBlur { .. }
181 | PipelineOp::BoxBlur { .. }
182 | PipelineOp::BoxBlurXY { .. }
183 | PipelineOp::MedianFilter { .. }
184 | PipelineOp::MaxFilter { .. }
185 | PipelineOp::MinFilter { .. }
186 | PipelineOp::RankFilter { .. }
187 | PipelineOp::Autocontrast { .. }
188 | PipelineOp::Invert
189 | PipelineOp::Flip
190 | PipelineOp::Mirror
191 | PipelineOp::Posterize { .. }
192 | PipelineOp::Solarize { .. }
193 | PipelineOp::Contain { .. }
194 | PipelineOp::Cover { .. }
195 | PipelineOp::Fit { .. }
196 | PipelineOp::Pad { .. }
197 | PipelineOp::Scale { .. }
198 | PipelineOp::Expand { .. }
199 | PipelineOp::CropBorder { .. }
200 | PipelineOp::Add { .. }
201 | PipelineOp::Subtract { .. }
202 | PipelineOp::Multiply { .. }
203 | PipelineOp::Screen { .. }
204 | PipelineOp::Darker { .. }
205 | PipelineOp::Lighter { .. }
206 | PipelineOp::Difference { .. }
207 | PipelineOp::Overlay { .. }
208 | PipelineOp::HardLight { .. }
209 | PipelineOp::SoftLight { .. }
210 | PipelineOp::AddModulo { .. }
211 | PipelineOp::SubtractModulo { .. }
212 | PipelineOp::LogicalAnd { .. }
213 | PipelineOp::LogicalOr { .. }
214 | PipelineOp::LogicalXor { .. }
215 | PipelineOp::Offset { .. }
216 | PipelineOp::Duplicate
217 | PipelineOp::InvertChops
218 | PipelineOp::Brightness { .. }
219 | PipelineOp::Contrast { .. }
220 | PipelineOp::ColorSaturation { .. }
221 | PipelineOp::Sharpness { .. }
222 | PipelineOp::EffectSpread { .. }
223 | PipelineOp::Paste { .. }
224 | PipelineOp::DrawLine { .. }
225 | PipelineOp::DrawRectangle { .. }
226 | PipelineOp::DrawRoundedRect { .. }
227 | PipelineOp::DrawEllipse { .. }
228 | PipelineOp::DrawCircle { .. }
229 | PipelineOp::DrawPolygon { .. }
230 | PipelineOp::DrawArc { .. }
231 | PipelineOp::DrawChord { .. }
232 | PipelineOp::DrawPieslice { .. }
233 | PipelineOp::DrawPoint { .. }
234 | PipelineOp::PutPixel { .. }
235 | PipelineOp::PutData { .. }
238 | PipelineOp::Eval { .. }
239 )
240}
241
242fn known_putalpha_mode(mode: PixelMode) -> Option<&'static str> {
243 match mode {
244 PixelMode::YCbCr | PixelMode::HSV | PixelMode::RGB => Some("RGBA"),
245 PixelMode::L | PixelMode::LA => Some("LA"),
246 PixelMode::RGBA => Some("RGBA"),
247 PixelMode::P | PixelMode::PA => Some("PA"),
248 PixelMode::CMYK => Some("RGBA"),
249 _ => None,
253 }
254}
255
256pub(crate) fn known_pipeline_op_mode(op: &PipelineOp, current: &str) -> Option<String> {
263 if op_preserves_mode(op) {
264 return Some(current.to_owned());
265 }
266 Some(
267 match op {
268 PipelineOp::Equalize | PipelineOp::EqualizeMasked { .. }
269 if matches!(current, "P" | "PA") =>
270 {
271 "RGB"
272 }
273 PipelineOp::Equalize | PipelineOp::EqualizeMasked { .. } => current,
274 PipelineOp::Convert { mode, .. } | PipelineOp::Merge { mode, .. } => match mode {
281 ColorMode::L => "L",
282 ColorMode::LA => "LA",
283 ColorMode::RGB => "RGB",
284 ColorMode::RGBA => "RGBA",
285 _ => return None,
286 },
287 PipelineOp::ConvertLab { .. } => "LAB",
288 PipelineOp::Grayscale => "L",
289 PipelineOp::Colorize { .. } => "RGB",
290 PipelineOp::Constant { .. } => "L",
291 PipelineOp::PutAlpha { mode, .. } | PipelineOp::PutAlphaData { mode, .. } => {
292 known_putalpha_mode(*mode)?
293 }
294 PipelineOp::ExtractBand { .. } => "L",
295 PipelineOp::EffectNoise { .. } => "L",
296 _ => return None,
297 }
298 .to_owned(),
299 )
300}
301
302fn round_dimension(value: f64) -> Option<u32> {
308 if !value.is_finite() || value < 0.0 || value > f64::from(u32::MAX) {
309 return None;
310 }
311 let lower = value.floor();
312 let fraction = value - lower;
313 let rounded = if fraction < 0.5 {
314 lower
315 } else if fraction > 0.5 || (lower as u64) % 2 == 1 {
316 lower + 1.0
317 } else {
318 lower
319 };
320 (rounded <= f64::from(u32::MAX)).then_some(rounded as u32)
321}
322
323fn known_pipeline_op_dimensions(
329 op: &PipelineOp,
330 (width, height): (u32, u32),
331) -> Option<(u32, u32)> {
332 match op {
333 PipelineOp::Resize { w, h, .. }
334 | PipelineOp::ResizeBoxed { w, h, .. }
335 | PipelineOp::Thumbnail { w, h, .. }
336 | PipelineOp::Pad { w, h, .. }
337 | PipelineOp::Transform { w, h, .. } => Some((*w, *h)),
338 PipelineOp::Crop {
339 left,
340 top,
341 right,
342 bottom,
343 } => Some((right.checked_sub(*left)?, bottom.checked_sub(*top)?)),
344 PipelineOp::Expand { border, .. } => {
345 let border = border.checked_mul(2)?;
346 Some((width.checked_add(border)?, height.checked_add(border)?))
347 }
348 PipelineOp::CropBorder { border } => {
349 let border = border.checked_mul(2)?;
350 Some((width.checked_sub(border)?, height.checked_sub(border)?))
351 }
352 PipelineOp::Transpose { method } => Some(match method {
353 TransposeMethod::Rotate90
354 | TransposeMethod::Rotate270
355 | TransposeMethod::Transpose
356 | TransposeMethod::Transverse => (height, width),
357 TransposeMethod::FlipLeftRight
358 | TransposeMethod::FlipTopBottom
359 | TransposeMethod::Rotate180 => (width, height),
360 }),
361 PipelineOp::Rotate {
362 angle,
363 expand,
364 center,
365 translate,
366 ..
367 } => {
368 if !expand {
369 return Some((width, height));
370 }
371 let normalized = angle.rem_euclid(360.0);
376 if center.is_none()
377 && translate.is_none()
378 && [90.0, 270.0]
379 .into_iter()
380 .any(|right_angle| (normalized - right_angle).abs() <= f64::EPSILON)
381 {
382 return Some((height, width));
383 }
384 let sw = f64::from(width);
385 let sh = f64::from(height);
386 let radians = -angle.to_radians();
387 let affine_a = crate::ops::rotate::round_rotate_coefficient(radians.cos());
388 let affine_b = crate::ops::rotate::round_rotate_coefficient(radians.sin());
389 let affine_d = crate::ops::rotate::round_rotate_coefficient(-radians.sin());
390 let affine_e = affine_a;
391 let (center_x, center_y) = center.unwrap_or((sw / 2.0, sh / 2.0));
392 let (translate_x, translate_y) = translate.unwrap_or((0.0, 0.0));
393 let affine_c = affine_a * (-center_x - translate_x)
394 + affine_b * (-center_y - translate_y)
395 + center_x;
396 let affine_f = affine_d * (-center_x - translate_x)
397 + affine_e * (-center_y - translate_y)
398 + center_y;
399 let transform = |x: f64, y: f64| {
400 (
401 affine_a * x + affine_b * y + affine_c,
402 affine_d * x + affine_e * y + affine_f,
403 )
404 };
405 let corners = [(0.0, 0.0), (sw, 0.0), (sw, sh), (0.0, sh)];
406 let (mut min_x, mut min_y, mut max_x, mut max_y) =
407 (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
408 for &(x, y) in &corners {
409 let (rotated_x, rotated_y) = transform(x, y);
410 min_x = min_x.min(rotated_x);
411 max_x = max_x.max(rotated_x);
412 min_y = min_y.min(rotated_y);
413 max_y = max_y.max(rotated_y);
414 }
415 Some((
416 round_dimension(max_x.ceil() - min_x.floor())?,
417 round_dimension(max_y.ceil() - min_y.floor())?,
418 ))
419 }
420 PipelineOp::Reduce { x_factor, y_factor } => Some((
421 width.div_ceil((*x_factor).max(1)),
422 height.div_ceil((*y_factor).max(1)),
423 )),
424 PipelineOp::Scale { factor, .. } => Some((
425 round_dimension(f64::from(width) * *factor)?.max(1),
426 round_dimension(f64::from(height) * *factor)?.max(1),
427 )),
428 PipelineOp::Contain { w, h, .. } | PipelineOp::Cover { w, h, .. } => {
429 if width == 0 || height == 0 || *w == 0 || *h == 0 {
430 return None;
431 }
432 let image_ratio = f64::from(width) / f64::from(height);
433 let destination_ratio = f64::from(*w) / f64::from(*h);
434 if (image_ratio - destination_ratio).abs() < 1e-10 {
435 return Some((*w, *h));
436 }
437 let cover = matches!(op, PipelineOp::Cover { .. });
438 if (image_ratio > destination_ratio) != cover {
439 let new_height =
440 round_dimension(f64::from(height) / f64::from(width) * f64::from(*w))?;
441 Some((*w, if cover { new_height.max(1) } else { new_height }))
442 } else {
443 let new_width =
444 round_dimension(f64::from(width) / f64::from(height) * f64::from(*h))?;
445 Some((if cover { new_width.max(1) } else { new_width }, *h))
446 }
447 }
448 PipelineOp::Convert { .. }
452 | PipelineOp::ConvertLab { .. }
453 | PipelineOp::RemapPalette { .. }
454 | PipelineOp::Color3DLut { .. }
455 | PipelineOp::ExtractBand { .. }
456 | PipelineOp::Filter3x3 { .. }
457 | PipelineOp::Filter5x5 { .. }
458 | PipelineOp::GaussianBlur { .. }
459 | PipelineOp::BoxBlur { .. }
460 | PipelineOp::BoxBlurXY { .. }
461 | PipelineOp::MedianFilter { .. }
462 | PipelineOp::MaxFilter { .. }
463 | PipelineOp::MinFilter { .. }
464 | PipelineOp::RankFilter { .. }
465 | PipelineOp::Autocontrast { .. }
466 | PipelineOp::Equalize
467 | PipelineOp::EqualizeMasked { .. }
468 | PipelineOp::Invert
469 | PipelineOp::Flip
470 | PipelineOp::Mirror
471 | PipelineOp::Posterize { .. }
472 | PipelineOp::Solarize { .. }
473 | PipelineOp::Grayscale
474 | PipelineOp::Colorize { .. }
475 | PipelineOp::Constant { .. }
476 | PipelineOp::PutPixel { .. }
481 | PipelineOp::Offset { .. }
482 | PipelineOp::Duplicate
483 | PipelineOp::InvertChops
484 | PipelineOp::Brightness { .. }
485 | PipelineOp::Contrast { .. }
486 | PipelineOp::ColorSaturation { .. }
487 | PipelineOp::Sharpness { .. }
488 | PipelineOp::EffectSpread { .. }
489 | PipelineOp::Eval { .. }
490 | PipelineOp::EffectNoise { .. }
491 | PipelineOp::DrawLine { .. }
492 | PipelineOp::DrawRectangle { .. }
493 | PipelineOp::DrawRoundedRect { .. }
494 | PipelineOp::DrawEllipse { .. }
495 | PipelineOp::DrawCircle { .. }
496 | PipelineOp::DrawPolygon { .. }
497 | PipelineOp::DrawArc { .. }
498 | PipelineOp::DrawChord { .. }
499 | PipelineOp::DrawPieslice { .. }
500 | PipelineOp::DrawPoint { .. } => Some((width, height)),
501 _ => None,
502 }
503}
504
505impl std::ops::Deref for PipelineOps {
506 type Target = [PipelineOp];
507
508 fn deref(&self) -> &Self::Target {
509 self.as_slice()
510 }
511}
512
513#[derive(Debug, Clone)]
515pub enum ImagingCoreBytesInput {
516 Scalars(Vec<i64>),
518 Floats(Vec<f64>),
520 Multiband,
522}
523
524pub fn imaging_core_to_bytes(input: ImagingCoreBytesInput) -> Result<Vec<u8>, PilError> {
526 match input {
527 ImagingCoreBytesInput::Scalars(values) => values
528 .into_iter()
529 .map(|value| {
530 u8::try_from(value)
531 .map_err(|_| PilError::ValueError("bytes must be in range(0, 256)".into()))
532 })
533 .collect(),
534 ImagingCoreBytesInput::Floats(_) => Err(PilError::TypeError(
537 "'float' object cannot be interpreted as an integer".into(),
538 )),
539 ImagingCoreBytesInput::Multiband => Err(PilError::TypeError(
542 "'tuple' object cannot be interpreted as an integer".into(),
543 )),
544 }
545}
546
547#[derive(Debug, Clone, Default, PartialEq, Eq)]
549pub struct ExifCompatFields {
550 pub loaded_exif: Option<Vec<u8>>,
552 pub head: Option<Vec<u8>>,
554 pub endian: Option<String>,
556 pub bigtiff: bool,
558 pub has_source: bool,
560}
561
562pub fn prepare_exif_compat(raw: Option<&[u8]>, loaded_exif: bool) -> ExifCompatFields {
564 let Some(raw) = raw.filter(|raw| !raw.is_empty()) else {
565 return ExifCompatFields::default();
566 };
567 let payload = raw.strip_prefix(b"Exif\0\0").unwrap_or(raw);
568 let endian = (payload.len() >= 4)
569 .then(|| &payload[2..4])
570 .filter(|magic| *magic == b"*\0" || *magic == b"\0*")
571 .map(|_| {
572 if payload.starts_with(b"II") {
573 "<".to_owned()
574 } else {
575 ">".to_owned()
576 }
577 });
578 ExifCompatFields {
579 loaded_exif: loaded_exif.then(|| raw.to_vec()),
580 head: Some(payload[..payload.len().min(8)].to_vec()),
581 endian,
582 bigtiff: !loaded_exif,
583 has_source: true,
584 }
585}
586
587fn clear_palette_info_alpha(info: &mut Option<ImageInfo>) {
588 let Some(info) = info.as_mut() else {
589 return;
590 };
591 let Some(palette) = info.palette.as_mut() else {
592 return;
593 };
594 palette.alpha.clear();
595}
596
597#[derive(Debug, Clone)]
602pub struct PalettedData {
603 pub indices: crate::raster::GrayImage,
605 pub palette: Vec<u8>,
607 pub palette_alpha: Vec<u8>,
609 pub source_format: Option<ImageFormat>,
611 pub info: Option<ImageInfo>,
613 pub exif: Option<Vec<u8>>,
615 pub materialized: MaterializationCache,
617}
618
619#[derive(Debug, Clone, PartialEq, Eq)]
621pub enum PaletteTransparency {
622 Index(u8),
624 Table(Vec<u8>),
626}
627
628#[derive(Debug, Clone, PartialEq)]
631pub enum ImageInfoValue {
632 Integer(i64),
634 Float(f64),
636 String(String),
638 Bytes(Vec<u8>),
640 IntegerList(Vec<i64>),
642 FloatList(Vec<f64>),
644 IntegerTuple(Vec<i64>),
646 Object(Vec<(String, ImageInfoValue)>),
648}
649
650#[derive(Debug, Clone)]
652pub struct LoadedData {
653 pub image: Arc<DynamicImage>,
655 pub(crate) known_zero_fill: bool,
658 pub explicit_mode: Option<String>,
660 pub decoded_mode: ImageMode,
662 pub palette: Option<Vec<u8>>,
664 pub palette_alpha: Option<Vec<u8>>,
666 pub source_format: Option<ImageFormat>,
668 pub info: Option<ImageInfo>,
670 pub exif: Option<Vec<u8>>,
672}
673
674#[cfg(feature = "gpu")]
676#[derive(Clone)]
677pub(crate) struct GpuResultMetadata {
678 info: Option<ImageInfo>,
679 exif: Option<Vec<u8>>,
680 format: Option<ImageFormat>,
681}
682
683#[cfg(feature = "gpu")]
684impl GpuResultMetadata {
685 pub(crate) fn materialize(&self, image: DynamicImage, mode: &str) -> Image {
686 let mut result = Image::from_dynamic(image, Some(mode.to_owned()));
687 if let Image::Loaded(data) = &mut result {
688 data.info = self.info.clone();
689 data.exif = self.exif.clone();
690 data.source_format = self.format;
691 }
692 result
693 }
694}
695
696enum ImageByteExport {
698 Shared(Arc<DynamicImage>),
699 Packed(Vec<u8>),
700}
701
702impl AsRef<[u8]> for ImageByteExport {
703 fn as_ref(&self) -> &[u8] {
704 match self {
705 Self::Shared(image) => image.as_bytes(),
706 Self::Packed(bytes) => bytes,
707 }
708 }
709}
710
711#[derive(Debug, Clone, PartialEq)]
718pub enum PutDataValue {
719 Number(f64),
721 Packed(i64),
723 Components(Vec<i128>),
726}
727
728#[derive(Debug, Clone, Copy, PartialEq, Eq)]
734pub enum PutDataValueKind {
735 Numeric,
737 Components {
739 channels: usize,
741 },
742}
743
744#[derive(Debug, Clone, Copy)]
750pub enum PutDataInput<'a> {
751 Integers(&'a [i64]),
753 Numbers(&'a [f64]),
755}
756
757#[derive(Debug, Clone, PartialEq)]
761pub enum FormattedPixelValue {
762 Scalar(u8),
764 Integer(i32),
766 Float(f64),
768 Components(Vec<u8>),
770 InlineComponents {
772 bytes: [u8; 4],
774 bands: u8,
776 },
777}
778
779const PILLOW_COLOR_TABLE_SIZES: &[(u32, u32)] = &[
782 (4, 3),
783 (8, 3),
784 (16, 3),
785 (32, 5),
786 (64, 3),
787 (128, 3),
788 (256, 29),
789 (512, 17),
790 (1024, 9),
791 (2048, 5),
792 (4096, 83),
793 (8192, 27),
794 (16384, 43),
795 (32768, 3),
796 (65536, 45),
797 (131072, 9),
798 (262144, 39),
799 (524288, 39),
800 (1048576, 9),
801 (2097152, 5),
802 (4194304, 3),
803 (8388608, 33),
804 (16777216, 27),
805 (33554432, 9),
806 (67108864, 71),
807 (134217728, 39),
808 (268435456, 9),
809 (536870912, 5),
810 (1073741824, 83),
811];
812
813fn pillow_color_table_parameters(maxcolors: u32) -> Option<(u32, u32)> {
814 PILLOW_COLOR_TABLE_SIZES
815 .iter()
816 .find(|(size, _)| *size > maxcolors)
817 .map(|(size, polynomial)| (size - 1, *polynomial))
818}
819
820const PILLOW_COLOR_DIRECT_TABLE_MAX_BYTES: usize = 8 * 1024 * 1024;
821
822fn pillow_color_direct_table_slots(code_mask: u32, pixel_count: usize) -> Option<usize> {
823 let slots = usize::try_from(code_mask).ok()?.checked_add(1)?;
824 if code_mask <= 1023 {
825 return Some(slots);
826 }
827
828 let bytes = slots.checked_mul(std::mem::size_of::<u64>())?;
829 (bytes <= PILLOW_COLOR_DIRECT_TABLE_MAX_BYTES && slots <= pixel_count.saturating_mul(2))
830 .then_some(slots)
831}
832
833fn pillow_image_pixel_count(image: &DynamicImage) -> usize {
834 let (width, height) = image.dimensions();
835 usize::try_from(width)
836 .ok()
837 .and_then(|width| {
838 usize::try_from(height)
839 .ok()
840 .and_then(|height| width.checked_mul(height))
841 })
842 .unwrap_or(0)
843}
844
845enum PillowColorCounts {
846 Direct(Vec<u64>),
847 Sparse(std::collections::HashMap<u32, (u32, u32)>),
848}
849
850impl PillowColorCounts {
851 fn new(code_mask: u32, sparse_capacity: usize, pixel_count: usize) -> Self {
852 if let Some(slot_count) = pillow_color_direct_table_slots(code_mask, pixel_count) {
856 if slot_count <= 1024 {
857 return Self::Direct(vec![0; slot_count]);
858 }
859
860 let mut slots = Vec::new();
861 if slots.try_reserve_exact(slot_count).is_ok() {
862 slots.resize(slot_count, 0);
863 return Self::Direct(slots);
864 }
865 }
866 Self::Sparse(std::collections::HashMap::with_capacity(sparse_capacity))
867 }
868
869 fn count(
870 &mut self,
871 colors: &mut usize,
872 pixel: u32,
873 maxcolors: usize,
874 code_mask: u32,
875 code_polynomial: u32,
876 ) -> bool {
877 match self {
878 Self::Direct(slots) => count_pillow_color_direct(
879 slots,
880 colors,
881 pixel,
882 maxcolors,
883 code_mask,
884 code_polynomial,
885 ),
886 Self::Sparse(table) => count_pillow_color_sparse(
887 table,
888 colors,
889 pixel,
890 maxcolors,
891 code_mask,
892 code_polynomial,
893 ),
894 }
895 }
896
897 fn count_repeated(
898 &mut self,
899 colors: &mut usize,
900 pixel: u32,
901 repetitions: usize,
902 maxcolors: usize,
903 code_mask: u32,
904 code_polynomial: u32,
905 ) -> Option<bool> {
906 if repetitions <= 1 {
907 return Some(self.count(colors, pixel, maxcolors, code_mask, code_polynomial));
908 }
909 let repetitions = u32::try_from(repetitions).ok()?;
910 match self {
911 Self::Direct(slots) => count_pillow_color_direct_repeated(
912 slots,
913 colors,
914 pixel,
915 repetitions,
916 maxcolors,
917 code_mask,
918 code_polynomial,
919 ),
920 Self::Sparse(table) => count_pillow_color_sparse_repeated(
921 table,
922 colors,
923 pixel,
924 repetitions,
925 maxcolors,
926 code_mask,
927 code_polynomial,
928 ),
929 }
930 }
931
932 fn into_slot_order(self, distinct_colors: usize) -> Vec<(u32, (u32, u32))> {
933 match self {
934 Self::Direct(slots) => {
935 let mut result = Vec::with_capacity(distinct_colors);
936 result.extend(slots.into_iter().enumerate().filter_map(|(slot, packed)| {
937 (packed != 0).then_some((slot as u32, (packed as u32, (packed >> 32) as u32)))
938 }));
939 result
940 }
941 Self::Sparse(table) => {
942 let mut result: Vec<_> = table.into_iter().collect();
943 result.sort_unstable_by_key(|(slot, _)| *slot);
944 result
945 }
946 }
947 }
948}
949
950fn count_pillow_color_direct(
953 slots: &mut [u64],
954 colors: &mut usize,
955 pixel: u32,
956 maxcolors: usize,
957 code_mask: u32,
958 code_polynomial: u32,
959) -> bool {
960 let mut slot = (!pixel) & code_mask;
961 let mut increment = 0u32;
962 let mut first_conflict = true;
963
964 loop {
965 let entry = &mut slots[slot as usize];
966 if *entry == 0 {
967 if *colors == maxcolors {
968 return false;
969 }
970 *entry = (1u64 << 32) | u64::from(pixel);
971 *colors += 1;
972 return true;
973 }
974 if *entry as u32 == pixel {
975 let count = (*entry >> 32) as u32 + 1;
976 *entry = (u64::from(count) << 32) | u64::from(pixel);
977 return true;
978 }
979
980 if first_conflict {
981 increment = (pixel ^ (pixel >> 3)) & code_mask;
982 if increment == 0 {
983 increment = code_mask;
984 }
985 first_conflict = false;
986 } else {
987 increment <<= 1;
988 if increment > code_mask {
989 increment ^= code_polynomial;
990 }
991 }
992 slot = (slot + increment) & code_mask;
993 }
994}
995
996fn count_pillow_color_sparse(
1000 table: &mut std::collections::HashMap<u32, (u32, u32)>,
1001 colors: &mut usize,
1002 pixel: u32,
1003 maxcolors: usize,
1004 code_mask: u32,
1005 code_polynomial: u32,
1006) -> bool {
1007 let mut slot = (!pixel) & code_mask;
1008 let mut increment = 0u32;
1009 let mut first_conflict = true;
1010
1011 loop {
1012 match table.entry(slot) {
1013 std::collections::hash_map::Entry::Occupied(mut entry) => {
1014 let (stored_pixel, count) = entry.get_mut();
1015 if *stored_pixel == pixel {
1016 *count += 1;
1017 return true;
1018 }
1019 }
1020 std::collections::hash_map::Entry::Vacant(entry) => {
1021 if *colors == maxcolors {
1022 return false;
1023 }
1024 entry.insert((pixel, 1));
1025 *colors += 1;
1026 return true;
1027 }
1028 }
1029
1030 if first_conflict {
1031 increment = (pixel ^ (pixel >> 3)) & code_mask;
1032 if increment == 0 {
1033 increment = code_mask;
1034 }
1035 first_conflict = false;
1036 } else {
1037 increment <<= 1;
1038 if increment > code_mask {
1039 increment ^= code_polynomial;
1040 }
1041 }
1042 slot = (slot + increment) & code_mask;
1043 }
1044}
1045
1046fn count_pillow_color_scalar_samples(
1050 counts: &mut PillowColorCounts,
1051 colors: &mut usize,
1052 bytes: &[u8],
1053 maxcolors: usize,
1054 code_mask: u32,
1055 code_polynomial: u32,
1056) -> bool {
1057 match counts {
1058 PillowColorCounts::Direct(slots) => {
1059 for sample in bytes.chunks_exact(4) {
1060 let pixel = u32::from_ne_bytes([sample[0], sample[1], sample[2], sample[3]]);
1061 if !count_pillow_color_direct(
1062 slots,
1063 colors,
1064 pixel,
1065 maxcolors,
1066 code_mask,
1067 code_polynomial,
1068 ) {
1069 return false;
1070 }
1071 }
1072 }
1073 PillowColorCounts::Sparse(table) => {
1074 for sample in bytes.chunks_exact(4) {
1075 let pixel = u32::from_ne_bytes([sample[0], sample[1], sample[2], sample[3]]);
1076 if !count_pillow_color_sparse(
1077 table,
1078 colors,
1079 pixel,
1080 maxcolors,
1081 code_mask,
1082 code_polynomial,
1083 ) {
1084 return false;
1085 }
1086 }
1087 }
1088 }
1089 true
1090}
1091
1092fn count_pillow_color_direct_repeated(
1096 slots: &mut [u64],
1097 colors: &mut usize,
1098 pixel: u32,
1099 repetitions: u32,
1100 maxcolors: usize,
1101 code_mask: u32,
1102 code_polynomial: u32,
1103) -> Option<bool> {
1104 let mut slot = (!pixel) & code_mask;
1105 let mut increment = 0u32;
1106 let mut first_conflict = true;
1107
1108 loop {
1109 let entry = &mut slots[slot as usize];
1110 if *entry == 0 {
1111 if *colors == maxcolors {
1112 return Some(false);
1113 }
1114 *entry = (u64::from(repetitions) << 32) | u64::from(pixel);
1115 *colors += 1;
1116 return Some(true);
1117 }
1118 if *entry as u32 == pixel {
1119 let count = (*entry >> 32) as u32;
1120 let count = count.checked_add(repetitions)?;
1121 *entry = (u64::from(count) << 32) | u64::from(pixel);
1122 return Some(true);
1123 }
1124
1125 if first_conflict {
1126 increment = (pixel ^ (pixel >> 3)) & code_mask;
1127 if increment == 0 {
1128 increment = code_mask;
1129 }
1130 first_conflict = false;
1131 } else {
1132 increment <<= 1;
1133 if increment > code_mask {
1134 increment ^= code_polynomial;
1135 }
1136 }
1137 slot = (slot + increment) & code_mask;
1138 }
1139}
1140
1141fn count_pillow_color_sparse_repeated(
1144 table: &mut std::collections::HashMap<u32, (u32, u32)>,
1145 colors: &mut usize,
1146 pixel: u32,
1147 repetitions: u32,
1148 maxcolors: usize,
1149 code_mask: u32,
1150 code_polynomial: u32,
1151) -> Option<bool> {
1152 let mut slot = (!pixel) & code_mask;
1153 let mut increment = 0u32;
1154 let mut first_conflict = true;
1155
1156 loop {
1157 match table.get_mut(&slot) {
1158 Some((stored_pixel, count)) if *stored_pixel == pixel => {
1159 *count = count.checked_add(repetitions)?;
1160 return Some(true);
1161 }
1162 Some(_) => {}
1163 None => {
1164 if *colors == maxcolors {
1165 return Some(false);
1166 }
1167 table.insert(slot, (pixel, repetitions));
1168 *colors += 1;
1169 return Some(true);
1170 }
1171 }
1172
1173 if first_conflict {
1174 increment = (pixel ^ (pixel >> 3)) & code_mask;
1175 if increment == 0 {
1176 increment = code_mask;
1177 }
1178 first_conflict = false;
1179 } else {
1180 increment <<= 1;
1181 if increment > code_mask {
1182 increment ^= code_polynomial;
1183 }
1184 }
1185 slot = (slot + increment) & code_mask;
1186 }
1187}
1188
1189fn pillow_color_components(pixel: u32, bands: usize) -> FormattedPixelValue {
1190 let bytes = pixel.to_ne_bytes();
1191 match bands {
1192 2 => FormattedPixelValue::InlineComponents {
1194 bytes: [bytes[0], bytes[3], 0, 0],
1195 bands: 2,
1196 },
1197 3 => FormattedPixelValue::InlineComponents {
1198 bytes: [bytes[0], bytes[1], bytes[2], 0],
1199 bands: 3,
1200 },
1201 4 => FormattedPixelValue::InlineComponents { bytes, bands: 4 },
1202 _ => unreachable!("getcolors only supports one through four bands"),
1203 }
1204}
1205
1206fn pillow_color_pixel(components: &[u8]) -> u32 {
1207 let mut bytes = [0u8; 4];
1208 match components {
1209 [luma, alpha] => {
1210 bytes[0] = *luma;
1211 bytes[1] = *luma;
1214 bytes[2] = *luma;
1215 bytes[3] = *alpha;
1216 }
1217 [first, second, third] => bytes[..3].copy_from_slice(&[*first, *second, *third]),
1218 [first, second, third, fourth] => {
1219 bytes.copy_from_slice(&[*first, *second, *third, *fourth])
1220 }
1221 _ => unreachable!("getcolors only supports one through four bands"),
1222 }
1223 u32::from_ne_bytes(bytes)
1224}
1225
1226enum RgbGrayscaleColorCounts {
1227 NotGrayscale,
1228 TooManyColors,
1229 Colors(Vec<(u32, FormattedPixelValue)>),
1230}
1231
1232enum ScalarColorDomainCounts {
1233 NotApplicable,
1234 TooManyColors,
1235 Colors(Vec<(u32, FormattedPixelValue)>),
1236}
1237
1238fn scalar_byte_domain_index(mode: &str, pixel: u32) -> Option<usize> {
1239 match mode {
1240 "I" => {
1241 let value = i32::from_ne_bytes(pixel.to_ne_bytes());
1242 if (0..=255).contains(&value) {
1243 usize::try_from(value).ok()
1244 } else {
1245 None
1246 }
1247 }
1248 "F" => {
1249 if pixel == 0 {
1250 return Some(0);
1251 }
1252 if pixel >> 31 != 0 {
1253 return None;
1254 }
1255 let exponent = (pixel >> 23) & 0xff;
1256 if !(127..=134).contains(&exponent) {
1257 return None;
1258 }
1259 let shift = 23 - (exponent - 127);
1260 let significand = (1 << 23) | (pixel & 0x7f_ffff);
1261 let fractional_mask = (1 << shift) - 1;
1262 if significand & fractional_mask != 0 {
1263 return None;
1264 }
1265 let value = significand >> shift;
1266 if value <= 255 {
1267 usize::try_from(value).ok()
1268 } else {
1269 None
1270 }
1271 }
1272 _ => None,
1273 }
1274}
1275
1276fn scalar_byte_domain_is_plausible(mode: &str, bytes: &[u8]) -> bool {
1277 let sample_count = bytes.len() / 4;
1278 if sample_count == 0 {
1279 return true;
1280 }
1281 let last_index = sample_count - 1;
1282 let base_step = last_index / 15;
1283 let remainder = last_index % 15;
1284 for ordinal in 0..=15usize {
1285 let Some(sample_index) = base_step
1286 .checked_mul(ordinal)
1287 .and_then(|base| base.checked_add((remainder * ordinal) / 15))
1288 else {
1289 return false;
1290 };
1291 let Some(start) = sample_index.checked_mul(4) else {
1292 return false;
1293 };
1294 let Some(end) = start.checked_add(4) else {
1295 return false;
1296 };
1297 let Some(sample) = bytes.get(start..end) else {
1298 return false;
1299 };
1300 let pixel = u32::from_ne_bytes([sample[0], sample[1], sample[2], sample[3]]);
1301 if scalar_byte_domain_index(mode, pixel).is_none() {
1302 return false;
1303 }
1304 }
1305 true
1306}
1307
1308fn getcolors_scalar_byte_domain(
1309 mode: &str,
1310 bytes: &[u8],
1311 maxcolors: usize,
1312 code_mask: u32,
1313 code_polynomial: u32,
1314) -> ScalarColorDomainCounts {
1315 let mut histogram = [0u32; 256];
1316 let mut first_seen = Vec::<u8>::with_capacity(256);
1317 for sample in bytes.chunks_exact(4) {
1318 let pixel = u32::from_ne_bytes([sample[0], sample[1], sample[2], sample[3]]);
1319 let Some(index) = scalar_byte_domain_index(mode, pixel) else {
1320 return ScalarColorDomainCounts::NotApplicable;
1321 };
1322 let count = histogram[index];
1323 let Some(next_count) = count.checked_add(1) else {
1324 return ScalarColorDomainCounts::NotApplicable;
1325 };
1326 if count == 0 {
1327 if first_seen.len() == maxcolors {
1328 return ScalarColorDomainCounts::TooManyColors;
1329 }
1330 let Ok(index) = u8::try_from(index) else {
1331 return ScalarColorDomainCounts::NotApplicable;
1332 };
1333 first_seen.push(index);
1334 }
1335 histogram[index] = next_count;
1336 }
1337
1338 let mut counts =
1341 PillowColorCounts::Sparse(std::collections::HashMap::with_capacity(first_seen.len()));
1342 let mut distinct_colors = 0usize;
1343 for value in first_seen {
1344 let index = usize::from(value);
1345 let pixel = if mode == "I" {
1346 u32::from_ne_bytes(i32::from(value).to_ne_bytes())
1347 } else {
1348 f32::from(value).to_bits()
1349 };
1350 let Ok(repetitions) = usize::try_from(histogram[index]) else {
1351 return ScalarColorDomainCounts::NotApplicable;
1352 };
1353 let Some(counted) = counts.count_repeated(
1354 &mut distinct_colors,
1355 pixel,
1356 repetitions,
1357 maxcolors,
1358 code_mask,
1359 code_polynomial,
1360 ) else {
1361 return ScalarColorDomainCounts::NotApplicable;
1362 };
1363 if !counted {
1364 return ScalarColorDomainCounts::TooManyColors;
1365 }
1366 }
1367
1368 ScalarColorDomainCounts::Colors(
1369 counts
1370 .into_slot_order(distinct_colors)
1371 .into_iter()
1372 .map(|(_, (pixel, count))| {
1373 let value = if mode == "I" {
1374 FormattedPixelValue::Integer(i32::from_ne_bytes(pixel.to_ne_bytes()))
1375 } else {
1376 FormattedPixelValue::Float(f32::from_bits(pixel) as f64)
1377 };
1378 (count, value)
1379 })
1380 .collect(),
1381 )
1382}
1383
1384const SCALAR_I_SPARSE_RUN_COLOR_LIMIT: usize = 4096;
1385const SCALAR_I_REPEATED_RUN_MIN_PREFIX_SAMPLES: usize = 256;
1386const SCALAR_I_REPEATED_RUN_MIN_DIRECT_SLOTS: usize = 65_536;
1387
1388fn getcolors_scalar_i_repeated_runs(
1389 bytes: &[u8],
1390 maxcolors: usize,
1391 code_mask: u32,
1392 code_polynomial: u32,
1393) -> ScalarColorDomainCounts {
1394 let exact_len = bytes.len() / 4 * 4;
1395 let mut counts = PillowColorCounts::Sparse(std::collections::HashMap::with_capacity(256));
1396 let mut distinct_colors = 0usize;
1397 let mut offset = 0usize;
1398
1399 while offset < exact_len {
1400 let sample = &bytes[offset..offset + 4];
1401 let pixel = u32::from_ne_bytes([sample[0], sample[1], sample[2], sample[3]]);
1402
1403 let pattern = [
1404 sample[0], sample[1], sample[2], sample[3], sample[0], sample[1], sample[2], sample[3],
1405 sample[0], sample[1], sample[2], sample[3], sample[0], sample[1], sample[2], sample[3],
1406 ];
1407 let mut run_end = offset;
1408 while let Some(end) = run_end.checked_add(pattern.len()) {
1409 if end > exact_len || bytes[run_end..end] != pattern[..] {
1410 break;
1411 }
1412 run_end = end;
1413 }
1414 while let Some(end) = run_end.checked_add(4) {
1415 if end > exact_len || bytes[run_end..end] != sample[..] {
1416 break;
1417 }
1418 run_end = end;
1419 }
1420
1421 let repetitions = (run_end - offset) / 4;
1422 match counts.count_repeated(
1423 &mut distinct_colors,
1424 pixel,
1425 repetitions,
1426 maxcolors,
1427 code_mask,
1428 code_polynomial,
1429 ) {
1430 Some(true) => {}
1431 Some(false) => return ScalarColorDomainCounts::TooManyColors,
1432 None => {
1433 for _ in 0..repetitions {
1434 if !counts.count(
1435 &mut distinct_colors,
1436 pixel,
1437 maxcolors,
1438 code_mask,
1439 code_polynomial,
1440 ) {
1441 return ScalarColorDomainCounts::TooManyColors;
1442 }
1443 }
1444 }
1445 }
1446 if distinct_colors > SCALAR_I_SPARSE_RUN_COLOR_LIMIT {
1447 return ScalarColorDomainCounts::NotApplicable;
1448 }
1449 offset = run_end;
1450 }
1451
1452 ScalarColorDomainCounts::Colors(
1453 counts
1454 .into_slot_order(distinct_colors)
1455 .into_iter()
1456 .map(|(_, (pixel, count))| {
1457 (
1458 count,
1459 FormattedPixelValue::Integer(i32::from_ne_bytes(pixel.to_ne_bytes())),
1460 )
1461 })
1462 .collect(),
1463 )
1464}
1465
1466fn scalar_prefix_has_repeated_samples(bytes: &[u8]) -> bool {
1467 let mut samples = bytes.chunks_exact(4).take(64);
1468 let Some(mut previous) = samples.next() else {
1469 return false;
1470 };
1471 let mut repeated_pairs = 0usize;
1472 for sample in samples {
1473 if sample == previous {
1474 repeated_pairs += 1;
1475 if repeated_pairs >= 4 {
1476 return true;
1477 }
1478 }
1479 previous = sample;
1480 }
1481 false
1482}
1483
1484fn scalar_i_prefix_has_long_run(bytes: &[u8]) -> bool {
1485 let Some(first) = bytes.get(..4) else {
1486 return false;
1487 };
1488 bytes
1489 .chunks_exact(4)
1490 .take(SCALAR_I_REPEATED_RUN_MIN_PREFIX_SAMPLES)
1491 .all(|sample| sample == first)
1492}
1493
1494fn getcolors_rgb8_grayscale(
1495 image: &crate::raster::RgbImage,
1496 maxcolors: usize,
1497 code_mask: u32,
1498 code_polynomial: u32,
1499) -> RgbGrayscaleColorCounts {
1500 let mut histogram = [0u32; 256];
1501 let mut distinct_colors = 0usize;
1502 for pixel in image.as_raw().chunks_exact(3) {
1503 let [red, green, blue] = [pixel[0], pixel[1], pixel[2]];
1504 if red != green || green != blue {
1505 return RgbGrayscaleColorCounts::NotGrayscale;
1506 }
1507 let count = &mut histogram[usize::from(red)];
1508 if *count == 0 {
1509 distinct_colors += 1;
1510 if distinct_colors > maxcolors {
1511 return RgbGrayscaleColorCounts::TooManyColors;
1512 }
1513 }
1514 *count += 1;
1515 }
1516
1517 let mut occupied = Vec::<(u32, u32, u32)>::with_capacity(distinct_colors);
1521 for (gray, count) in histogram.into_iter().enumerate() {
1522 if count == 0 {
1523 continue;
1524 }
1525 let Ok(gray) = u8::try_from(gray) else {
1526 continue;
1527 };
1528 let pixel = pillow_color_pixel(&[gray, gray, gray]);
1529 let mut slot = (!pixel) & code_mask;
1530 let mut increment = 0u32;
1531 let mut first_conflict = true;
1532
1533 loop {
1534 if !occupied
1535 .iter()
1536 .any(|(occupied_slot, _, _)| *occupied_slot == slot)
1537 {
1538 occupied.push((slot, pixel, count));
1539 break;
1540 }
1541
1542 if first_conflict {
1543 increment = (pixel ^ (pixel >> 3)) & code_mask;
1544 if increment == 0 {
1545 increment = code_mask;
1546 }
1547 first_conflict = false;
1548 } else {
1549 increment <<= 1;
1550 if increment > code_mask {
1551 increment ^= code_polynomial;
1552 }
1553 }
1554 slot = (slot + increment) & code_mask;
1555 }
1556 }
1557
1558 occupied.sort_unstable_by_key(|(slot, _, _)| *slot);
1559 RgbGrayscaleColorCounts::Colors(
1560 occupied
1561 .into_iter()
1562 .map(|(_, pixel, count)| (count, pillow_color_components(pixel, 3)))
1563 .collect(),
1564 )
1565}
1566
1567#[cfg(test)]
1568mod pillow_color_counts_tests {
1569 use super::{
1570 Image, PILLOW_COLOR_DIRECT_TABLE_MAX_BYTES, PillowColorCounts, RgbGrayscaleColorCounts,
1571 SCALAR_I_REPEATED_RUN_MIN_PREFIX_SAMPLES, SCALAR_I_SPARSE_RUN_COLOR_LIMIT,
1572 ScalarColorDomainCounts, getcolors_rgb8_grayscale, getcolors_scalar_i_repeated_runs,
1573 pillow_color_components, pillow_color_direct_table_slots, pillow_color_pixel,
1574 pillow_color_table_parameters, scalar_i_prefix_has_long_run,
1575 scalar_prefix_has_repeated_samples,
1576 };
1577 use crate::raster::{DynamicImage, RgbImage};
1578
1579 fn scalar_i_bytes(runs: &[(i32, usize)]) -> Vec<u8> {
1580 let mut bytes = Vec::new();
1581 for &(value, repetitions) in runs {
1582 for _ in 0..repetitions {
1583 bytes.extend_from_slice(&value.to_ne_bytes());
1584 }
1585 }
1586 bytes
1587 }
1588
1589 #[test]
1590 fn scalar_i_repeated_runs_match_scalar_inserts_and_preserve_slot_order() {
1591 let bytes = scalar_i_bytes(&[
1592 (7, 3_072),
1593 (2, 1_001),
1594 (7, 19),
1595 (0, 5),
1596 (255, 4_096),
1597 (-1, 3),
1598 ]);
1599 let maxcolors = 1_000_000;
1600 let (code_mask, code_polynomial) =
1601 pillow_color_table_parameters(maxcolors).expect("test limit has a Pillow table");
1602 let actual = getcolors_scalar_i_repeated_runs(
1603 &bytes,
1604 maxcolors as usize,
1605 code_mask,
1606 code_polynomial,
1607 );
1608 let mut expected = PillowColorCounts::Direct(vec![0; code_mask as usize + 1]);
1609 let mut expected_colors = 0usize;
1610 for sample in bytes.chunks_exact(4) {
1611 let pixel = u32::from_ne_bytes([sample[0], sample[1], sample[2], sample[3]]);
1612 assert!(expected.count(
1613 &mut expected_colors,
1614 pixel,
1615 maxcolors as usize,
1616 code_mask,
1617 code_polynomial,
1618 ));
1619 }
1620 let expected = expected
1621 .into_slot_order(expected_colors)
1622 .into_iter()
1623 .map(|(_, (pixel, count))| {
1624 (
1625 count,
1626 super::FormattedPixelValue::Integer(i32::from_ne_bytes(pixel.to_ne_bytes())),
1627 )
1628 })
1629 .collect::<Vec<_>>();
1630 let ScalarColorDomainCounts::Colors(actual) = actual else {
1631 panic!("repeated I input must produce colors");
1632 };
1633 assert_eq!(actual, expected);
1634 }
1635
1636 #[test]
1637 fn scalar_i_repeated_runs_preserve_maxcolors_limit() {
1638 let bytes = scalar_i_bytes(&[(1, 8), (2, 8), (3, 8)]);
1639 let (code_mask, code_polynomial) =
1640 pillow_color_table_parameters(2).expect("test limit has a Pillow table");
1641 assert!(matches!(
1642 getcolors_scalar_i_repeated_runs(&bytes, 2, code_mask, code_polynomial),
1643 ScalarColorDomainCounts::TooManyColors
1644 ));
1645 }
1646
1647 #[test]
1648 fn scalar_i_repeated_runs_yield_to_general_path_after_sparse_limit() {
1649 let mut runs = vec![(0, SCALAR_I_REPEATED_RUN_MIN_PREFIX_SAMPLES)];
1650 runs.extend((1..=SCALAR_I_SPARSE_RUN_COLOR_LIMIT).map(|value| (value as i32, 1)));
1651 let bytes = scalar_i_bytes(&runs);
1652 let maxcolors = 100_000;
1653 let (code_mask, code_polynomial) =
1654 pillow_color_table_parameters(maxcolors as u32).expect("test limit has a Pillow table");
1655
1656 assert!(matches!(
1657 getcolors_scalar_i_repeated_runs(&bytes, maxcolors, code_mask, code_polynomial,),
1658 ScalarColorDomainCounts::NotApplicable
1659 ));
1660 }
1661
1662 #[test]
1663 fn scalar_i_prefix_gate_rejects_short_run_before_high_cardinality_tail() {
1664 let mut runs = vec![(0, 64)];
1665 runs.extend((1..=192).map(|value| (value, 1)));
1666 let bytes = scalar_i_bytes(&runs);
1667
1668 assert!(!scalar_i_prefix_has_long_run(&bytes));
1669 assert!(scalar_prefix_has_repeated_samples(&bytes));
1670 }
1671
1672 #[test]
1673 fn dense_table_admission_is_bounded_by_memory_and_scan_size() {
1674 assert_eq!(pillow_color_direct_table_slots(1023, 0), Some(1024));
1675 assert_eq!(pillow_color_direct_table_slots(2047, 1023), None);
1676 assert_eq!(pillow_color_direct_table_slots(2047, 1024), Some(2048));
1677 assert_eq!(
1678 pillow_color_direct_table_slots(1_048_575, 524_288),
1679 Some(PILLOW_COLOR_DIRECT_TABLE_MAX_BYTES / 8)
1680 );
1681 assert_eq!(
1682 pillow_color_direct_table_slots(2_097_151, usize::MAX),
1683 None,
1684 "the dense table must stay below its byte cap even for large images"
1685 );
1686 }
1687
1688 #[test]
1689 fn dense_and_sparse_tables_keep_pillow_slot_order_and_limits() {
1690 let code_mask = 2047;
1691 let code_polynomial = 5;
1692 let pixels = [0, 2048, 1, 2049, 4096, 0, 2048, 8192];
1693 let mut dense = PillowColorCounts::new(code_mask, 0, 1024);
1694 assert!(matches!(&dense, PillowColorCounts::Direct(_)));
1695 let mut sparse = PillowColorCounts::Sparse(std::collections::HashMap::new());
1696 let mut dense_colors = 0;
1697 let mut sparse_colors = 0;
1698
1699 for pixel in pixels {
1700 let dense_ok = dense.count(&mut dense_colors, pixel, 5, code_mask, code_polynomial);
1701 let sparse_ok = sparse.count(&mut sparse_colors, pixel, 5, code_mask, code_polynomial);
1702 assert_eq!(dense_ok, sparse_ok);
1703 }
1704
1705 assert_eq!(dense_colors, 5);
1706 assert_eq!(dense_colors, sparse_colors);
1707 assert_eq!(
1708 dense.into_slot_order(dense_colors),
1709 sparse.into_slot_order(sparse_colors)
1710 );
1711 assert!(matches!(
1712 PillowColorCounts::new(code_mask, 0, 1023),
1713 PillowColorCounts::Sparse(_)
1714 ));
1715 }
1716
1717 #[test]
1718 fn large_rgb_grayscale_getcolors_matches_pillow_slot_order() {
1719 let mut raw = Vec::with_capacity(256 * 256 * 3);
1720 for _ in 0..256 {
1721 for gray in 0..=u8::MAX {
1722 raw.extend_from_slice(&[gray, gray, gray]);
1723 }
1724 }
1725 let rgb = RgbImage::from_raw(256, 256, raw)
1726 .expect("RGB test data must contain exactly three bytes per pixel");
1727 let image = Image::from_dynamic(DynamicImage::ImageRgb8(rgb.clone()), Some("RGB".into()));
1728 let maxcolors = 1_000_000;
1729 let (code_mask, code_polynomial) =
1730 pillow_color_table_parameters(maxcolors).expect("test limit has a Pillow table");
1731
1732 let mut reference = PillowColorCounts::Sparse(std::collections::HashMap::new());
1733 let mut reference_colors = 0;
1734 for pixel in rgb.pixels() {
1735 assert!(reference.count(
1736 &mut reference_colors,
1737 pillow_color_pixel(&pixel.0),
1738 maxcolors as usize,
1739 code_mask,
1740 code_polynomial,
1741 ));
1742 }
1743 let expected = reference
1744 .into_slot_order(reference_colors)
1745 .into_iter()
1746 .map(|(_, (pixel, count))| (count, pillow_color_components(pixel, 3)))
1747 .collect::<Vec<_>>();
1748
1749 assert!(matches!(
1750 getcolors_rgb8_grayscale(&rgb, maxcolors as usize, code_mask, code_polynomial),
1751 RgbGrayscaleColorCounts::Colors(_)
1752 ));
1753 assert_eq!(
1754 image.getcolors(maxcolors).expect("count should succeed"),
1755 Some(expected)
1756 );
1757 }
1758
1759 #[test]
1760 fn large_rgb_grayscale_shortcut_rejects_mismatched_or_excess_colors() {
1761 let non_gray = RgbImage::from_raw(1, 1, vec![1, 2, 1])
1762 .expect("RGB test data must contain exactly three bytes per pixel");
1763 let (code_mask, code_polynomial) =
1764 pillow_color_table_parameters(1_000_000).expect("test limit has a Pillow table");
1765 assert!(matches!(
1766 getcolors_rgb8_grayscale(&non_gray, 1_000_000, code_mask, code_polynomial),
1767 RgbGrayscaleColorCounts::NotGrayscale
1768 ));
1769
1770 let gray = RgbImage::from_raw(3, 1, vec![0, 0, 0, 127, 127, 127, 255, 255, 255])
1771 .expect("RGB test data must contain exactly three bytes per pixel");
1772 assert!(matches!(
1773 getcolors_rgb8_grayscale(&gray, 2, code_mask, code_polynomial),
1774 RgbGrayscaleColorCounts::TooManyColors
1775 ));
1776 }
1777}
1778
1779#[derive(Debug, Clone, PartialEq)]
1781pub enum FormattedImageData {
1782 Scalars(Vec<u8>),
1784 IntegerScalars(Vec<i32>),
1786 FloatScalars(Vec<f64>),
1788 Components(Vec<Vec<u8>>),
1790}
1791
1792#[derive(Debug, Clone, PartialEq)]
1795pub enum FormattedExtrema {
1796 Empty,
1798 EmptyMultiple(usize),
1800 Single((u8, u8)),
1802 Multiple(Vec<(u8, u8)>),
1804 Integer((i32, i32)),
1806 Float((f64, f64)),
1808}
1809
1810fn pillow_band_count(mode: &str) -> usize {
1811 match mode {
1812 "L" | "1" | "P" | "I" | "F" | "I;16" | "I;16L" | "I;16B" | "I;16N" => 1,
1813 "LA" | "La" | "PA" => 2,
1814 "RGB" | "YCbCr" | "HSV" | "LAB" => 3,
1815 _ => 4,
1816 }
1817}
1818
1819#[inline]
1821fn select_interleaved_band(data: &[u8], bands: usize, band: usize) -> Vec<u8> {
1822 data.chunks_exact(bands).map(|pixel| pixel[band]).collect()
1823}
1824
1825#[inline]
1826fn select_interleaved_band_into(data: &[u8], bands: usize, band: usize, output: &mut [u8]) {
1827 let selected = data.iter().skip(band).step_by(bands);
1828 for (destination, source) in output.iter_mut().zip(selected) {
1829 *destination = *source;
1830 }
1831}
1832
1833#[inline]
1834fn select_lab_band(data: &[u8], band: usize) -> Vec<u8> {
1835 let mut output = vec![0; data.len() / 3];
1836 select_lab_band_into(data, band, &mut output);
1837 output
1838}
1839
1840#[inline]
1841fn select_lab_band_into(data: &[u8], band: usize, output: &mut [u8]) {
1842 for (destination, pixel) in output.iter_mut().zip(data.chunks_exact(3)) {
1843 *destination = match band {
1844 0 => pixel[0],
1845 1 => pixel[1].wrapping_sub(128),
1846 2 => pixel[2].wrapping_sub(128),
1847 _ => unreachable!("LAB has exactly three bands"),
1848 };
1849 }
1850}
1851
1852#[derive(Debug, Clone, PartialEq, Eq)]
1854pub enum ChannelSelector {
1855 Index(i32),
1857 Name(String),
1859 Invalid(String),
1862}
1863
1864#[derive(Debug, Clone, PartialEq)]
1866pub enum PutPixelValue {
1867 Integer(i64),
1869 Float(f64),
1871 Components(Vec<i64>),
1873 FloatComponents(Vec<f64>),
1875 Invalid,
1877}
1878
1879#[derive(Debug, Clone)]
1881pub enum PutAlphaInput {
1882 Integer(i64),
1885 Image(Box<Image>),
1887 Invalid(String),
1889}
1890
1891#[derive(Debug, Clone)]
1893pub struct PythonNewColorInput {
1894 string: Option<String>,
1895 single: Option<u8>,
1896 rgb: Option<(u8, u8, u8)>,
1897 rgba: Option<(u8, u8, u8, u8)>,
1898 luma_alpha: Option<(u8, u8)>,
1899 integer: Option<i32>,
1900 float: Option<f64>,
1901 provided: bool,
1902}
1903
1904impl PythonNewColorInput {
1905 #[allow(clippy::too_many_arguments)]
1907 pub fn from_parts(
1908 string: Option<String>,
1909 single: Option<u8>,
1910 rgb: Option<(u8, u8, u8)>,
1911 rgba: Option<(u8, u8, u8, u8)>,
1912 luma_alpha: Option<(u8, u8)>,
1913 integer: Option<i32>,
1914 float: Option<f64>,
1915 provided: bool,
1916 ) -> Self {
1917 Self {
1918 string,
1919 single,
1920 rgb,
1921 rgba,
1922 luma_alpha,
1923 integer,
1924 float,
1925 provided,
1926 }
1927 }
1928}
1929
1930#[derive(Debug, Clone)]
1932pub enum PythonOpenModeInput {
1933 None,
1935 Name(String),
1937 Invalid(String),
1939}
1940
1941#[derive(Debug, Clone)]
1943pub enum PythonOpenFormatsInput {
1944 None,
1946 Names(Vec<String>),
1948 Invalid(String),
1950}
1951
1952pub fn validate_python_open_inputs(
1954 mode: PythonOpenModeInput,
1955 formats: PythonOpenFormatsInput,
1956) -> Result<Option<Vec<String>>, PilError> {
1957 match mode {
1958 PythonOpenModeInput::None => {}
1959 PythonOpenModeInput::Name(name) if name == "r" => {}
1960 PythonOpenModeInput::Name(name) => {
1961 return Err(PilError::ValueError(format!("bad mode '{name}'")));
1962 }
1963 PythonOpenModeInput::Invalid(value) => {
1964 return Err(PilError::ValueError(format!("bad mode {value}")));
1967 }
1968 }
1969 match formats {
1970 PythonOpenFormatsInput::None => Ok(None),
1971 PythonOpenFormatsInput::Names(names) => Ok(Some(names)),
1972 PythonOpenFormatsInput::Invalid(_) => Err(PilError::TypeError(
1973 "formats must be a list or tuple".to_owned(),
1974 )),
1975 }
1976}
1977
1978pub fn validate_python_open_source_bytes(data: &[u8]) -> Result<(), PilError> {
1980 if data.contains(&0) {
1981 return Err(PilError::ValueError("embedded null byte".to_owned()));
1982 }
1983 Ok(())
1984}
1985
1986#[derive(Clone, Copy)]
1987enum FromBytesMode {
1988 L,
1989 LA,
1990 LAB,
1991 L16,
1992 RGB,
1993 RGBA,
1994 CMYK,
1995 HSV,
1996 YCbCr,
1997 I,
1998 F,
1999 P,
2000 Mode1,
2001}
2002
2003const MODE1_BYTE_PIXELS: [[u8; 8]; 256] = {
2004 let mut table = [[0; 8]; 256];
2005 let mut value = 0;
2006 while value < 256 {
2007 let mut bit = 0;
2008 while bit < 8 {
2009 table[value][bit] = if value & (128 >> bit) == 0 { 0 } else { 255 };
2010 bit += 1;
2011 }
2012 value += 1;
2013 }
2014 table
2015};
2016
2017pub(crate) fn unpack_mode1_rows(packed: &[u8], width: usize, pixels: &mut [u8]) {
2019 if width == 0 {
2020 return;
2021 }
2022 let row_bytes = width.div_ceil(8);
2023 debug_assert!(pixels.len().is_multiple_of(width));
2024 debug_assert!(packed.len() >= row_bytes * (pixels.len() / width));
2025 for (source, destination) in packed
2026 .chunks_exact(row_bytes)
2027 .zip(pixels.chunks_exact_mut(width))
2028 {
2029 let (blocks, tail) = destination.as_chunks_mut::<8>();
2030 for (block, &byte) in blocks.iter_mut().zip(source) {
2031 *block = MODE1_BYTE_PIXELS[usize::from(byte)];
2032 }
2033 if !tail.is_empty() {
2034 tail.copy_from_slice(
2035 &MODE1_BYTE_PIXELS[usize::from(source[blocks.len()])][..tail.len()],
2036 );
2037 }
2038 }
2039}
2040
2041pub(crate) fn pack_mode1_rows(pixels: &[u8], width: usize, height: usize) -> Vec<u8> {
2043 if width == 0 || height == 0 {
2044 return Vec::new();
2045 }
2046 debug_assert!(pixels.len() >= width * height);
2047 let row_bytes = width.div_ceil(8);
2048 let mut packed = vec![0; row_bytes * height];
2049 for (source, destination) in pixels
2050 .chunks_exact(width)
2051 .zip(packed.chunks_exact_mut(row_bytes))
2052 {
2053 let (blocks, tail) = source.as_chunks::<8>();
2054 for (block, byte) in blocks.iter().zip(destination.iter_mut()) {
2055 let word = u64::from_le_bytes(*block);
2056 let flags = (((word & 0x7f7f_7f7f_7f7f_7f7f) + 0x7f7f_7f7f_7f7f_7f7f) | word)
2060 & 0x8080_8080_8080_8080;
2061 *byte = ((flags >> 7).wrapping_mul(0x8040_2010_0804_0201) >> 56) as u8;
2064 }
2065 if !tail.is_empty() {
2066 destination[blocks.len()] = tail.iter().enumerate().fold(0, |byte, (bit, &pixel)| {
2067 byte | (u8::from(pixel != 0) << (7 - bit))
2068 });
2069 }
2070 }
2071 packed
2072}
2073
2074#[cfg(test)]
2075mod mode1_byte_block_tests {
2076 use super::{pack_mode1_rows, unpack_mode1_rows};
2077
2078 #[test]
2079 fn every_packed_byte_expands_in_msb_order() {
2080 for value in 0..=255u8 {
2081 let mut pixels = [0; 8];
2082 unpack_mode1_rows(&[value], 8, &mut pixels);
2083 for (bit, pixel) in pixels.into_iter().enumerate() {
2084 assert_eq!(pixel, if value & (128 >> bit) != 0 { 255 } else { 0 });
2085 }
2086 }
2087 }
2088
2089 #[test]
2090 fn every_nonzero_byte_packs_as_a_set_bit() {
2091 for position in 0..8 {
2092 for background in [0, 1, 127, 128, 255] {
2093 for value in 0..=255u8 {
2094 let mut pixels = [background; 8];
2095 pixels[position] = value;
2096 let expected = pixels.iter().enumerate().fold(0, |byte, (bit, &pixel)| {
2097 byte | (u8::from(pixel != 0) << (7 - bit))
2098 });
2099 assert_eq!(pack_mode1_rows(&pixels, 8, 1), [expected]);
2100 }
2101 }
2102 }
2103 }
2104
2105 #[test]
2106 fn rows_keep_padding_separate_at_each_byte_boundary() {
2107 for width in 0usize..=33 {
2108 for height in 0..=3 {
2109 let row_bytes = width.div_ceil(8);
2110 let mut expected: Vec<u8> = (0..row_bytes * height)
2111 .map(|index| (index * 73 + 29) as u8)
2112 .collect();
2113 let mut pixels = vec![0; width * height];
2114 unpack_mode1_rows(&expected, width, &mut pixels);
2115 if !width.is_multiple_of(8) {
2116 for row in expected.chunks_exact_mut(row_bytes) {
2117 row[row_bytes - 1] &= 255 << (8 - width % 8);
2118 }
2119 }
2120 assert_eq!(pack_mode1_rows(&pixels, width, height), expected);
2121 }
2122 }
2123 }
2124}
2125
2126#[cfg(test)]
2127mod getpixel_rgb_fast_path_tests {
2128 use super::{Image, PilError};
2129
2130 #[test]
2131 fn fast_path_reads_only_loaded_native_rgb_pixels() -> Result<(), PilError> {
2132 let rgb = Image::new(2, 1, "RGB", (17, 83, 211, 255))?;
2133 assert_eq!(rgb.getpixel_rgb_if_loaded(1, 0)?, Some([17, 83, 211]));
2134 assert!(matches!(
2135 rgb.getpixel_rgb_if_loaded(2, 0),
2136 Err(PilError::IndexError(_))
2137 ));
2138
2139 let gray = Image::new(1, 1, "L", (42, 0, 0, 255))?;
2140 assert_eq!(gray.getpixel_rgb_if_loaded(0, 0)?, None);
2141
2142 let deferred = crate::ops::imageops::invert(&rgb)?;
2143 assert_eq!(deferred.getpixel_rgb_if_loaded(0, 0)?, None);
2144 Ok(())
2145 }
2146}
2147
2148pub(crate) enum ScalarImageSamples {
2149 Integer(Vec<i32>),
2150 Float(Vec<f64>),
2151}
2152
2153fn decode_integer_samples(raw: &[u8]) -> Vec<i32> {
2154 raw.chunks_exact(4)
2155 .map(|sample| i32::from_le_bytes([sample[0], sample[1], sample[2], sample[3]]))
2156 .collect()
2157}
2158
2159fn decode_float_samples(raw: &[u8]) -> Vec<f64> {
2160 raw.chunks_exact(4)
2161 .map(|sample| f32::from_le_bytes([sample[0], sample[1], sample[2], sample[3]]) as f64)
2162 .collect()
2163}
2164
2165fn validate_scalar_storage(image: &DynamicImage, mode: &str) -> Result<(), PilError> {
2166 if !matches!(mode, "I" | "F") {
2167 return Ok(());
2168 }
2169 let expected = if image.width() == 0 || image.height() == 0 {
2174 0
2175 } else {
2176 CheckedDims::new(image.width(), image.height(), 4)?.total_bytes()
2177 };
2178 if image.as_bytes().len() != expected {
2179 return Err(PilError::InternalError(format!(
2180 "{mode} image has invalid scalar storage"
2181 )));
2182 }
2183 Ok(())
2184}
2185
2186fn putdata_clip_u8(value: f64) -> u8 {
2187 if value.is_nan() || value >= 255.0 {
2188 255
2189 } else if value <= 0.0 {
2190 0
2191 } else {
2192 value as u8
2193 }
2194}
2195
2196fn putdata_clip_component(value: i128) -> u8 {
2197 value.clamp(0, 255) as u8
2198}
2199
2200fn is_l16_mode(mode: &str) -> bool {
2201 matches!(mode, "I;16" | "I;16L" | "I;16B" | "I;16N")
2202}
2203
2204fn putalpha_conversion_target(mode: &str) -> Option<&'static str> {
2205 match mode {
2206 "1" | "I" | "I;16" | "I;16L" | "I;16B" | "I;16N" | "F" => Some("LA"),
2207 "YCbCr" | "HSV" => Some("RGBA"),
2208 _ => None,
2209 }
2210}
2211
2212fn l16_uses_big_endian(mode: &str) -> bool {
2213 match mode {
2214 "I;16B" => true,
2215 "I;16L" => false,
2216 "I;16" | "I;16N" => cfg!(target_endian = "big"),
2217 _ => false,
2218 }
2219}
2220
2221fn putdata_l16_sample(value: &PutDataValue, scale: f64, offset: f64) -> Result<u16, PilError> {
2222 match value {
2223 PutDataValue::Number(number) => Ok((number * scale + offset) as u16),
2227 _ => Err(PilError::TypeError("sequence must be flattened".to_owned())),
2231 }
2232}
2233
2234fn putdata_bytes(
2235 mode: crate::pipeline::PixelMode,
2236 values: &[PutDataValue],
2237 scale: f64,
2238 offset: f64,
2239) -> Result<Vec<u8>, PilError> {
2240 let capacity = values
2241 .len()
2242 .checked_mul(mode.channels())
2243 .ok_or_else(|| PilError::DimensionError("putdata byte count overflow".into()))?;
2244 let mut data = Vec::with_capacity(capacity);
2245
2246 for value in values {
2247 match (mode, value) {
2248 (
2249 crate::pipeline::PixelMode::Mode1
2250 | crate::pipeline::PixelMode::L
2251 | crate::pipeline::PixelMode::P,
2252 PutDataValue::Number(number),
2253 ) => data.push(putdata_clip_u8(number * scale + offset)),
2254 (crate::pipeline::PixelMode::I, PutDataValue::Number(number)) => {
2255 data.extend_from_slice(&((number * scale + offset) as i32).to_le_bytes());
2256 }
2257 (crate::pipeline::PixelMode::F, PutDataValue::Number(number)) => {
2258 data.extend_from_slice(&((number * scale + offset) as f32).to_le_bytes());
2259 }
2260 (
2261 crate::pipeline::PixelMode::LA | crate::pipeline::PixelMode::PA,
2262 PutDataValue::Packed(packed),
2263 ) => {
2264 let bytes = packed.to_le_bytes();
2265 data.extend_from_slice(&[bytes[0], bytes[3]]);
2266 }
2267 (
2268 crate::pipeline::PixelMode::RGB
2269 | crate::pipeline::PixelMode::YCbCr
2270 | crate::pipeline::PixelMode::HSV,
2271 PutDataValue::Packed(packed),
2272 ) => data.extend_from_slice(&packed.to_le_bytes()[..3]),
2273 (
2274 crate::pipeline::PixelMode::RGBA | crate::pipeline::PixelMode::CMYK,
2275 PutDataValue::Packed(packed),
2276 ) => data.extend_from_slice(&packed.to_le_bytes()[..4]),
2277 (
2278 crate::pipeline::PixelMode::LA | crate::pipeline::PixelMode::PA,
2279 PutDataValue::Components(components),
2280 ) if components.len() == 2 => {
2281 data.extend(components.iter().copied().map(putdata_clip_component));
2282 }
2283 (
2284 crate::pipeline::PixelMode::RGB
2285 | crate::pipeline::PixelMode::YCbCr
2286 | crate::pipeline::PixelMode::HSV,
2287 PutDataValue::Components(components),
2288 ) if matches!(components.len(), 3 | 4) => {
2289 data.extend(components[..3].iter().copied().map(putdata_clip_component));
2290 }
2291 (
2292 crate::pipeline::PixelMode::RGBA | crate::pipeline::PixelMode::CMYK,
2293 PutDataValue::Components(components),
2294 ) if matches!(components.len(), 3 | 4) => {
2295 data.extend(components[..3].iter().copied().map(putdata_clip_component));
2296 data.push(
2297 components
2298 .get(3)
2299 .copied()
2300 .map_or(255, putdata_clip_component),
2301 );
2302 }
2303 (
2304 crate::pipeline::PixelMode::LA | crate::pipeline::PixelMode::PA,
2305 PutDataValue::Components(_),
2306 ) => {
2307 return Err(PilError::TypeError(
2308 "color must be int, or tuple of one or two elements".into(),
2309 ));
2310 }
2311 (
2312 crate::pipeline::PixelMode::RGB
2313 | crate::pipeline::PixelMode::RGBA
2314 | crate::pipeline::PixelMode::CMYK
2315 | crate::pipeline::PixelMode::YCbCr
2316 | crate::pipeline::PixelMode::HSV,
2317 PutDataValue::Components(_),
2318 ) => {
2319 return Err(PilError::TypeError(
2320 "color must be int, or tuple of one, three or four elements".into(),
2321 ));
2322 }
2323 (
2324 crate::pipeline::PixelMode::Mode1
2325 | crate::pipeline::PixelMode::L
2326 | crate::pipeline::PixelMode::P
2327 | crate::pipeline::PixelMode::I
2328 | crate::pipeline::PixelMode::F,
2329 _,
2330 ) => {
2331 return Err(PilError::TypeError("sequence must be flattened".into()));
2332 }
2333 _ => {
2334 return Err(PilError::TypeError("color must be int or tuple".into()));
2335 }
2336 }
2337 }
2338
2339 Ok(data)
2340}
2341
2342#[derive(Debug, Clone)]
2348pub enum Image {
2349 Loaded(LoadedData),
2351 Paletted(PalettedData),
2353 Bytes {
2355 source: EncodedImage,
2357 format: Option<ImageFormat>,
2359 info: Option<ImageInfo>,
2361 materialized: MaterializationCache,
2363 },
2364 Pipeline {
2369 source: Arc<Image>,
2371 ops: PipelineOps,
2373 format: Option<ImageFormat>,
2375 explicit_mode: Option<String>,
2377 backend: Option<crate::compute::Backend>,
2379 palette: Option<Vec<u8>>,
2381 palette_alpha: Option<Vec<u8>>,
2383 materialized: MaterializationCache,
2385 shape: PipelineShapeCache,
2387 mode: PipelineModeCache,
2389 },
2390}
2391
2392pub type MaterializationCache = Arc<OnceLock<Result<Arc<DynamicImage>, PilError>>>;
2394
2395fn take_cached_materialization(cache: MaterializationCache) -> Result<Arc<DynamicImage>, PilError> {
2396 match Arc::try_unwrap(cache) {
2397 Ok(cache) => cache.into_inner(),
2398 Err(cache) => cache.get().cloned(),
2399 }
2400 .ok_or_else(|| {
2401 PilError::InternalError("materialized image cache was unexpectedly empty".to_owned())
2402 })?
2403}
2404
2405#[derive(Debug, Clone)]
2412pub struct PipelinePrefixCache {
2413 ops_len: usize,
2415 materialized: MaterializationCache,
2417}
2418
2419pub type PipelineShapeCache = Arc<OnceLock<Result<Option<(u32, u32)>, PilError>>>;
2426
2427pub type PipelineModeCache = Arc<OnceLock<Result<Option<String>, PilError>>>;
2432
2433pub(crate) fn materialization_cache() -> MaterializationCache {
2434 Arc::new(OnceLock::new())
2435}
2436
2437pub(crate) fn pipeline_shape_cache() -> PipelineShapeCache {
2438 Arc::new(OnceLock::new())
2439}
2440
2441pub(crate) fn pipeline_mode_cache() -> PipelineModeCache {
2442 Arc::new(OnceLock::new())
2443}
2444
2445#[cfg(feature = "gpu")]
2446pub(crate) struct GpuPendingGraph<'a> {
2447 pub(crate) source: &'a Image,
2448 pub(crate) cached: Option<Arc<DynamicImage>>,
2449 pub(crate) width: u32,
2450 pub(crate) height: u32,
2451 pub(crate) mode: String,
2452 pub(crate) encoded_bytes: u64,
2453 pub(crate) ops: Vec<&'a PipelineOp>,
2454}
2455
2456#[cfg(feature = "gpu")]
2457fn gpu_info_bytes(info: &ImageInfo) -> u64 {
2458 let profile_bytes = |profile: &image_slash_star::RawIccProfile| {
2459 (profile.keyword.len() + profile.data.len()) as u64
2460 };
2461 4096 + info
2462 .palette
2463 .as_ref()
2464 .map_or(0, |p| (p.rgb.len() + p.alpha.len()) as u64)
2465 + info.source_color.icc_profile().map_or(0, profile_bytes)
2466 + info
2467 .source
2468 .avif_item_icc_profiles()
2469 .iter()
2470 .map(|p| profile_bytes(p.profile()))
2471 .sum::<u64>()
2472 + std::mem::size_of_val(info.source.avif_item_locations()) as u64
2473 + std::mem::size_of_val(info.source.avif_item_properties()) as u64
2474 + std::mem::size_of_val(info.source.avif_item_plane_properties()) as u64
2475 + std::mem::size_of_val(info.source.avif_item_codec_properties()) as u64
2476 + std::mem::size_of_val(info.source.avif_item_relationships()) as u64
2477 + std::mem::size_of_val(info.source.avif_auxiliary_relationships()) as u64
2478 + std::mem::size_of_val(info.source.avif_premultiplied_relationships()) as u64
2479 + std::mem::size_of_val(info.source.avif_item_color_properties()) as u64
2480 + std::mem::size_of_val(info.source.avif_grid_item_ids()) as u64
2481}
2482
2483impl Image {
2484 #[cfg(feature = "gpu")]
2486 pub(crate) fn gpu_pending_graph(&self) -> Result<GpuPendingGraph<'_>, PilError> {
2487 self.gpu_pending_graph_depth(0)
2488 }
2489
2490 #[cfg(feature = "gpu")]
2491 fn gpu_pending_graph_depth(&self, depth: usize) -> Result<GpuPendingGraph<'_>, PilError> {
2492 if depth > 64 {
2493 return Err(PilError::ValueError(
2494 "GPU graph exceeds 64 source levels".into(),
2495 ));
2496 }
2497 match self {
2498 Self::Pipeline {
2499 source,
2500 ops,
2501 materialized,
2502 backend,
2503 explicit_mode,
2504 palette,
2505 mode,
2506 ..
2507 } => {
2508 if backend.is_some_and(|backend| backend != crate::Backend::Gpu) {
2509 return Err(PilError::ValueError(
2510 "GPU batch graph is locked to another backend".into(),
2511 ));
2512 }
2513 if palette.is_some() || matches!(explicit_mode.as_deref(), Some("P" | "PA")) {
2514 return Err(PilError::ValueError(
2515 "GPU graph palette boundary is not yet represented by a native plan".into(),
2516 ));
2517 }
2518 if let Some(pixels) = materialized.get() {
2519 let pixels = pixels.clone()?;
2520 let pixel_mode = explicit_mode
2521 .clone()
2522 .or_else(|| {
2523 mode.get()
2524 .and_then(|m| m.as_ref().ok().and_then(|m| m.clone()))
2525 })
2526 .unwrap_or_else(|| image_mode_name(pixels.color().into()).to_owned());
2527 return Ok(GpuPendingGraph {
2528 source: self,
2529 width: pixels.width(),
2530 height: pixels.height(),
2531 mode: pixel_mode,
2532 cached: Some(pixels),
2533 encoded_bytes: 0,
2534 ops: Vec::new(),
2535 });
2536 }
2537 let (mut graph, skip) = if let Some(prefix) = ops.prefix_cache()
2538 && let Some(pixels) = prefix.materialized.get()
2539 {
2540 let pixels = pixels.clone()?;
2541 let pixel_mode = explicit_mode
2542 .clone()
2543 .unwrap_or_else(|| image_mode_name(pixels.color().into()).to_owned());
2544 (
2545 GpuPendingGraph {
2546 source: self,
2547 width: pixels.width(),
2548 height: pixels.height(),
2549 mode: pixel_mode,
2550 cached: Some(pixels),
2551 encoded_bytes: 0,
2552 ops: Vec::new(),
2553 },
2554 prefix.ops_len,
2555 )
2556 } else {
2557 (source.gpu_pending_graph_depth(depth + 1)?, 0)
2558 };
2559 if graph
2560 .ops
2561 .len()
2562 .saturating_add(ops.len().saturating_sub(skip))
2563 > 256
2564 {
2565 return Err(PilError::ValueError(
2566 "GPU batch graph exceeds 256 pending operations".into(),
2567 ));
2568 }
2569 graph.ops.extend(ops.as_slice()[skip..].iter());
2570 Ok(graph)
2571 }
2572 Self::Loaded(data) => Ok(GpuPendingGraph {
2573 source: self,
2574 cached: Some(data.image.clone()),
2575 width: data.image.width(),
2576 height: data.image.height(),
2577 mode: data
2578 .explicit_mode
2579 .clone()
2580 .unwrap_or_else(|| image_mode_name(data.decoded_mode).to_owned()),
2581 encoded_bytes: 0,
2582 ops: Vec::new(),
2583 }),
2584 Self::Bytes {
2585 source,
2586 info: Some(info),
2587 materialized,
2588 ..
2589 } => Ok(GpuPendingGraph {
2590 source: self,
2591 cached: materialized.get().map(|image| image.clone()).transpose()?,
2592 width: info.width,
2593 height: info.height,
2594 mode: image_mode_name(info.mode).to_owned(),
2595 encoded_bytes: source.bytes().len() as u64,
2596 ops: Vec::new(),
2597 }),
2598 _ => Err(PilError::ValueError(
2599 "GPU source has no proven native byte header/layout".into(),
2600 )),
2601 }
2602 }
2603
2604 #[cfg(feature = "gpu")]
2606 pub(crate) fn gpu_metadata_bytes(&self) -> u64 {
2607 let mut leaf = self;
2608 while let Self::Pipeline { source, .. } = leaf {
2609 leaf = source;
2610 }
2611 let (info, exif) = match leaf {
2612 Self::Pipeline { .. } => unreachable!(),
2613 Self::Loaded(data) => (data.info.as_ref(), data.exif.as_ref()),
2614 Self::Paletted(data) => (data.info.as_ref(), data.exif.as_ref()),
2615 Self::Bytes { source, info, .. } => {
2616 return (source.bytes().len() as u64)
2617 .saturating_mul(16)
2618 .saturating_add(info.as_ref().map_or(0, gpu_info_bytes));
2619 }
2620 };
2621 4096 + exif.map_or(0, |bytes| bytes.len() as u64) + info.map_or(0, gpu_info_bytes)
2622 }
2623
2624 #[cfg(feature = "gpu")]
2626 pub(crate) fn gpu_result_metadata(&self) -> GpuResultMetadata {
2627 GpuResultMetadata {
2628 info: self.image_info(),
2629 exif: self.exif_metadata(),
2630 format: match self {
2631 Self::Pipeline { format, .. } | Self::Bytes { format, .. } => *format,
2632 Self::Loaded(source) => source.source_format,
2633 Self::Paletted(source) => source.source_format,
2634 },
2635 }
2636 }
2637
2638 pub(crate) fn shares_execution_source(&self, other: &Self) -> bool {
2647 match (self, other) {
2648 (Self::Loaded(left), Self::Loaded(right)) => Arc::ptr_eq(&left.image, &right.image),
2649 (Self::Paletted(left), Self::Paletted(right)) => {
2650 Arc::ptr_eq(&left.materialized, &right.materialized)
2651 }
2652 (
2653 Self::Bytes {
2654 materialized: left, ..
2655 },
2656 Self::Bytes {
2657 materialized: right,
2658 ..
2659 },
2660 )
2661 | (
2662 Self::Pipeline {
2663 materialized: left, ..
2664 },
2665 Self::Pipeline {
2666 materialized: right,
2667 ..
2668 },
2669 ) => Arc::ptr_eq(left, right),
2670 _ => false,
2671 }
2672 }
2673}
2674
2675#[derive(Debug, Clone)]
2677pub struct StatResult {
2678 pub count: StatValue,
2680 pub sum: StatValue,
2682 pub sum2: StatValue,
2684 pub mean: StatValue,
2686 pub median: StatValue,
2688 pub rms: StatValue,
2690 pub var: StatValue,
2692 pub stddev: StatValue,
2694 pub extrema: StatValue,
2696}
2697
2698#[derive(Debug, Clone)]
2700pub enum StatValue {
2701 Int(i64),
2703 Float(f64),
2705 IntList(Vec<i64>),
2707 FloatList(Vec<f64>),
2709 ExtremaSingle((i64, i64)),
2711 ExtremaList(Vec<(i64, i64)>),
2713}
2714
2715impl StatResult {
2716 fn from_bands(bands: &[Vec<f64>]) -> Self {
2717 let fi = |idx: usize| -> StatValue {
2718 StatValue::IntList(bands.iter().map(|b| b[idx] as i64).collect())
2719 };
2720 let ff = |idx: usize| -> StatValue {
2721 StatValue::FloatList(bands.iter().map(|b| b[idx]).collect())
2722 };
2723 let extrema = |min_idx, max_idx| -> StatValue {
2724 StatValue::ExtremaList(
2726 bands
2727 .iter()
2728 .map(|b| (b[min_idx] as i64, b[max_idx] as i64))
2729 .collect(),
2730 )
2731 };
2732 StatResult {
2733 count: fi(0),
2734 sum: ff(1),
2735 sum2: ff(2),
2736 mean: ff(3),
2737 median: fi(4),
2738 rms: ff(5),
2739 var: ff(6),
2740 stddev: ff(7),
2741 extrema: extrema(8, 9),
2742 }
2743 }
2744}
2745
2746impl Image {
2747 pub(crate) fn from_dynamic(image: DynamicImage, explicit_mode: Option<String>) -> Self {
2749 let decoded_mode = image.color().into();
2750 Self::Loaded(LoadedData {
2751 image: Arc::new(image),
2752 known_zero_fill: false,
2753 explicit_mode,
2754 decoded_mode,
2755 palette: None,
2756 palette_alpha: None,
2757 source_format: None,
2758 info: None,
2759 exif: None,
2760 })
2761 }
2762
2763 pub(crate) fn from_generated_dynamic(image: DynamicImage, mode: &str) -> Self {
2769 if mode == "P" {
2770 let indices = match image {
2771 DynamicImage::ImageLuma8(indices) => indices,
2772 other => other.to_luma8(),
2773 };
2774 return Self::Paletted(PalettedData {
2775 indices,
2776 palette: Vec::new(),
2777 palette_alpha: Vec::new(),
2778 source_format: None,
2779 info: None,
2780 exif: None,
2781 materialized: materialization_cache(),
2782 });
2783 }
2784 let explicit_mode = matches!(mode, "1" | "I" | "F").then(|| mode.to_owned());
2785 Self::from_dynamic(image, explicit_mode)
2786 }
2787
2788 pub fn from_luma_mask(width: u32, height: u32, pixels: Vec<u8>) -> Result<Self, PilError> {
2794 let expected = (width as usize)
2795 .checked_mul(height as usize)
2796 .ok_or_else(|| PilError::ValueError("mask dimensions overflow".into()))?;
2797 if pixels.len() != expected {
2798 return Err(PilError::ValueError(format!(
2799 "mask byte length mismatch: expected {expected}, got {}",
2800 pixels.len()
2801 )));
2802 }
2803 let image = crate::raster::GrayImage::from_raw(width, height, pixels)
2804 .ok_or_else(|| PilError::InternalError("failed to construct L mask".into()))?;
2805 Ok(Self::from_dynamic(DynamicImage::ImageLuma8(image), None))
2806 }
2807
2808 #[allow(clippy::too_many_arguments)]
2811 pub fn new(
2818 width: u32,
2819 height: u32,
2820 mode: &str,
2821 color: (u8, u8, u8, u8),
2822 ) -> Result<Self, PilError> {
2823 let img = match mode {
2824 "RGB" => DynamicImage::ImageRgb8(crate::raster::RgbImage::from_pixel(
2825 width,
2826 height,
2827 crate::raster::Rgb([color.0, color.1, color.2]),
2828 )),
2829 "RGBA" | "RGBa" | "RGBX" => {
2833 DynamicImage::ImageRgba8(crate::raster::RgbaImage::from_pixel(
2834 width,
2835 height,
2836 crate::raster::Rgba([color.0, color.1, color.2, color.3]),
2837 ))
2838 }
2839 "L" => DynamicImage::ImageLuma8(crate::raster::GrayImage::from_pixel(
2840 width,
2841 height,
2842 crate::raster::Luma([color.0]),
2843 )),
2844 "LA" | "La" => DynamicImage::ImageLumaA8(crate::raster::GrayAlphaImage::from_pixel(
2845 width,
2846 height,
2847 crate::raster::LumaA([color.0, color.3]),
2848 )),
2849 "I;16" | "I;16L" | "I;16B" | "I;16N" => {
2854 DynamicImage::ImageLuma16(crate::raster::ImageBuffer::from_pixel(
2855 width,
2856 height,
2857 crate::raster::Luma([u16::from_le_bytes([color.0, color.1])]),
2858 ))
2859 }
2860 "PA" => DynamicImage::ImageLumaA8(crate::raster::GrayAlphaImage::from_pixel(
2861 width,
2862 height,
2863 crate::raster::LumaA([color.0, color.3]),
2864 )),
2865 "1" => DynamicImage::ImageLuma8(crate::raster::GrayImage::from_pixel(
2866 width,
2867 height,
2868 crate::raster::Luma([color.0]),
2871 )),
2872 "P" => {
2876 return Ok(Image::Paletted(PalettedData {
2877 indices: crate::raster::GrayImage::from_pixel(
2878 width,
2879 height,
2880 crate::raster::Luma([0u8]),
2881 ),
2882 palette: vec![color.0, color.1, color.2],
2886 palette_alpha: Vec::new(),
2887 source_format: None,
2888 info: None,
2889 exif: None,
2890 materialized: materialization_cache(),
2891 }));
2892 }
2893 "CMYK" => DynamicImage::ImageRgba8(crate::raster::RgbaImage::from_pixel(
2894 width,
2895 height,
2896 crate::raster::Rgba([color.0, color.1, color.2, color.3]),
2897 )),
2898 "YCbCr" | "HSV" => DynamicImage::ImageRgb8(crate::raster::RgbImage::from_pixel(
2901 width,
2902 height,
2903 crate::raster::Rgb([color.0, color.1, color.2]),
2904 )),
2905 "LAB" => DynamicImage::ImageRgb8(crate::raster::RgbImage::from_pixel(
2908 width,
2909 height,
2910 crate::raster::Rgb([
2911 color.0,
2912 color.1.wrapping_add(128),
2913 color.2.wrapping_add(128),
2914 ]),
2915 )),
2916 "I" | "F" => DynamicImage::ImageRgba8(crate::raster::RgbaImage::from_pixel(
2918 width,
2919 height,
2920 crate::raster::Rgba([color.0, color.1, color.2, color.3]),
2921 )),
2922 _ => return Err(PilError::ValueError("unrecognized image mode".into())),
2923 };
2924 crate::compute::record_pipeline_allocation(img.as_bytes().len());
2925 let explicit = if matches!(
2926 mode,
2927 "CMYK"
2928 | "YCbCr"
2929 | "LAB"
2930 | "HSV"
2931 | "I"
2932 | "F"
2933 | "RGBa"
2934 | "La"
2935 | "RGBX"
2936 | "PA"
2937 | "1"
2938 | "I;16"
2939 | "I;16L"
2940 | "I;16B"
2941 | "I;16N"
2942 ) {
2943 Some(mode.to_string())
2944 } else {
2945 None
2946 };
2947 let known_zero_fill = match mode {
2948 "RGB" => color.0 == 0 && color.1 == 0 && color.2 == 0,
2949 "CMYK" => color == (0, 0, 0, 0),
2950 _ => false,
2951 };
2952 let mut image = Image::from_dynamic(img, explicit);
2953 if known_zero_fill {
2954 let Image::Loaded(data) = &mut image else {
2955 unreachable!("RGB and CMYK constructors produce loaded images")
2956 };
2957 data.known_zero_fill = true;
2958 }
2959 Ok(image)
2960 }
2961
2962 pub fn new_with_input(
2968 width: u32,
2969 height: u32,
2970 mode: &str,
2971 input: PythonNewColorInput,
2972 ) -> Result<Self, PilError> {
2973 let color = crate::color::resolve_new_color(
2974 mode,
2975 input.string.as_deref(),
2976 input.single,
2977 input.rgb,
2978 input.rgba,
2979 input.luma_alpha,
2980 input.integer,
2981 input.float,
2982 )?;
2983 if mode == "P" {
2984 if let Some(index) = input.single {
2985 return Ok(Self::new_palette_index(width, height, index));
2986 }
2987 if !input.provided {
2988 return Ok(Self::new_palette_index(width, height, 0));
2989 }
2990 let tuple_color = if let Some((r, g, b, a)) = input.rgba {
2991 if a != 255 {
2992 return Err(PilError::ValueError(
2993 "cannot add non-opaque RGBA color to RGB palette".to_owned(),
2994 ));
2995 }
2996 (r, g, b, a)
2997 } else if let Some((r, g, b)) = input.rgb {
2998 (r, g, b, 255)
2999 } else {
3000 color
3001 };
3002 return Self::new(width, height, mode, tuple_color);
3003 }
3004 Self::new(width, height, mode, color)
3005 }
3006
3007 pub fn new_palette_index(width: u32, height: u32, index: u8) -> Self {
3013 Image::Paletted(PalettedData {
3014 indices: crate::raster::GrayImage::from_pixel(
3015 width,
3016 height,
3017 crate::raster::Luma([index]),
3018 ),
3019 palette: Vec::new(),
3020 palette_alpha: Vec::new(),
3021 source_format: None,
3022 info: None,
3023 exif: None,
3024 materialized: materialization_cache(),
3025 })
3026 }
3027
3028 pub fn frombytes(mode: &str, size: (u32, u32), data: &[u8]) -> Result<Self, PilError> {
3047 Self::frombytes_with_data(mode, size, Cow::Borrowed(data))
3048 }
3049
3050 pub(crate) fn frombytes_owned(
3053 mode: &str,
3054 size: (u32, u32),
3055 data: Vec<u8>,
3056 ) -> Result<Self, PilError> {
3057 Self::frombytes_with_data(mode, size, Cow::Owned(data))
3058 }
3059
3060 fn frombytes_with_data(
3061 mode: &str,
3062 size: (u32, u32),
3063 data: Cow<'_, [u8]>,
3064 ) -> Result<Self, PilError> {
3065 let (w, h) = size;
3066 let frombytes_mode = match mode {
3067 "L" => FromBytesMode::L,
3068 "LA" | "La" | "PA" => FromBytesMode::LA,
3071 "I;16" | "I;16L" | "I;16B" | "I;16N" => FromBytesMode::L16,
3072 "RGB" => FromBytesMode::RGB,
3073 "LAB" => FromBytesMode::LAB,
3074 "RGBA" | "RGBa" | "RGBX" => FromBytesMode::RGBA,
3075 "CMYK" => FromBytesMode::CMYK,
3076 "HSV" => FromBytesMode::HSV,
3077 "YCbCr" => FromBytesMode::YCbCr,
3078 "I" => FromBytesMode::I,
3079 "F" => FromBytesMode::F,
3080 "P" => FromBytesMode::P,
3081 "1" => FromBytesMode::Mode1,
3082 _ => return Err(PilError::ValueError("unrecognized image mode".into())),
3083 };
3084 if w == 0 || h == 0 {
3085 if matches!(frombytes_mode, FromBytesMode::P) {
3090 return Ok(Image::Paletted(PalettedData {
3091 indices: crate::raster::GrayImage::from_pixel(w, h, crate::raster::Luma([0u8])),
3092 palette: Vec::new(),
3093 palette_alpha: Vec::new(),
3094 source_format: None,
3095 info: None,
3096 exif: None,
3097 materialized: materialization_cache(),
3098 }));
3099 }
3100 if matches!(frombytes_mode, FromBytesMode::L16) {
3101 return Ok(Self::from_dynamic(
3102 DynamicImage::ImageLuma16(crate::raster::ImageBuffer::from_pixel(
3103 w,
3104 h,
3105 crate::raster::Luma([0u16]),
3106 )),
3107 Some(mode.to_owned()),
3108 ));
3109 }
3110 return Self::new(w, h, mode, (0, 0, 0, 0));
3111 }
3112 let channels = match frombytes_mode {
3117 FromBytesMode::L | FromBytesMode::P | FromBytesMode::Mode1 => 1,
3118 FromBytesMode::LA | FromBytesMode::L16 => 2,
3119 FromBytesMode::RGB | FromBytesMode::LAB | FromBytesMode::HSV | FromBytesMode::YCbCr => {
3120 3
3121 }
3122 FromBytesMode::RGBA | FromBytesMode::CMYK | FromBytesMode::I | FromBytesMode::F => 4,
3123 };
3124 let expected = if matches!(frombytes_mode, FromBytesMode::Mode1) {
3125 (w as usize)
3126 .div_ceil(8)
3127 .checked_mul(h as usize)
3128 .ok_or_else(|| PilError::DimensionError("image buffer size overflow".into()))?
3129 } else {
3130 (w as usize)
3131 .checked_mul(h as usize)
3132 .and_then(|pixels| pixels.checked_mul(channels))
3133 .ok_or_else(|| PilError::DimensionError("image buffer size overflow".into()))?
3134 };
3135 if data.len() < expected {
3136 return Err(PilError::ValueError("not enough image data".into()));
3137 }
3138 let _dimensions = CheckedDims::new(w, h, channels as u8)?;
3141 let data = match data {
3142 Cow::Borrowed(data) => Cow::Borrowed(&data[..expected]),
3143 Cow::Owned(data) => {
3144 if data.len() == expected {
3145 Cow::Owned(data)
3146 } else {
3147 Cow::Owned(data[..expected].to_vec())
3148 }
3149 }
3150 };
3151 let img = match frombytes_mode {
3152 FromBytesMode::L => DynamicImage::ImageLuma8(
3153 crate::raster::GrayImage::from_raw(w, h, data.into_owned())
3154 .ok_or_else(|| PilError::ValueError("frombytes: buffer error".into()))?,
3155 ),
3156 FromBytesMode::L16 => {
3157 let pixels = data
3158 .chunks_exact(2)
3159 .map(|sample| {
3160 if l16_uses_big_endian(mode) {
3161 u16::from_be_bytes([sample[0], sample[1]])
3162 } else {
3163 u16::from_le_bytes([sample[0], sample[1]])
3164 }
3165 })
3166 .collect();
3167 DynamicImage::ImageLuma16(
3168 crate::raster::ImageBuffer::from_raw(w, h, pixels)
3169 .ok_or_else(|| PilError::ValueError("frombytes: buffer error".into()))?,
3170 )
3171 }
3172 FromBytesMode::RGB => DynamicImage::ImageRgb8(
3173 crate::raster::RgbImage::from_raw(w, h, data.into_owned())
3174 .ok_or_else(|| PilError::ValueError("frombytes: buffer error".into()))?,
3175 ),
3176 FromBytesMode::RGBA => DynamicImage::ImageRgba8(
3177 crate::raster::RgbaImage::from_raw(w, h, data.into_owned())
3178 .ok_or_else(|| PilError::ValueError("frombytes: buffer error".into()))?,
3179 ),
3180 FromBytesMode::LA => DynamicImage::ImageLumaA8(
3181 crate::raster::GrayAlphaImage::from_raw(w, h, data.into_owned())
3182 .ok_or_else(|| PilError::ValueError("frombytes: buffer error".into()))?,
3183 ),
3184 FromBytesMode::P => {
3185 return Ok(Image::Paletted(PalettedData {
3186 indices: crate::raster::GrayImage::from_raw(w, h, data.into_owned())
3187 .ok_or_else(|| PilError::ValueError("frombytes: buffer error".into()))?,
3188 palette: Vec::new(),
3191 palette_alpha: Vec::new(),
3192 source_format: None,
3193 info: None,
3194 exif: None,
3195 materialized: materialization_cache(),
3196 }));
3197 }
3198 FromBytesMode::CMYK | FromBytesMode::I | FromBytesMode::F => DynamicImage::ImageRgba8(
3199 crate::raster::RgbaImage::from_raw(w, h, data.into_owned())
3200 .ok_or_else(|| PilError::ValueError("frombytes: buffer error".into()))?,
3201 ),
3202 FromBytesMode::LAB | FromBytesMode::HSV | FromBytesMode::YCbCr => {
3203 DynamicImage::ImageRgb8(
3204 crate::raster::RgbImage::from_raw(w, h, data.into_owned())
3205 .ok_or_else(|| PilError::ValueError("frombytes: buffer error".into()))?,
3206 )
3207 }
3208 FromBytesMode::Mode1 => {
3209 let mut pixels = CheckedDims::new(w, h, 1)?.alloc_buffer();
3210 unpack_mode1_rows(data.as_ref(), w as usize, &mut pixels);
3211 DynamicImage::ImageLuma8(
3212 crate::raster::GrayImage::from_raw(w, h, pixels)
3213 .ok_or_else(|| PilError::ValueError("frombytes: buffer error".into()))?,
3214 )
3215 }
3216 };
3217 let explicit_mode = match frombytes_mode {
3218 FromBytesMode::Mode1
3219 | FromBytesMode::CMYK
3220 | FromBytesMode::LAB
3221 | FromBytesMode::HSV
3222 | FromBytesMode::YCbCr
3223 | FromBytesMode::I
3224 | FromBytesMode::F => Some(mode.to_string()),
3225 FromBytesMode::RGBA if matches!(mode, "RGBa" | "RGBX") => Some(mode.to_string()),
3226 FromBytesMode::LA if matches!(mode, "La" | "PA") => Some(mode.to_string()),
3227 FromBytesMode::L16 => Some(mode.to_string()),
3228 FromBytesMode::L
3229 | FromBytesMode::LA
3230 | FromBytesMode::RGB
3231 | FromBytesMode::RGBA
3232 | FromBytesMode::P => None,
3233 };
3234 Ok(Image::from_dynamic(img, explicit_mode))
3235 }
3236
3237 pub fn open_bytes_with_format(data: Vec<u8>, format: Option<&str>) -> Result<Self, PilError> {
3245 let formats = format.map(|format| vec![format]);
3246 Self::open_bytes_with_formats(data, formats.as_deref())
3247 }
3248
3249 pub fn open_bytes_with_formats(
3260 data: Vec<u8>,
3261 formats: Option<&[&str]>,
3262 ) -> Result<Self, PilError> {
3263 let requested = formats
3264 .map(|formats| {
3265 formats
3266 .iter()
3267 .map(|format| parse_format_str(format))
3268 .collect::<Result<Vec<_>, _>>()
3269 })
3270 .transpose()?;
3271 let data: Arc<[u8]> = data.into();
3272 let source = EncodedImage::new(Arc::clone(&data))
3276 .map_err(|_| PilError::UnidentifiedImageError("memory".to_owned()))?;
3277 let info = source.info().clone();
3278 if requested
3279 .as_ref()
3280 .is_some_and(|requested| !requested.contains(&info.format))
3281 {
3282 return Err(PilError::UnidentifiedImageError("memory".to_owned()));
3283 }
3284 Ok(Image::Bytes {
3285 source,
3286 format: Some(info.format),
3287 info: Some(info),
3288 materialized: materialization_cache(),
3289 })
3290 }
3291
3292 pub fn open_bytes(data: Vec<u8>) -> Result<Self, PilError> {
3301 Self::open_bytes_with_format(data, None)
3302 }
3303
3304 fn is_palette_safe_op(op: &PipelineOp) -> bool {
3313 match op {
3314 PipelineOp::Duplicate
3318 | PipelineOp::Crop { .. }
3319 | PipelineOp::Reduce { .. }
3320 | PipelineOp::Transpose { .. }
3321 | PipelineOp::Flip
3322 | PipelineOp::Mirror
3323 | PipelineOp::CropBorder { .. }
3324 | PipelineOp::Offset { .. }
3325 | PipelineOp::Paste { .. }
3326 | PipelineOp::EffectSpread { .. }
3329 | PipelineOp::DrawLine { .. }
3330 | PipelineOp::DrawRectangle { .. }
3331 | PipelineOp::DrawRoundedRect { .. }
3332 | PipelineOp::DrawEllipse { .. }
3333 | PipelineOp::DrawCircle { .. }
3334 | PipelineOp::DrawPolygon { .. }
3335 | PipelineOp::DrawArc { .. }
3336 | PipelineOp::DrawChord { .. }
3337 | PipelineOp::DrawPieslice { .. }
3338 | PipelineOp::DrawPoint { .. }
3339 | PipelineOp::InvertChops
3342 | PipelineOp::Add { .. }
3346 | PipelineOp::Subtract { .. }
3347 | PipelineOp::Multiply { .. }
3348 | PipelineOp::Screen { .. }
3349 | PipelineOp::Darker { .. }
3350 | PipelineOp::Lighter { .. }
3351 | PipelineOp::Difference { .. }
3352 | PipelineOp::Overlay { .. }
3353 | PipelineOp::HardLight { .. }
3354 | PipelineOp::SoftLight { .. }
3355 | PipelineOp::AddModulo { .. }
3356 | PipelineOp::SubtractModulo { .. }
3357 | PipelineOp::Expand { .. }
3361 | PipelineOp::Merge { .. }
3365 | PipelineOp::RemapPalette { .. }
3368 | PipelineOp::Eval { .. }
3371 | PipelineOp::PutData {
3374 mode: crate::pipeline::PixelMode::P | crate::pipeline::PixelMode::PA,
3375 ..
3376 }
3377 | PipelineOp::PutAlpha {
3378 mode: crate::pipeline::PixelMode::P | crate::pipeline::PixelMode::PA,
3379 ..
3380 } => true,
3381 PipelineOp::PutAlphaData {
3382 mode: crate::pipeline::PixelMode::P | crate::pipeline::PixelMode::PA,
3383 ..
3384 } => true,
3385 PipelineOp::Pad { .. } => true,
3389 PipelineOp::Scale { .. } => true,
3394 PipelineOp::ExtractBand { .. } => true,
3398 PipelineOp::CompositeModule { other, .. } => {
3399 other.has_palette_mode() || other.explicit_mode() == Some("PA")
3404 }
3405 PipelineOp::PutPixel {
3406 palette_index: true,
3407 ..
3408 } => true,
3409 PipelineOp::Rotate { fill: None, .. } => true,
3410 PipelineOp::Resize { filter, .. } | PipelineOp::ResizeBoxed { filter, .. } => {
3411 matches!(filter, ResampleFilter::Nearest)
3412 }
3413 PipelineOp::Thumbnail { filter, .. } => {
3414 matches!(filter, ResampleFilter::Nearest)
3415 }
3416 PipelineOp::Transform {
3417 method: TransformMethod::Affine,
3418 filter: ResampleFilter::Nearest,
3419 palette_fill,
3420 ..
3421 } => palette_fill.is_some(),
3422 _ => false,
3423 }
3424 }
3425
3426 fn indexed_chops_result_without_palette(op: &PipelineOp) -> bool {
3433 matches!(
3434 op,
3435 PipelineOp::InvertChops
3436 | PipelineOp::Add { .. }
3437 | PipelineOp::Subtract { .. }
3438 | PipelineOp::Multiply { .. }
3439 | PipelineOp::Screen { .. }
3440 | PipelineOp::Darker { .. }
3441 | PipelineOp::Lighter { .. }
3442 | PipelineOp::Difference { .. }
3443 | PipelineOp::Overlay { .. }
3444 | PipelineOp::HardLight { .. }
3445 | PipelineOp::SoftLight { .. }
3446 | PipelineOp::AddModulo { .. }
3447 | PipelineOp::SubtractModulo { .. }
3448 )
3449 }
3450
3451 fn is_palette_safe_op_for_source(source: &Image, op: &PipelineOp) -> bool {
3459 Self::is_palette_safe_op(op)
3460 || (source.explicit_mode() == Some("PA")
3465 && matches!(op, PipelineOp::PutPixel { .. }))
3466 || (source.explicit_mode() == Some("PA")
3469 && matches!(op, PipelineOp::Resize { .. } | PipelineOp::ResizeBoxed { .. }))
3470 || (source.explicit_mode() == Some("PA")
3471 && matches!(
3472 op,
3473 PipelineOp::Filter3x3 { .. } | PipelineOp::Filter5x5 { .. }
3474 ))
3475 || (source.explicit_mode() == Some("PA")
3483 && matches!(op, PipelineOp::Rotate { .. }))
3484 || (source.explicit_mode() == Some("P")
3488 && matches!(op, PipelineOp::Rotate { .. }))
3489 || (matches!(source.explicit_mode(), Some("P") | Some("PA"))
3494 && matches!(op, PipelineOp::Transform { .. }))
3495 || (matches!(source.explicit_mode(), Some("P") | Some("PA"))
3499 && matches!(op, PipelineOp::Fit { .. }))
3500 || (matches!(source.explicit_mode(), Some("P") | Some("PA"))
3505 && matches!(op, PipelineOp::Contain { .. } | PipelineOp::Cover { .. }))
3506 }
3507
3508 pub(crate) fn has_palette_mode(&self) -> bool {
3512 match self {
3513 Image::Paletted(_) => true,
3514 Image::Bytes {
3515 info: Some(info), ..
3516 } => info.mode == ImageMode::P8,
3517 Image::Pipeline {
3518 explicit_mode: Some(mode),
3519 ..
3520 }
3521 | Image::Loaded(LoadedData {
3522 explicit_mode: Some(mode),
3523 ..
3524 }) => mode == "P",
3525 _ => false,
3526 }
3527 }
3528
3529 fn has_palette_samples(&self) -> bool {
3536 self.has_palette_mode() || self.explicit_mode() == Some("PA")
3537 }
3538
3539 pub fn materialize(&self) -> Result<DynamicImage, PilError> {
3546 let image = self.materialized_shared_for_ops()?;
3547 Ok(image.as_ref().clone())
3548 }
3549
3550 pub(crate) fn materialized_shared_for_ops(&self) -> Result<Arc<DynamicImage>, PilError> {
3553 let image = self.materialized_shared()?;
3554 let mode = self.mode_from_materialized(&image);
3555 validate_scalar_storage(&image, &mode)?;
3556 Ok(image)
3557 }
3558
3559 pub(crate) fn materialized_branch(&self) -> Result<Image, PilError> {
3566 match self {
3567 Image::Bytes { format, info, .. } => {
3568 let image = self.materialized_shared()?;
3572 image_from_materialized(image, *format, info.clone(), self.exif_metadata())
3573 }
3574 Image::Pipeline { .. } => {
3575 let image = self.materialized_shared()?;
3576 Ok(Image::Loaded(LoadedData {
3577 decoded_mode: image.color().into(),
3578 known_zero_fill: false,
3579 explicit_mode: self.explicit_mode().map(str::to_owned),
3580 palette: self.palette(),
3581 palette_alpha: self.palette_alpha(),
3582 source_format: None,
3583 info: self.image_info(),
3586 exif: self.exif_metadata(),
3587 image,
3588 }))
3589 }
3590 _ => Ok(self.clone()),
3591 }
3592 }
3593
3594 pub(crate) fn materialized_shared(&self) -> Result<Arc<DynamicImage>, PilError> {
3597 match self {
3598 Image::Loaded(data) => Ok(Arc::clone(&data.image)),
3599 Image::Paletted(data) => data
3600 .materialized
3601 .get_or_init(|| Ok(Arc::new(DynamicImage::ImageLuma8(data.indices.clone()))))
3602 .clone(),
3603 Image::Bytes {
3604 source,
3605 materialized,
3606 ..
3607 } => materialized
3608 .get_or_init(|| {
3609 decoded_to_dynamic(source.decode().map_err(map_deferred_decode_error)?)
3610 .map(Arc::new)
3611 })
3612 .clone(),
3613 Image::Pipeline {
3614 source,
3615 ops,
3616 explicit_mode,
3617 backend,
3618 palette,
3619 palette_alpha,
3620 materialized,
3621 ..
3622 } => materialized
3623 .get_or_init(|| {
3624 Self::evaluate_pipeline(
3625 source,
3626 ops.as_slice(),
3627 explicit_mode,
3628 *backend,
3629 palette,
3630 palette_alpha,
3631 ops.prefix_cache(),
3632 )
3633 })
3634 .clone(),
3635 }
3636 }
3637
3638 pub(crate) fn materialize_owned(self) -> Result<DynamicImage, PilError> {
3641 let shared = self.materialized_shared_for_ops()?;
3642 drop(shared);
3643 let cached = match self {
3644 Image::Loaded(data) => Ok(data.image),
3645 Image::Paletted(data) => take_cached_materialization(data.materialized),
3646 Image::Bytes { materialized, .. } | Image::Pipeline { materialized, .. } => {
3647 take_cached_materialization(materialized)
3648 }
3649 }?;
3650 Ok(Arc::try_unwrap(cached).unwrap_or_else(|shared| shared.as_ref().clone()))
3651 }
3652
3653 fn evaluate_pipeline(
3656 source: &Image,
3657 ops: &[PipelineOp],
3658 explicit_mode: &Option<String>,
3659 backend: Option<crate::compute::Backend>,
3660 palette: &Option<Vec<u8>>,
3661 palette_alpha: &Option<Vec<u8>>,
3662 prefix_cache: Option<&PipelinePrefixCache>,
3663 ) -> Result<Arc<DynamicImage>, PilError> {
3664 if let Some(prefix_cache) =
3665 prefix_cache.filter(|cache| cache.ops_len > 0 && cache.ops_len < ops.len())
3666 {
3667 let prefix_ops = &ops[..prefix_cache.ops_len];
3668 let prefix_image = prefix_cache
3669 .materialized
3670 .get_or_init(|| {
3671 let prepared = crate::compute::prepare_execution(prefix_ops, backend)?;
3672 let source_image = source.materialized_shared()?;
3673 Self::evaluate_pipeline_with_image(
3674 source,
3675 source_image.as_ref(),
3676 &source_image,
3677 prefix_ops,
3678 explicit_mode,
3679 &prepared,
3680 &None,
3681 &None,
3682 )
3683 })
3684 .clone()?;
3685 let suffix_ops = &ops[prefix_cache.ops_len..];
3686 let prepared = crate::compute::prepare_execution(suffix_ops, backend)?;
3687 return crate::compute::execute_prepared_shared(
3688 &prepared,
3689 suffix_ops,
3690 &prefix_image,
3691 explicit_mode.as_deref(),
3692 );
3693 }
3694 let prepared = crate::compute::prepare_execution(ops, backend)?;
3695 let source_image = source.materialized_shared()?;
3696 Self::evaluate_pipeline_with_image(
3697 source,
3698 source_image.as_ref(),
3699 &source_image,
3700 ops,
3701 explicit_mode,
3702 &prepared,
3703 palette,
3704 palette_alpha,
3705 )
3706 }
3707
3708 fn evaluate_pipeline_uncached(
3709 source: &Image,
3710 ops: &[PipelineOp],
3711 explicit_mode: &Option<String>,
3712 backend: Option<crate::compute::Backend>,
3713 palette: &Option<Vec<u8>>,
3714 palette_alpha: &Option<Vec<u8>>,
3715 ) -> Result<Arc<DynamicImage>, PilError> {
3716 let prepared = crate::compute::prepare_execution(ops, backend)?;
3717 let source_image = Arc::new(source.materialize_uncached()?);
3718 Self::evaluate_pipeline_with_image(
3719 source,
3720 source_image.as_ref(),
3721 &source_image,
3722 ops,
3723 explicit_mode,
3724 &prepared,
3725 palette,
3726 palette_alpha,
3727 )
3728 }
3729
3730 fn evaluate_pipeline_with_image(
3731 source: &Image,
3732 img: &DynamicImage,
3733 shared_img: &Arc<DynamicImage>,
3734 ops: &[PipelineOp],
3735 explicit_mode: &Option<String>,
3736 prepared: &crate::compute::PreparedExecution,
3737 palette: &Option<Vec<u8>>,
3738 palette_alpha: &Option<Vec<u8>>,
3739 ) -> Result<Arc<DynamicImage>, PilError> {
3740 if source.has_palette_samples() {
3741 let all_safe = ops
3742 .iter()
3743 .all(|op| Self::is_palette_safe_op_for_source(source, op));
3744 if all_safe {
3745 let palette_mode = if explicit_mode.as_deref() == Some("PA")
3746 || source.explicit_mode() == Some("PA")
3747 {
3748 "PA"
3749 } else {
3750 "P"
3751 };
3752 let result =
3753 crate::compute::execute_prepared(prepared, ops, img, Some(palette_mode))?;
3754 return Ok(Arc::new(result));
3755 }
3756
3757 let palette_mode = if source.explicit_mode() == Some("PA") {
3758 "PA"
3759 } else {
3760 "P"
3761 };
3762
3763 let palette = palette.clone().or_else(|| source.extract_palette());
3770 if palette_mode == "PA" {
3771 let expanded = expand_palette_alpha(
3772 &img.to_luma_alpha8(),
3773 palette.as_deref().unwrap_or_default(),
3774 );
3775 let result = crate::compute::execute_prepared(
3776 prepared,
3777 ops,
3778 &expanded,
3779 explicit_mode.as_deref(),
3780 )?;
3781 return Ok(Arc::new(result));
3782 }
3783 if let Some(palette) = palette {
3784 let palette_alpha = palette_alpha
3785 .clone()
3786 .or_else(|| source.palette_alpha())
3787 .unwrap_or_default();
3788 let expanded = expand_palette(&img.to_luma8(), &palette, &palette_alpha);
3789 let result = crate::compute::execute_prepared(
3790 prepared,
3791 ops,
3792 &expanded,
3793 explicit_mode.as_deref(),
3794 )?;
3795 return Ok(Arc::new(result));
3796 }
3797 }
3798
3799 let remap_source_mode =
3804 if ops.len() == 1 && matches!(ops.first(), Some(PipelineOp::RemapPalette { .. })) {
3805 Some(source.mode()?)
3806 } else {
3807 None
3808 };
3809 let convert_source_mode =
3814 if ops.len() == 1 && matches!(ops.first(), Some(PipelineOp::Convert { .. })) {
3815 Some(source.mode()?)
3820 } else {
3821 None
3822 };
3823 let source_luma16_mode = if remap_source_mode.is_none()
3829 && convert_source_mode.is_none()
3830 && explicit_mode.is_none()
3831 && matches!(img, DynamicImage::ImageLuma16(_))
3832 {
3833 Some(source.mode()?)
3834 } else {
3835 None
3836 };
3837 let initial_source_mode = if remap_source_mode.is_none()
3844 && convert_source_mode.is_none()
3845 && source_luma16_mode.is_none()
3846 {
3847 Some(source.mode()?)
3848 } else {
3849 None
3850 };
3851 let execution_mode = remap_source_mode
3852 .as_deref()
3853 .or(convert_source_mode.as_deref())
3854 .or(source_luma16_mode.as_deref())
3855 .or(initial_source_mode.as_deref())
3856 .or(explicit_mode.as_deref());
3857 crate::compute::execute_prepared_shared(prepared, ops, shared_img, execution_mode)
3862 }
3863
3864 fn materialize_uncached(&self) -> Result<DynamicImage, PilError> {
3865 match self {
3866 Image::Loaded(data) => Ok(data.image.as_ref().clone()),
3867 Image::Paletted(data) => Ok(DynamicImage::ImageLuma8(data.indices.clone())),
3868 Image::Bytes { source, .. } => decoded_to_dynamic(
3869 &image_slash_star::decode(source.bytes()).map_err(map_deferred_decode_error)?,
3870 ),
3871 Image::Pipeline {
3872 source,
3873 ops,
3874 explicit_mode,
3875 backend,
3876 palette,
3877 palette_alpha,
3878 ..
3879 } => Self::evaluate_pipeline_uncached(
3880 source,
3881 ops,
3882 explicit_mode,
3883 *backend,
3884 palette,
3885 palette_alpha,
3886 )
3887 .map(|image| image.as_ref().clone()),
3888 }
3889 }
3890
3891 pub fn materialize_indices(&self) -> Result<DynamicImage, PilError> {
3901 self.materialize()
3902 }
3903
3904 pub fn push_op(source: &Image, op: PipelineOp) -> Image {
3913 let source_is_paletted = source.has_palette_samples();
3914 let palette_safe = source_is_paletted && Self::is_palette_safe_op_for_source(source, &op);
3915 let indexed_chops_result_without_palette =
3916 source_is_paletted && Self::indexed_chops_result_without_palette(&op);
3917 let putalpha_mode = match &op {
3918 PipelineOp::PutAlpha { mode, .. } | PipelineOp::PutAlphaData { mode, .. } => {
3919 Some(*mode)
3920 }
3921 _ => None,
3922 };
3923 let promotes_p_to_pa = source.has_palette_mode()
3924 && matches!(
3925 &op,
3926 PipelineOp::PutAlpha {
3927 mode: crate::pipeline::PixelMode::P,
3928 ..
3929 } | PipelineOp::PutAlphaData {
3930 mode: crate::pipeline::PixelMode::P,
3931 ..
3932 }
3933 );
3934 let explicit_mode = if matches!(
3935 &op,
3936 PipelineOp::ExtractBand { .. } | PipelineOp::Merge { .. }
3937 ) {
3938 None
3939 } else if source_is_paletted {
3940 if source.explicit_mode() == Some("PA") && matches!(&op, PipelineOp::PutPixel { .. }) {
3941 Some("PA".to_owned())
3945 } else {
3946 palette_safe.then(|| {
3947 if source.explicit_mode() == Some("PA") {
3948 "PA".to_owned()
3949 } else {
3950 "P".to_owned()
3951 }
3952 })
3953 }
3954 } else {
3955 match &op {
3956 PipelineOp::Grayscale
3961 | PipelineOp::Constant { .. }
3962 | PipelineOp::Convert { .. }
3963 | PipelineOp::ConvertLab { .. }
3964 | PipelineOp::ExtractBand { .. } => None,
3965 _ => source.explicit_mode().map(str::to_owned),
3966 }
3967 };
3968 let explicit_mode = match putalpha_mode {
3973 Some(crate::pipeline::PixelMode::P | crate::pipeline::PixelMode::PA) => {
3974 Some("PA".to_owned())
3975 }
3976 Some(crate::pipeline::PixelMode::CMYK) => None,
3977 _ => explicit_mode,
3978 };
3979 let preserve_palette = palette_safe
3980 && !matches!(
3981 &op,
3982 PipelineOp::ExtractBand { .. } | PipelineOp::Merge { .. }
3983 );
3984 let source_palette = if indexed_chops_result_without_palette {
3985 Some(Vec::new())
3986 } else if preserve_palette {
3987 source.extract_palette()
3988 } else {
3989 None
3990 };
3991 let source_palette_alpha = if indexed_chops_result_without_palette {
3992 None
3993 } else if preserve_palette {
3994 source.palette_alpha()
3995 } else {
3996 None
3997 };
3998 match source {
3999 Image::Pipeline { .. }
4004 if source_is_paletted
4005 && (!palette_safe
4006 || promotes_p_to_pa
4007 || source.explicit_mode() == Some("PA")) =>
4008 {
4009 Image::Pipeline {
4010 source: Arc::new(source.clone()),
4011 ops: PipelineOps::one(op),
4012 format: None,
4016 explicit_mode,
4017 backend: source.backend(),
4018 palette: source_palette,
4019 palette_alpha: source_palette_alpha,
4020 materialized: materialization_cache(),
4021 shape: pipeline_shape_cache(),
4022 mode: pipeline_mode_cache(),
4023 }
4024 }
4025 Image::Pipeline {
4026 source: pipeline_source,
4027 ops,
4028 backend,
4029 materialized: pipeline_materialized,
4030 ..
4031 } => {
4032 let can_reuse_prefix = !source_is_paletted
4033 && ops.len() > 0
4034 && ops.mode_preserving()
4035 && op_preserves_mode(&op);
4036 let ancestor_cache = if can_reuse_prefix {
4037 if pipeline_materialized.get().is_some() {
4038 Some(PipelinePrefixCache {
4039 ops_len: ops.len(),
4040 materialized: Arc::clone(pipeline_materialized),
4041 })
4042 } else {
4043 ops.prefix_cache().cloned()
4049 }
4050 } else {
4051 None
4052 };
4053 let new_ops = ops.append(op).with_prefix_cache(ancestor_cache);
4054 Image::Pipeline {
4055 source: Arc::clone(pipeline_source),
4056 ops: new_ops,
4057 format: None,
4058 explicit_mode,
4059 backend: *backend,
4060 palette: source_palette,
4061 palette_alpha: source_palette_alpha,
4062 materialized: materialization_cache(),
4063 shape: pipeline_shape_cache(),
4064 mode: pipeline_mode_cache(),
4065 }
4066 }
4067 other => Image::Pipeline {
4068 source: Arc::new(other.clone()),
4069 ops: PipelineOps::one(op),
4070 format: None,
4071 explicit_mode,
4072 backend: other.backend(),
4073 palette: source_palette,
4074 palette_alpha: source_palette_alpha,
4075 materialized: materialization_cache(),
4076 shape: pipeline_shape_cache(),
4077 mode: pipeline_mode_cache(),
4078 },
4079 }
4080 }
4081
4082 pub(crate) fn push_mode_changing_op(
4088 source: &Image,
4089 op: PipelineOp,
4090 output_mode: &str,
4091 ) -> Image {
4092 Image::Pipeline {
4093 source: Arc::new(source.clone()),
4094 ops: PipelineOps::one(op),
4095 format: None,
4096 explicit_mode: Some(output_mode.to_owned()),
4097 backend: source.backend(),
4098 palette: None,
4099 palette_alpha: None,
4100 materialized: materialization_cache(),
4101 shape: pipeline_shape_cache(),
4102 mode: pipeline_mode_cache(),
4103 }
4104 }
4105
4106 pub fn getpixel(&self, x: u32, y: u32) -> Result<(u8, u8, u8, u8), PilError> {
4114 let img = self.materialized_shared()?;
4115 let (w, h) = (img.width(), img.height());
4116 if x >= w || y >= h {
4117 return Err(PilError::IndexError("image index out of range".into()));
4118 }
4119 let rgba = img.get_pixel(x, y).0;
4120 Ok((
4121 rgba[0],
4122 rgba.get(1).copied().unwrap_or(0),
4123 rgba.get(2).copied().unwrap_or(0),
4124 rgba.get(3).copied().unwrap_or(255),
4125 ))
4126 }
4127
4128 #[doc(hidden)]
4135 #[inline]
4136 pub fn getpixel_rgb_if_loaded(&self, x: u32, y: u32) -> Result<Option<[u8; 3]>, PilError> {
4137 let Image::Loaded(data) = self else {
4138 return Ok(None);
4139 };
4140 if data
4141 .explicit_mode
4142 .as_deref()
4143 .unwrap_or_else(|| image_mode_name(data.decoded_mode))
4144 != "RGB"
4145 {
4146 return Ok(None);
4147 }
4148 if x >= data.image.width() || y >= data.image.height() {
4149 return Err(PilError::IndexError("image index out of range".into()));
4150 }
4151 let DynamicImage::ImageRgb8(rgb) = data.image.as_ref() else {
4152 return Ok(None);
4153 };
4154 Ok(Some(rgb.get_pixel(x, y).0))
4155 }
4156
4157 pub fn getpixel_formatted(&self, x: u32, y: u32) -> Result<FormattedPixelValue, PilError> {
4159 let img = self.materialized_shared()?;
4160 let mode = self.mode_from_materialized(&img);
4161 let (width, height) = (img.width(), img.height());
4162 if is_l16_mode(&mode) {
4163 if x >= width || y >= height {
4164 return Err(PilError::IndexError("image index out of range".into()));
4165 }
4166 let index = (y as usize)
4167 .checked_mul(width as usize)
4168 .and_then(|row| row.checked_add(x as usize))
4169 .ok_or_else(|| PilError::InternalError("pixel index overflow".into()))?;
4170 return img
4171 .to_luma16()
4172 .as_raw()
4173 .get(index)
4174 .copied()
4175 .map(|value| FormattedPixelValue::Integer(i32::from(value)))
4176 .ok_or_else(|| PilError::InternalError("I;16 pixel index out of bounds".into()));
4177 }
4178 if mode == "I" || mode == "F" {
4179 if x >= width || y >= height {
4180 return Err(PilError::IndexError("image index out of range".into()));
4181 }
4182 let index = (y as usize)
4183 .checked_mul(width as usize)
4184 .and_then(|row| row.checked_add(x as usize))
4185 .ok_or_else(|| PilError::InternalError("pixel index overflow".into()))?;
4186 let offset = index
4187 .checked_mul(4)
4188 .ok_or_else(|| PilError::InternalError("scalar pixel offset overflow".into()))?;
4189 let end = offset
4190 .checked_add(4)
4191 .ok_or_else(|| PilError::InternalError("scalar pixel offset overflow".into()))?;
4192 let sample = img.as_bytes().get(offset..end).ok_or_else(|| {
4193 PilError::InternalError("scalar pixel index out of bounds".into())
4194 })?;
4195 if mode == "I" {
4196 return Ok(FormattedPixelValue::Integer(i32::from_le_bytes([
4197 sample[0], sample[1], sample[2], sample[3],
4198 ])));
4199 }
4200 return Ok(FormattedPixelValue::Float(f32::from_le_bytes([
4201 sample[0], sample[1], sample[2], sample[3],
4202 ]) as f64));
4203 }
4204
4205 let (r, g, b, a) = self.getpixel(x, y)?;
4206 Ok(match mode.as_str() {
4207 "L" | "1" | "P" => FormattedPixelValue::Scalar(r),
4208 "LA" | "La" | "PA" => FormattedPixelValue::Components(vec![r, a]),
4209 "RGB" => FormattedPixelValue::Components(vec![r, g, b]),
4210 "LAB" => {
4214 FormattedPixelValue::Components(vec![r, g.wrapping_sub(128), b.wrapping_sub(128)])
4215 }
4216 "RGBA" | "RGBa" | "RGBX" | "CMYK" => FormattedPixelValue::Components(vec![r, g, b, a]),
4217 _ => FormattedPixelValue::Components(vec![r, g, b]),
4218 })
4219 }
4220
4221 pub fn putpixel(&mut self, x: u32, y: u32, r: u8, g: u8, b: u8, a: u8) -> Result<(), PilError> {
4232 let (w, h) = self.size()?;
4233 if x >= w || y >= h {
4234 return Err(PilError::IndexError("image index out of range".into()));
4235 }
4236 let (r, g, b) = if self.explicit_mode() == Some("LAB") {
4237 (r, g.wrapping_add(128), b.wrapping_add(128))
4240 } else {
4241 (r, g, b)
4242 };
4243 let (color, palette_index, updated_palette) = if self.has_palette_mode() {
4244 if a != 255 {
4245 return Err(PilError::ValueError(
4246 "cannot add non-opaque RGBA color to RGB palette".into(),
4247 ));
4248 }
4249 let (index, palette) = self.resolve_palette_color([r, g, b])?;
4250 ((index, index, index, 255), true, palette)
4251 } else {
4252 ((r, g, b, a), false, None)
4253 };
4254 let mut new_self = Image::push_op(
4255 self,
4256 PipelineOp::PutPixel {
4257 x,
4258 y,
4259 color,
4260 palette_index,
4261 },
4262 );
4263 if let Some(updated_palette) = updated_palette {
4264 let Image::Pipeline { palette, .. } = &mut new_self else {
4265 return Err(PilError::InternalError(
4266 "putpixel did not create an operation pipeline".into(),
4267 ));
4268 };
4269 *palette = Some(updated_palette);
4270 }
4271 *self = new_self;
4272 Ok(())
4273 }
4274
4275 fn resolve_palette_color(&self, color: [u8; 3]) -> Result<(u8, Option<Vec<u8>>), PilError> {
4282 self.resolve_palette_color_with_reserved(color, &[])
4283 }
4284
4285 fn resolve_palette_color_with_reserved(
4286 &self,
4287 color: [u8; 3],
4288 reserved: &[u32],
4289 ) -> Result<(u8, Option<Vec<u8>>), PilError> {
4290 let mut palette = self.extract_palette().unwrap_or_default();
4296 if let Some(index) = palette
4297 .chunks_exact(3)
4298 .position(|entry| entry == color.as_slice())
4299 {
4300 return Ok((index as u8, None));
4301 }
4302
4303 let entries = palette.len() / 3;
4304 let mut next = entries;
4305 while next < 256 && reserved.contains(&(next as u32)) {
4306 next += 1;
4307 }
4308 let index = if next < 256 {
4309 next
4310 } else {
4311 let mut used = [false; 256];
4312 for index in self.tobytes()? {
4313 used[usize::from(index)] = true;
4314 }
4315 let transparent_index = self
4316 .palette_alpha()
4317 .filter(|alpha| alpha.len() == 1 && alpha[0] == 0)
4318 .map(|_| 0);
4319 (0..256)
4320 .rev()
4321 .find(|&index| {
4322 !used[index]
4323 && Some(index) != transparent_index
4324 && !reserved.contains(&(index as u32))
4325 })
4326 .ok_or_else(|| {
4327 PilError::ValueError("cannot allocate more than 256 colors".into())
4328 })?
4329 };
4330
4331 if index >= entries {
4332 palette.extend_from_slice(&color);
4333 } else {
4334 palette[index * 3..index * 3 + 3].copy_from_slice(&color);
4335 }
4336 Ok((index as u8, Some(palette)))
4337 }
4338
4339 pub fn putpixel_mode(&mut self, x: u32, y: u32, v: u8, mode: &str) -> Result<(), PilError> {
4349 if is_l16_mode(mode) {
4350 return self.putpixel_l16(x, y, i64::from(v));
4351 }
4352 if mode == "P" {
4353 let (w, h) = self.size()?;
4354 if x >= w || y >= h {
4355 return Err(PilError::IndexError("image index out of range".into()));
4356 }
4357 *self = Image::push_op(
4358 self,
4359 PipelineOp::PutPixel {
4360 x,
4361 y,
4362 color: (v, v, v, 255),
4363 palette_index: true,
4364 },
4365 );
4366 return Ok(());
4367 }
4368 let (r, g, b, a) = match mode {
4369 "L" | "1" => (v, v, v, 255),
4370 "LA" | "PA" => (v, 0, 0, 0),
4373 "RGB" => (v, 0, 0, 255),
4374 "YCbCr" | "HSV" => (v, 0, 0, 255),
4378 "RGBA" | "RGBX" | "CMYK" => (v, 0, 0, 0),
4379 _ => (v, v, v, 255),
4380 };
4381 self.putpixel(x, y, r, g, b, a)
4382 }
4383
4384 fn putpixel_l16(&mut self, x: u32, y: u32, value: i64) -> Result<(), PilError> {
4392 let (width, height) = self.size()?;
4393 if x >= width || y >= height {
4394 return Err(PilError::IndexError("image index out of range".into()));
4395 }
4396 let pixel_index = (y as usize)
4397 .checked_mul(width as usize)
4398 .and_then(|row| row.checked_add(x as usize))
4399 .ok_or_else(|| PilError::DimensionError("pixel index overflow".into()))?;
4400 self.load()?;
4401 if let Image::Loaded(data) = self {
4402 let image = Arc::make_mut(&mut data.image);
4403 let destination = image
4404 .as_mut_luma16()
4405 .ok_or_else(|| PilError::InternalError("putpixel I;16 storage mismatch".into()))?;
4406 let pixel = destination.as_mut().get_mut(pixel_index).ok_or_else(|| {
4407 PilError::InternalError("putpixel I;16 offset out of bounds".into())
4408 })?;
4409 *pixel = value as u16;
4410 data.known_zero_fill = false;
4411 return Ok(());
4412 }
4413 Err(PilError::InternalError(
4414 "putpixel I;16 did not materialize writable storage".into(),
4415 ))
4416 }
4417
4418 pub fn putpixel_mode_scalar(
4424 &mut self,
4425 x: u32,
4426 y: u32,
4427 value: f64,
4428 mode: &str,
4429 ) -> Result<(), PilError> {
4430 if !matches!(mode, "I" | "F") {
4431 return self.putpixel_mode(x, y, value as u8, mode);
4432 }
4433 let (width, height) = self.size()?;
4434 if x >= width || y >= height {
4435 return Err(PilError::IndexError("image index out of range".into()));
4436 }
4437 let pixel_index = (y as usize)
4438 .checked_mul(width as usize)
4439 .and_then(|row| row.checked_add(x as usize))
4440 .ok_or_else(|| PilError::DimensionError("pixel index overflow".into()))?;
4441 self.putdata_value_at(pixel_index, &PutDataValue::Number(value), 1.0, 0.0)
4442 }
4443
4444 pub fn prepare_putpixel_palette(
4454 &mut self,
4455 value: PutPixelValue,
4456 reserved: &[u32],
4457 ) -> Result<PutPixelValue, PilError> {
4458 if !self.has_palette_samples() {
4459 return Ok(value);
4460 }
4461 if let PutPixelValue::FloatComponents(values) = &value {
4462 let rgba = self.palette_mode() == Some("RGBA");
4465 let palette = if rgba {
4466 self.getpalette_rgba()
4467 } else {
4468 self.extract_palette()
4469 }
4470 .unwrap_or_default();
4471 let mut color = values.clone();
4472 if rgba && color.len() == 3 {
4473 color.push(255.0);
4474 }
4475 if let Some(index) = palette
4476 .chunks_exact(if rgba { 4 } else { 3 })
4477 .position(|entry| {
4478 entry.len() == color.len()
4479 && entry
4480 .iter()
4481 .zip(&color)
4482 .all(|(&byte, &value)| f64::from(byte) == value)
4483 })
4484 {
4485 return Ok(if self.explicit_mode() == Some("PA") {
4486 PutPixelValue::Components(vec![index as i64, 255])
4487 } else {
4488 PutPixelValue::Integer(index as i64)
4489 });
4490 }
4491 if self.explicit_mode() == Some("PA") && palette.len() / if rgba { 4 } else { 3 } >= 256
4492 {
4493 return Err(PilError::ValueError(
4494 "cannot allocate more than 256 colors".into(),
4495 ));
4496 }
4497 return Err(PilError::TypeError(
4498 "'float' object cannot be interpreted as an integer".into(),
4499 ));
4500 }
4501 let PutPixelValue::Components(ref values) = value else {
4502 return Ok(value);
4503 };
4504 if !matches!(values.len(), 3 | 4) {
4505 return Ok(value);
4506 }
4507 let pa = self.explicit_mode() == Some("PA");
4508 let alpha = values.get(3).copied().unwrap_or(255);
4509 let rgba_palette = self.palette_mode() == Some("RGBA");
4510 if !pa && !rgba_palette && alpha != 255 {
4511 return Err(PilError::ValueError(
4512 "cannot add non-opaque RGBA color to RGB palette".into(),
4513 ));
4514 }
4515 if pa {
4516 let palette = if rgba_palette {
4517 self.getpalette_rgba()
4518 } else {
4519 self.extract_palette()
4520 }
4521 .unwrap_or_default();
4522 let channels = if rgba_palette { 4 } else { 3 };
4523 if palette.len() / channels >= 256 {
4524 if let Some(index) = palette.chunks_exact(channels).position(|entry| {
4528 entry[..3]
4529 .iter()
4530 .zip(&values[..3])
4531 .all(|(&byte, &value)| i64::from(byte) == value)
4532 && (!rgba_palette || entry[3] == 255)
4533 }) {
4534 return Ok(PutPixelValue::Components(vec![index as i64, alpha]));
4535 }
4536 return Err(PilError::ValueError(
4537 "cannot allocate more than 256 colors".into(),
4538 ));
4539 }
4540 }
4541 let mut color = Vec::with_capacity(4);
4542 for &value in &values[..3] {
4543 color.push(
4544 u8::try_from(value)
4545 .map_err(|_| PilError::ValueError("bytes must be in range(0, 256)".into()))?,
4546 );
4547 }
4548 let index = if rgba_palette {
4549 color.push(if pa {
4550 255
4551 } else {
4552 u8::try_from(alpha)
4553 .map_err(|_| PilError::ValueError("bytes must be in range(0, 256)".into()))?
4554 });
4555 let mut palette = self.getpalette_rgba().unwrap_or_default();
4556 if let Some(index) = palette.chunks_exact(4).position(|entry| entry == color) {
4557 index as u8
4558 } else {
4559 let entries = palette.len() / 4;
4560 let mut next = entries;
4561 while next < 256 && reserved.contains(&(next as u32)) {
4562 next += 1;
4563 }
4564 let index = if next < 256 {
4565 next
4566 } else if !pa {
4567 let mut used = [false; 256];
4568 for index in self.tobytes()? {
4569 used[usize::from(index)] = true;
4570 }
4571 (0..256)
4572 .rev()
4573 .find(|&index| !used[index] && !reserved.contains(&(index as u32)))
4574 .ok_or_else(|| {
4575 PilError::ValueError("cannot allocate more than 256 colors".into())
4576 })?
4577 } else {
4578 return Err(PilError::ValueError(
4579 "cannot allocate more than 256 colors".into(),
4580 ));
4581 };
4582 if index >= entries {
4583 palette.extend_from_slice(&color);
4584 } else {
4585 palette[index * 4..index * 4 + 4].copy_from_slice(&color);
4586 }
4587 self.putpalette(&palette, "RGBA")?;
4588 index as u8
4589 }
4590 } else {
4591 let (index, palette) =
4592 self.resolve_palette_color_with_reserved([color[0], color[1], color[2]], reserved)?;
4593 if let Some(palette) = palette {
4594 self.putpalette(&palette, "RGB")?;
4595 }
4596 index
4597 };
4598 Ok(if pa {
4599 PutPixelValue::Components(vec![i64::from(index), alpha])
4600 } else {
4601 PutPixelValue::Integer(i64::from(index))
4602 })
4603 }
4604
4605 pub fn putpixel_value(&mut self, x: u32, y: u32, value: PutPixelValue) -> Result<(), PilError> {
4607 let value = self.prepare_putpixel_palette(value, &[])?;
4608 let mode = self.mode()?;
4609 match value {
4610 PutPixelValue::Integer(value) => {
4611 if is_l16_mode(&mode) {
4612 return self.putpixel_l16(x, y, value);
4613 }
4614 if mode == "I" {
4615 return self.putpixel_mode_scalar(x, y, f64::from(value as i32), &mode);
4618 }
4619 if mode == "F" {
4620 return self.putpixel_mode_scalar(x, y, value as f64, &mode);
4621 }
4622 if matches!(mode.as_str(), "1" | "L" | "P") {
4623 return self.putpixel_mode(x, y, value.clamp(0, 255) as u8, &mode);
4624 }
4625 let bytes = value.to_le_bytes();
4629 self.putpixel(x, y, bytes[0], bytes[1], bytes[2], bytes[3])
4630 }
4631 PutPixelValue::Float(value) => {
4632 if mode == "F" {
4633 self.putpixel_mode_scalar(x, y, value, &mode)
4634 } else {
4635 Err(if mode.len() == 1 {
4636 PilError::TypeError("color must be int or single-element tuple".into())
4637 } else {
4638 PilError::TypeError("color must be int or tuple".into())
4639 })
4640 }
4641 }
4642 PutPixelValue::Invalid => Err(if mode.len() == 1 {
4643 PilError::TypeError("color must be int or single-element tuple".into())
4644 } else {
4645 PilError::TypeError(
4648 "color must be int, or tuple of one, three or four elements".into(),
4649 )
4650 }),
4651 PutPixelValue::Components(values) => {
4652 if let [value] = values.as_slice() {
4653 return self.putpixel_value(x, y, PutPixelValue::Integer(*value));
4654 }
4655 let bands = pillow_band_count(&mode);
4656 let palette_color =
4657 matches!(mode.as_str(), "P" | "PA") && matches!(values.len(), 3 | 4);
4658 if !palette_color
4659 && ((bands == 1)
4660 || (bands == 2 && values.len() != 2)
4661 || (bands >= 3 && !matches!(values.len(), 3 | 4)))
4662 {
4663 return Err(PilError::TypeError(
4664 match bands {
4665 1 => "color must be int or single-element tuple",
4666 2 => "color must be int, or tuple of one or two elements",
4667 _ => "color must be int, or tuple of one, three or four elements",
4668 }
4669 .into(),
4670 ));
4671 }
4672 let bytes: Vec<u8> = values
4673 .iter()
4674 .map(|&value| value.clamp(0, 255) as u8)
4675 .collect();
4676 match bytes.as_slice() {
4677 [value, alpha] => self.putpixel(x, y, *value, 0, 0, *alpha),
4678 [r, g, b] => self.putpixel(x, y, *r, *g, *b, 255),
4679 [r, g, b, a] => self.putpixel(x, y, *r, *g, *b, *a),
4680 _ => Err(PilError::InternalError(
4681 "validated putpixel arity changed".into(),
4682 )),
4683 }
4684 }
4685 PutPixelValue::FloatComponents(values) => match values.as_slice() {
4686 [value] if mode == "F" => self.putpixel_mode_scalar(x, y, *value, &mode),
4687 _ => Err(if mode.len() == 1 {
4688 PilError::TypeError("color must be int or single-element tuple".into())
4689 } else {
4690 PilError::TypeError(
4691 "color must be int, or tuple of one, three or four elements".into(),
4692 )
4693 }),
4694 },
4695 }
4696 }
4697
4698 pub fn stat_formatted(&self) -> Result<StatResult, PilError> {
4707 let bands = self.stat()?;
4708 Ok(StatResult::from_bands(&bands))
4709 }
4710
4711 pub fn stat_formatted_with_mask(
4718 &self,
4719 mask: crate::ops::imageops::ImageOpsMask,
4720 ) -> Result<StatResult, PilError> {
4721 match mask {
4722 crate::ops::imageops::ImageOpsMask::None => self.stat_formatted(),
4723 crate::ops::imageops::ImageOpsMask::Invalid(type_name) => Err(
4724 PilError::AttributeError(format!("'{type_name}' object has no attribute 'load'")),
4725 ),
4726 crate::ops::imageops::ImageOpsMask::Image(mask) => {
4727 let histogram = self.histogram_with_mask(Some(&mask))?;
4728 let histogram: Vec<f64> = histogram.into_iter().map(f64::from).collect();
4729 Ok(stat_from_histogram(&histogram))
4730 }
4731 }
4732 }
4733
4734 pub fn stat(&self) -> Result<Vec<Vec<f64>>, PilError> {
4745 let explicit_mode = self.explicit_mode();
4746 let is_f = explicit_mode == Some("F");
4747 let is_i = explicit_mode == Some("I");
4748
4749 if is_f || is_i {
4750 let img = self.materialized_shared()?;
4756 let rgba = img.as_bytes();
4757 let n_pixels = rgba.len() / 4;
4758 if n_pixels == 0 {
4759 return Err(PilError::ValueError("min/max not given".into()));
4762 }
4763 let decode = |bytes: &[u8]| {
4768 let bytes: [u8; 4] = [bytes[0], bytes[1], bytes[2], bytes[3]];
4769 if is_f {
4770 f32::from_le_bytes(bytes) as f64
4771 } else {
4772 i32::from_le_bytes(bytes) as f64
4773 }
4774 };
4775 let mut samples = rgba.chunks_exact(4);
4776 let first = decode(samples.next().expect("n_pixels guarantees one sample"));
4777 let mut min_val = first;
4778 let mut max_val = first;
4779 for bytes in samples {
4780 let value = decode(bytes);
4781 if value.partial_cmp(&min_val) == Some(std::cmp::Ordering::Less) {
4782 min_val = value;
4783 }
4784 if value.partial_cmp(&max_val) == Some(std::cmp::Ordering::Greater) {
4785 max_val = value;
4786 }
4787 }
4788 if (max_val - min_val).abs() < f64::EPSILON {
4789 return Ok(vec![vec![
4795 0.0, 0.0, 0.0, 0.0, 255.0, 0.0, 0.0, 0.0, 255.0, 0.0,
4796 ]]);
4797 }
4798 let mut hist = [0i64; 256];
4799 if is_f {
4800 let min_f = min_val as f32;
4807 let max_f = max_val as f32;
4808 let scale = 255.0_f32 / (max_f - min_f);
4809 for bytes in rgba.chunks_exact(4) {
4810 let value = f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
4811 let bin = ((value - min_f) * scale).clamp(0.0, 255.0) as usize;
4812 hist[bin] += 1;
4813 }
4814 } else {
4815 let scale = 255.0 / (max_val - min_val);
4816 for bytes in rgba.chunks_exact(4) {
4817 let value = decode(bytes);
4818 let bin = if value == max_val {
4823 255
4824 } else {
4825 ((value - min_val) * scale).clamp(0.0, 255.0) as usize
4826 };
4827 hist[bin] += 1;
4828 }
4829 }
4830 let count = n_pixels as f64;
4831 let sum: f64 = hist
4832 .iter()
4833 .enumerate()
4834 .map(|(i, &c)| i as f64 * c as f64)
4835 .sum();
4836 let sum2: f64 = hist
4837 .iter()
4838 .enumerate()
4839 .map(|(i, &c)| (i as f64) * (i as f64) * c as f64)
4840 .sum();
4841 let mean = sum / count;
4842 let rms = (sum2 / count).sqrt();
4843 let var = (sum2 - sum * sum / count) / count;
4844 let var = if var < 0.0 { 0.0 } else { var };
4845 let stddev = var.sqrt();
4846 let mut cum = 0i64;
4847 let half = (count / 2.0) as i64;
4848 let mut median = 0.0;
4849 for (i, &c) in hist.iter().enumerate() {
4850 cum += c;
4851 if cum > half {
4852 median = i as f64;
4853 break;
4854 }
4855 }
4856 let mut min_bin = 255usize;
4857 let mut max_bin = 0usize;
4858 for (i, &c) in hist.iter().enumerate() {
4859 if c > 0 {
4860 min_bin = min_bin.min(i);
4861 max_bin = max_bin.max(i);
4862 }
4863 }
4864 return Ok(vec![vec![
4865 count,
4866 sum,
4867 sum2,
4868 mean,
4869 median,
4870 rms,
4871 var,
4872 stddev,
4873 min_bin as f64,
4874 max_bin as f64,
4875 ]]);
4876 }
4877
4878 let img = self.materialized_shared()?;
4879 let is_l16_stat = img.color() == crate::raster::ColorType::L16
4880 && matches!(explicit_mode, Some(mode) if is_l16_mode(mode));
4881 if is_l16_stat
4882 || matches!(
4883 img.color(),
4884 crate::raster::ColorType::L8
4885 | crate::raster::ColorType::La8
4886 | crate::raster::ColorType::Rgb8
4887 | crate::raster::ColorType::Rgba8
4888 )
4889 {
4890 let histogram = self.histogram()?;
4897 let mut results = Vec::with_capacity(histogram.len() / 256);
4898 for band in histogram.chunks_exact(256) {
4899 let count_u64: u64 = band.iter().map(|&value| u64::from(value)).sum();
4900 let count = count_u64 as f64;
4901 if count == 0.0 {
4902 results.push(vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 255.0, 0.0]);
4903 continue;
4904 }
4905 let sum: f64 = band
4906 .iter()
4907 .enumerate()
4908 .map(|(value, &frequency)| value as f64 * frequency as f64)
4909 .sum();
4910 let sum2: f64 = band
4911 .iter()
4912 .enumerate()
4913 .map(|(value, &frequency)| {
4914 let value = value as f64;
4915 value * value * frequency as f64
4916 })
4917 .sum();
4918 let mean = sum / count;
4919 let rms = (sum2 / count).sqrt();
4920 let var = (sum2 - sum * sum / count) / count;
4921 let stddev = var.sqrt();
4922 let half = count_u64 / 2;
4923 let mut cumulative = 0u64;
4924 let mut median = None;
4925 let mut min: f64 = 255.0;
4926 let mut max: f64 = 0.0;
4927 for (value, &frequency) in band.iter().enumerate() {
4928 if frequency > 0 {
4929 min = min.min(value as f64);
4930 max = max.max(value as f64);
4931 }
4932 cumulative += u64::from(frequency);
4933 if median.is_none() && cumulative > half {
4934 median = Some(value as f64);
4935 }
4936 }
4937 results.push(vec![
4938 count,
4939 sum,
4940 sum2,
4941 mean,
4942 median.unwrap_or(255.0),
4943 rms,
4944 var,
4945 stddev,
4946 min,
4947 max,
4948 ]);
4949 }
4950 return Ok(results);
4951 }
4952
4953 let n_bands = img.color().channel_count() as usize;
4954
4955 let mut histograms = vec![[0u64; 256]; n_bands];
4960
4961 match n_bands {
4962 1 => {
4963 let gray = img.to_luma8();
4964 for px in gray.pixels() {
4965 histograms[0][px[0] as usize] += 1;
4966 }
4967 }
4968 2 => {
4969 let rgba = img.to_rgba8();
4971 for px in rgba.pixels() {
4972 histograms[0][px[0] as usize] += 1; histograms[1][px[3] as usize] += 1; }
4975 }
4976 3 => {
4977 let rgb = img.to_rgb8();
4978 for px in rgb.pixels() {
4979 histograms[0][px[0] as usize] += 1;
4980 histograms[1][px[1] as usize] += 1;
4981 histograms[2][px[2] as usize] += 1;
4982 }
4983 }
4984 _ => {
4985 let rgba = img.to_rgba8();
4986 for px in rgba.pixels() {
4987 for b in 0..4 {
4988 histograms[b][px[b] as usize] += 1;
4989 }
4990 }
4991 }
4992 }
4993
4994 let mut results = Vec::with_capacity(n_bands);
4995 for histogram in &histograms {
4996 let count_u64: u64 = histogram.iter().sum();
4997 let count = count_u64 as f64;
4998 if count_u64 == 0 {
4999 results.push(vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 255.0, 0.0]);
5002 continue;
5003 }
5004 let sum: f64 = histogram
5005 .iter()
5006 .enumerate()
5007 .map(|(value, &frequency)| value as f64 * frequency as f64)
5008 .sum();
5009 let sum2: f64 = histogram
5010 .iter()
5011 .enumerate()
5012 .map(|(value, &frequency)| {
5013 let value = value as f64;
5014 value * value * frequency as f64
5015 })
5016 .sum();
5017 let mean = sum / count;
5018 let rms = (sum2 / count).sqrt();
5019 let var = (sum2 - sum * sum / count) / count;
5024 let stddev = var.sqrt();
5025 let half = count_u64 / 2;
5026 let mut cumulative = 0u64;
5027 let mut median = None;
5028 let mut min = 255.0;
5029 let mut max = 0.0;
5030 for (value, &frequency) in histogram.iter().enumerate() {
5031 if frequency > 0 {
5032 min = value as f64;
5033 break;
5034 }
5035 }
5036 for (value, &frequency) in histogram.iter().enumerate() {
5037 if frequency > 0 {
5038 max = value as f64;
5039 }
5040 cumulative += frequency;
5041 if median.is_none() && cumulative > half {
5042 median = Some(value as f64);
5043 }
5044 }
5045 results.push(vec![
5046 count,
5047 sum,
5048 sum2,
5049 mean,
5050 median.unwrap_or(255.0),
5051 rms,
5052 var,
5053 stddev,
5054 min,
5055 max,
5056 ]);
5057 }
5058 Ok(results)
5059 }
5060
5061 pub fn getbands(&self) -> Result<Vec<String>, PilError> {
5068 let mode = self.mode()?;
5074 let bands: Vec<&str> = match mode.as_str() {
5075 "CMYK" => vec!["C", "M", "Y", "K"],
5076 "YCbCr" => vec!["Y", "Cb", "Cr"],
5077 "HSV" => vec!["H", "S", "V"],
5078 "LAB" => vec!["L", "A", "B"],
5079 "PA" => vec!["P", "A"],
5080 "La" => vec!["L", "a"],
5081 "RGBa" => vec!["R", "G", "B", "a"],
5082 "RGBX" => vec!["R", "G", "B", "X"],
5083 "I" | "F" | "P" | "1" => {
5084 vec![mode.as_str()]
5085 }
5086 "I;16" | "I;16L" | "I;16B" | "I;16N" => vec!["I"],
5089 "L" => vec!["L"],
5090 "LA" => vec!["L", "A"],
5091 "RGB" => vec!["R", "G", "B"],
5092 "RGBA" => vec!["R", "G", "B", "A"],
5093 _ => Vec::new(),
5094 };
5095 Ok(bands.into_iter().map(str::to_string).collect())
5096 }
5097
5098 pub fn resolve_save_format(
5104 explicit: Option<&str>,
5105 extension: Option<&str>,
5106 ) -> Result<String, PilError> {
5107 if let Some(format) = explicit {
5108 parse_format_str(format)
5109 .map(|_| format.to_owned())
5110 .map_err(|_| PilError::KeyError(format.to_owned()))
5111 } else {
5112 let extension = extension.ok_or_else(|| {
5113 PilError::ValueError("unknown file extension: ".into())
5116 })?;
5117 parse_format_str(extension)
5118 .map(|_| extension.to_owned())
5119 .map_err(|_| PilError::ValueError(format!("unknown file extension: .{extension}")))
5120 }
5121 }
5122
5123 pub fn tobytes(&self) -> Result<Vec<u8>, PilError> {
5130 let mode = self.mode()?;
5131 self.tobytes_formatted(&mode)
5132 }
5133
5134 pub fn tobytes_unpacked(&self) -> Result<Vec<u8>, PilError> {
5144 if self.mode()? == "1" {
5145 return Ok(self.materialized_shared()?.to_luma8().into_raw());
5146 }
5147 self.tobytes()
5148 }
5149
5150 pub fn tobytes_formatted(&self, mode: &str) -> Result<Vec<u8>, PilError> {
5161 if let Image::Paletted(data) = self {
5163 return Ok(data.indices.as_raw().to_vec());
5164 }
5165 let img = self.materialized_shared()?;
5166
5167 if matches!(mode, "F" | "I") {
5171 return Ok(img.as_bytes().to_vec());
5172 }
5173
5174 if is_l16_mode(mode) {
5175 let native_is_big = cfg!(target_endian = "big");
5176 let raw_is_big = l16_uses_big_endian(mode);
5177 let bytes = img.as_bytes();
5178 if native_is_big == raw_is_big {
5179 return Ok(bytes.to_vec());
5180 }
5181 let mut swapped = Vec::with_capacity(bytes.len());
5182 for sample in bytes.chunks_exact(2) {
5183 swapped.extend_from_slice(&[sample[1], sample[0]]);
5184 }
5185 return Ok(swapped);
5186 }
5187
5188 if mode == "1" && img.color() == crate::raster::ColorType::L8 {
5190 return Ok(pack_mode1_rows(
5191 img.as_bytes(),
5192 img.width() as usize,
5193 img.height() as usize,
5194 ));
5195 }
5196 Ok(img.as_bytes().to_vec())
5197 }
5198
5199 pub fn tobytes_encoded(
5210 &self,
5211 mode: &str,
5212 encoder_name: &str,
5213 args: &[String],
5214 ) -> Result<Vec<u8>, PilError> {
5215 if encoder_name != "raw" {
5216 return Err(PilError::IOError(format!(
5217 "encoder {encoder_name} not available"
5218 )));
5219 }
5220 let raw_mode = args.first().map(String::as_str).unwrap_or(mode);
5221 let mode_supports_raw = raw_mode == mode
5222 || (mode == "RGB" && matches!(raw_mode, "BGR" | "RGBA"))
5223 || (mode == "RGBA" && raw_mode == "BGRA");
5224 if !mode_supports_raw {
5225 return Err(PilError::ValueError(format!(
5226 "No packer found from {mode} to {raw_mode}"
5227 )));
5228 }
5229 if args.is_empty() && self.mode()? == mode {
5233 return self.tobytes();
5234 }
5235 let mut data = self.tobytes_formatted(mode)?;
5236 if mode == "RGB" && raw_mode == "RGBA" {
5237 let mut expanded = Vec::with_capacity(data.len() / 3 * 4);
5238 for pixel in data.chunks_exact(3) {
5239 expanded.extend_from_slice(pixel);
5240 expanded.push(255);
5241 }
5242 data = expanded;
5243 }
5244 match args.first().map(String::as_str) {
5245 Some("BGRA") => {
5246 for pixel in data.chunks_exact_mut(4) {
5247 pixel.swap(0, 2);
5248 }
5249 }
5250 Some("BGR") => {
5251 for pixel in data.chunks_exact_mut(3) {
5252 pixel.swap(0, 2);
5253 }
5254 }
5255 _ => {}
5256 }
5257 Ok(data)
5258 }
5259
5260 pub fn tobytes_encoded_shared(
5274 &self,
5275 mode: &str,
5276 encoder_name: &str,
5277 args: &[String],
5278 ) -> Result<impl AsRef<[u8]> + Send + Sync + 'static + use<>, PilError> {
5279 if encoder_name != "raw"
5280 || !args.is_empty()
5281 || matches!(self, Image::Paletted(_))
5282 || mode == "1"
5283 || (is_l16_mode(mode) && cfg!(target_endian = "big") != l16_uses_big_endian(mode))
5284 {
5285 return self
5286 .tobytes_encoded(mode, encoder_name, args)
5287 .map(ImageByteExport::Packed);
5288 }
5289
5290 self.mode()?;
5294 self.materialized_shared().map(ImageByteExport::Shared)
5295 }
5296
5297 pub fn use_backend(mut self, b: crate::compute::Backend) -> Image {
5302 self.lock_backend_recursive(b);
5303 self
5304 }
5305
5306 fn lock_backend_recursive(&mut self, b: crate::compute::Backend) {
5307 let Image::Pipeline {
5308 source,
5309 ops,
5310 backend,
5311 materialized,
5312 ..
5313 } = self
5314 else {
5315 return;
5316 };
5317
5318 Arc::make_mut(source).lock_backend_recursive(b);
5319 let mut flattened_ops = ops.to_vec();
5320 for op in &mut flattened_ops {
5321 Self::lock_op_backend_recursive(op, b);
5322 }
5323 *ops = PipelineOps::from_vec(flattened_ops);
5324 *backend = Some(b);
5325 *materialized = materialization_cache();
5328 }
5329
5330 fn lock_op_backend_recursive(op: &mut PipelineOp, b: crate::compute::Backend) {
5331 match op {
5332 PipelineOp::Add { other, .. }
5333 | PipelineOp::Subtract { other, .. }
5334 | PipelineOp::Multiply { other }
5335 | PipelineOp::Screen { other }
5336 | PipelineOp::Darker { other }
5337 | PipelineOp::Lighter { other }
5338 | PipelineOp::Difference { other }
5339 | PipelineOp::Overlay { other }
5340 | PipelineOp::HardLight { other }
5341 | PipelineOp::SoftLight { other }
5342 | PipelineOp::AddModulo { other }
5343 | PipelineOp::SubtractModulo { other }
5344 | PipelineOp::LogicalAnd { other }
5345 | PipelineOp::LogicalOr { other }
5346 | PipelineOp::LogicalXor { other }
5347 | PipelineOp::BlendModule { other, .. } => {
5348 Arc::make_mut(other).lock_backend_recursive(b);
5349 }
5350 PipelineOp::CompositeModule { other, mask, .. } => {
5351 Arc::make_mut(other).lock_backend_recursive(b);
5352 Arc::make_mut(mask).lock_backend_recursive(b);
5353 }
5354 PipelineOp::Paste { source, mask, .. } => {
5355 Arc::make_mut(source).lock_backend_recursive(b);
5356 if let Some(mask) = mask {
5357 Arc::make_mut(mask).lock_backend_recursive(b);
5358 }
5359 }
5360 PipelineOp::AlphaComposite { source, .. } => {
5361 Arc::make_mut(source).lock_backend_recursive(b);
5362 }
5363 PipelineOp::Merge { bands, .. } => {
5364 for band in Arc::make_mut(bands).iter_mut() {
5365 band.lock_backend_recursive(b);
5366 }
5367 }
5368 PipelineOp::Autocontrast {
5369 mask: Some(mask), ..
5370 }
5371 | PipelineOp::EqualizeMasked { mask } => {
5372 Arc::make_mut(mask).lock_backend_recursive(b);
5373 }
5374 _ => {}
5375 }
5376 }
5377
5378 pub fn backend(&self) -> Option<crate::compute::Backend> {
5380 match self {
5381 Image::Pipeline { backend, .. } => *backend,
5382 _ => None,
5383 }
5384 }
5385
5386 pub fn explicit_mode(&self) -> Option<&str> {
5392 match self {
5393 Image::Loaded(LoadedData {
5394 explicit_mode: Some(m),
5395 ..
5396 }) => Some(m.as_str()),
5397 Image::Paletted(_) => Some("P"),
5398 Image::Pipeline {
5399 explicit_mode: Some(m),
5400 ..
5401 } => Some(m.as_str()),
5402 _ => None,
5403 }
5404 }
5405
5406 pub fn palette(&self) -> Option<Vec<u8>> {
5412 match self {
5413 Image::Paletted(data) => Some(data.palette.clone()),
5414 Image::Loaded(data) => data.palette.clone(),
5415 Image::Pipeline { palette, .. } => palette.clone(),
5416 Image::Bytes { info, .. } => info
5417 .as_ref()
5418 .and_then(|info| info.palette.as_ref())
5419 .map(|palette| palette.rgb.clone()),
5420 }
5421 }
5422
5423 pub fn palette_alpha(&self) -> Option<Vec<u8>> {
5425 match self {
5426 Image::Paletted(data) => Some(data.palette_alpha.clone()),
5427 Image::Loaded(data) => data.palette_alpha.clone(),
5428 Image::Pipeline { palette_alpha, .. } => palette_alpha.clone(),
5429 Image::Bytes { info, .. } => info
5430 .as_ref()
5431 .and_then(|info| info.palette.as_ref())
5432 .map(|palette| palette.alpha.clone()),
5433 }
5434 }
5435
5436 pub fn image_info(&self) -> Option<ImageInfo> {
5441 match self {
5442 Image::Loaded(data) => data.info.clone(),
5443 Image::Paletted(data) => data.info.clone(),
5444 Image::Bytes { info, .. } => info.clone(),
5445 Image::Pipeline { source, .. } => source.image_info(),
5446 }
5447 }
5448
5449 pub(crate) fn source_format(&self) -> Option<ImageFormat> {
5450 match self {
5451 Image::Loaded(data) => data.source_format,
5452 Image::Paletted(data) => data.source_format,
5453 Image::Bytes { format, .. } | Image::Pipeline { format, .. } => *format,
5454 }
5455 }
5456
5457 pub fn getpalette_trimmed(&self) -> Option<Vec<u8>> {
5463 self.extract_palette()
5464 }
5465
5466 pub fn getpalette_rgba(&self) -> Option<Vec<u8>> {
5469 let palette = self.getpalette_trimmed()?;
5470 let alpha = if self.pending_palette_transparency().is_none() {
5471 self.palette_alpha().unwrap_or_default()
5472 } else {
5473 Vec::new()
5474 };
5475 let mut rgba = Vec::with_capacity(palette.len() / 3 * 4);
5476 for (index, color) in palette.chunks_exact(3).enumerate() {
5477 rgba.extend_from_slice(color);
5478 rgba.push(alpha.get(index).copied().unwrap_or(255));
5479 }
5480 Some(rgba)
5481 }
5482
5483 pub fn getpalette_rawmode(&self, rawmode: &str) -> Result<Option<Vec<u8>>, PilError> {
5491 let Some(palette) = self.getpalette_trimmed() else {
5492 return Ok(None);
5493 };
5494 let palette_alpha = if self.pending_palette_transparency().is_none() {
5499 self.palette_alpha().unwrap_or_default()
5500 } else {
5501 Vec::new()
5502 };
5503 let has_alpha = !palette_alpha.is_empty();
5504 match rawmode {
5505 "RGB" => Ok(Some(palette)),
5506 "RGBA" => Ok(self.getpalette_rgba()),
5507 "RGBX" => {
5508 if has_alpha {
5512 return Err(PilError::ValueError("unrecognized raw mode".into()));
5513 }
5514 let mut out = Vec::with_capacity(palette.len() / 3 * 4);
5515 for color in palette.chunks_exact(3) {
5516 out.extend_from_slice(color);
5517 out.push(255);
5518 }
5519 Ok(Some(out))
5520 }
5521 "R" | "G" | "B" => {
5522 let channel = match rawmode {
5523 "R" => 0,
5524 "G" => 1,
5525 _ => 2,
5526 };
5527 Ok(Some(
5528 palette
5529 .chunks_exact(3)
5530 .map(|color| color[channel])
5531 .collect(),
5532 ))
5533 }
5534 _ => Err(PilError::ValueError("unrecognized raw mode".into())),
5535 }
5536 }
5537
5538 pub fn getpalette_with_input(
5541 &self,
5542 rawmode: Option<&str>,
5543 ) -> Result<Option<Vec<u8>>, PilError> {
5544 let rawmode = rawmode.or_else(|| self.palette_mode()).unwrap_or("RGB");
5545 let palette = self.getpalette_rawmode(rawmode)?;
5546 if palette.is_none() && matches!(self.mode()?.as_str(), "P" | "PA") {
5547 return Ok(Some(Vec::new()));
5548 }
5549 Ok(palette)
5550 }
5551
5552 pub fn indexed_color_table(&self, mode: &str) -> Result<Vec<(u8, u8, u8)>, PilError> {
5558 match mode {
5559 "L" => Ok((0..=u8::MAX).map(|value| (value, value, value)).collect()),
5560 "P" => Ok(self
5561 .getpalette_with_input(Some("RGB"))?
5562 .unwrap_or_default()
5563 .chunks_exact(3)
5564 .map(|color| (color[0], color[1], color[2]))
5565 .collect()),
5566 _ => Ok(Vec::new()),
5567 }
5568 }
5569
5570 pub fn putpalette(&mut self, data: &[u8], rawmode: &str) -> Result<(), PilError> {
5584 let mode = self.mode()?;
5585 if !matches!(mode.as_str(), "L" | "LA" | "P" | "PA") {
5586 return Err(PilError::ValueError("illegal image mode".to_owned()));
5587 }
5588 let (palette, palette_alpha) = split_palette_data(data, rawmode)?;
5589 let source_format = self.source_format();
5590 let info = self.image_info();
5591 let exif = self.exif_metadata();
5592 let materialized = self.materialize()?;
5593
5594 *self = match mode.as_str() {
5595 "L" | "P" => Image::Paletted(PalettedData {
5596 indices: materialized.to_luma8(),
5597 palette,
5598 palette_alpha,
5599 source_format,
5600 info,
5601 exif,
5602 materialized: materialization_cache(),
5603 }),
5604 "LA" | "PA" => {
5605 let image = DynamicImage::ImageLumaA8(materialized.to_luma_alpha8());
5606 let decoded_mode = image.color().into();
5607 Image::Loaded(LoadedData {
5608 image: Arc::new(image),
5609 known_zero_fill: false,
5610 explicit_mode: Some("PA".to_owned()),
5611 decoded_mode,
5612 palette: Some(palette),
5613 palette_alpha: Some(palette_alpha),
5614 source_format,
5615 info,
5616 exif,
5617 })
5618 }
5619 _ => unreachable!("putpalette mode was validated"),
5620 };
5621 Ok(())
5622 }
5623
5624 pub fn pending_palette_transparency(&self) -> Option<PaletteTransparency> {
5629 if !self.has_palette_samples() {
5630 return None;
5631 }
5632 let alpha = self
5633 .image_info()?
5634 .palette
5635 .as_ref()
5636 .map(|palette| palette.alpha.as_slice())?
5637 .to_vec();
5638 if alpha.is_empty() {
5639 return None;
5640 }
5641 let mut transparent_index = None;
5642 for (index, value) in alpha.iter().copied().enumerate() {
5643 if value == 255 {
5644 continue;
5645 }
5646 if value != 0 || transparent_index.is_some() {
5647 return Some(PaletteTransparency::Table(alpha));
5648 }
5649 transparent_index = u8::try_from(index).ok();
5650 }
5651 transparent_index
5652 .map(PaletteTransparency::Index)
5653 .or_else(|| Some(PaletteTransparency::Table(alpha)))
5654 }
5655
5656 pub fn pending_transparency_info(&self) -> Option<ImageInfoValue> {
5659 match self.pending_palette_transparency()? {
5660 PaletteTransparency::Index(index) => Some(ImageInfoValue::Integer(i64::from(index))),
5661 PaletteTransparency::Table(alpha) => Some(ImageInfoValue::Bytes(alpha)),
5662 }
5663 }
5664
5665 pub fn compatibility_info(&self) -> Vec<(String, ImageInfoValue)> {
5672 let format = self
5673 .source_format()
5674 .or_else(|| self.image_info().map(|info| info.format));
5675 let mut fields = match format {
5681 Some(ImageFormat::Jpeg) => {
5682 let mut fields = vec![
5683 ("jfif".to_owned(), ImageInfoValue::Integer(257)),
5684 (
5685 "jfif_version".to_owned(),
5686 ImageInfoValue::IntegerTuple(vec![1, 1]),
5687 ),
5688 ("jfif_unit".to_owned(), ImageInfoValue::Integer(0)),
5689 (
5690 "jfif_density".to_owned(),
5691 ImageInfoValue::IntegerTuple(vec![1, 1]),
5692 ),
5693 ];
5694 if self.exif_metadata().is_some() {
5699 fields.push(("dpi".to_owned(), ImageInfoValue::IntegerTuple(vec![72, 72])));
5700 }
5701 fields
5702 }
5703 Some(ImageFormat::Bmp) => vec![
5704 (
5705 "dpi".to_owned(),
5706 ImageInfoValue::FloatList(vec![96.01194815354799, 96.01194815354799]),
5707 ),
5708 ("compression".to_owned(), ImageInfoValue::Integer(0)),
5709 ],
5710 Some(ImageFormat::Gif) => vec![
5711 (
5712 "version".to_owned(),
5713 ImageInfoValue::Object(vec![
5714 (
5715 "kind".to_owned(),
5716 ImageInfoValue::String("bytes".to_owned()),
5717 ),
5718 (
5719 "encoding".to_owned(),
5720 ImageInfoValue::String("base64".to_owned()),
5721 ),
5722 (
5723 "data".to_owned(),
5724 ImageInfoValue::String("R0lGODdh".to_owned()),
5725 ),
5726 ]),
5727 ),
5728 ("background".to_owned(), ImageInfoValue::Integer(0)),
5729 ],
5730 Some(ImageFormat::Tiff) => vec![
5731 (
5732 "compression".to_owned(),
5733 ImageInfoValue::String("raw".to_owned()),
5734 ),
5735 ("dpi".to_owned(), ImageInfoValue::IntegerList(vec![1, 1])),
5736 (
5737 "resolution".to_owned(),
5738 ImageInfoValue::IntegerList(vec![1, 1]),
5739 ),
5740 ],
5741 Some(ImageFormat::WebP) => {
5742 let mut fields = vec![
5743 ("loop".to_owned(), ImageInfoValue::Integer(1)),
5744 (
5745 "background".to_owned(),
5746 ImageInfoValue::IntegerTuple(vec![255, 255, 255, 255]),
5747 ),
5748 ];
5749 if self.is_materialized() {
5750 fields.extend([
5751 ("timestamp".to_owned(), ImageInfoValue::Integer(0)),
5752 ("duration".to_owned(), ImageInfoValue::Integer(0)),
5753 ]);
5754 }
5755 fields
5756 }
5757 _ => Vec::new(),
5758 };
5759 if matches!(format, Some(ImageFormat::Jpeg))
5760 && let Some(exif) = self.exif_metadata()
5761 {
5762 fields.push(("exif".to_owned(), ImageInfoValue::Bytes(exif)));
5763 }
5764 if let Some(transparency) = self.pending_transparency_info() {
5765 fields.push(("transparency".to_owned(), transparency));
5766 }
5767 if self.explicit_mode() == Some("LAB")
5771 && let Some(profile) = self.pipeline_lab_icc_profile()
5772 {
5773 fields.push((
5774 "icc_profile".to_owned(),
5775 ImageInfoValue::Bytes(profile.to_vec()),
5776 ));
5777 }
5778 fields
5779 }
5780
5781 fn pipeline_lab_icc_profile(&self) -> Option<&[u8]> {
5782 match self {
5783 Image::Pipeline { source, ops, .. } => ops
5784 .iter()
5785 .rev()
5786 .find_map(|op| match op {
5787 PipelineOp::ConvertLab { icc_profile } => Some(icc_profile.as_ref()),
5788 _ => None,
5789 })
5790 .or_else(|| source.pipeline_lab_icc_profile()),
5791 _ => None,
5792 }
5793 }
5794
5795 pub fn converted_transparency_info(&self, target_mode: &str) -> Option<ImageInfoValue> {
5798 if matches!(target_mode, "LA" | "RGBA") && self.explicit_mode() == Some("PA") {
5799 return self.pending_transparency_info();
5800 }
5801 let transparency = self.converted_palette_transparency(target_mode)?;
5802 match transparency.as_slice() {
5803 [value] => Some(ImageInfoValue::Integer(i64::from(*value))),
5804 values => Some(ImageInfoValue::IntegerTuple(
5805 values.iter().map(|&value| i64::from(value)).collect(),
5806 )),
5807 }
5808 }
5809
5810 pub fn converted_compatibility_info(&self, target_mode: &str) -> Vec<(String, ImageInfoValue)> {
5813 self.converted_transparency_info(target_mode)
5814 .map(|value| vec![("transparency".to_owned(), value)])
5815 .unwrap_or_default()
5816 }
5817
5818 pub fn converted_palette_transparency(&self, target_mode: &str) -> Option<Vec<u8>> {
5826 if !matches!(target_mode, "L" | "RGB") {
5827 return None;
5828 }
5829 let index = match self.pending_palette_transparency()? {
5830 PaletteTransparency::Index(index) => index,
5831 PaletteTransparency::Table(_) => return None,
5832 };
5833 let palette = self.palette()?;
5834 let base = usize::from(index) * 3;
5835 let r = *palette.get(base)?;
5836 let g = *palette.get(base + 1)?;
5837 let b = *palette.get(base + 2)?;
5838 if target_mode == "RGB" {
5839 Some(vec![r, g, b])
5840 } else {
5841 let y = (19595u32 * u32::from(r)
5843 + 38470u32 * u32::from(g)
5844 + 7471u32 * u32::from(b)
5845 + 32768)
5846 >> 16;
5847 Some(vec![y.min(255) as u8])
5848 }
5849 }
5850
5851 pub fn palette_mode(&self) -> Option<&'static str> {
5853 (self.has_palette_mode() || self.explicit_mode() == Some("PA")).then(|| {
5854 if self.pending_palette_transparency().is_none()
5855 && self.palette_alpha().is_some_and(|alpha| !alpha.is_empty())
5856 {
5857 "RGBA"
5858 } else {
5859 "RGB"
5860 }
5861 })
5862 }
5863
5864 pub fn has_transparency_data(&self) -> bool {
5867 if self
5868 .mode()
5869 .is_ok_and(|mode| matches!(mode.as_str(), "LA" | "La" | "PA" | "RGBA" | "RGBa"))
5870 {
5871 return true;
5872 }
5873 self.pending_palette_transparency().is_some()
5874 || (self.has_palette_mode()
5875 && self.palette_alpha().is_some_and(|alpha| !alpha.is_empty()))
5876 }
5877
5878 pub fn apply_transparency(&mut self) -> Result<(), PilError> {
5892 let Some(pending) = self.pending_palette_transparency() else {
5893 return Ok(());
5894 };
5895 if !self.has_palette_mode() {
5896 return Ok(());
5897 }
5898
5899 let Some(palette) = self.palette() else {
5905 return Ok(());
5906 };
5907 let palette_entries = palette.len() / 3;
5910 let mut palette_alpha = self.palette_alpha().unwrap_or_default();
5911 palette_alpha.resize(palette_entries, 255);
5912 palette_alpha.truncate(palette_entries);
5913 match pending {
5914 PaletteTransparency::Index(index) => {
5915 if let Some(alpha) = palette_alpha.get_mut(usize::from(index)) {
5916 *alpha = 0;
5917 } else {
5918 return Err(PilError::IndexError(
5923 "list assignment index out of range".into(),
5924 ));
5925 }
5926 }
5927 PaletteTransparency::Table(table) => {
5928 for (index, value) in table.into_iter().enumerate() {
5929 let Some(alpha) = palette_alpha.get_mut(index) else {
5930 return Err(PilError::IndexError(
5935 "list assignment index out of range".into(),
5936 ));
5937 };
5938 *alpha = value;
5939 }
5940 }
5941 }
5942
5943 if let Image::Paletted(data) = self {
5944 data.palette_alpha = palette_alpha;
5945 clear_palette_info_alpha(&mut data.info);
5946 } else {
5947 let indices = self.materialize()?.to_luma8();
5948 let source_format = self.source_format();
5949 let mut info = self.image_info();
5950 clear_palette_info_alpha(&mut info);
5951 let exif = self.exif_metadata();
5952 *self = Image::Paletted(PalettedData {
5953 indices,
5954 palette,
5955 palette_alpha,
5956 source_format,
5957 info,
5958 exif,
5959 materialized: materialization_cache(),
5960 });
5961 }
5962 Ok(())
5963 }
5964
5965 pub fn get_child_images(&self) -> Vec<Image> {
5970 vec![]
5971 }
5972
5973 pub fn getexif(&self) -> Vec<u8> {
5980 match self {
5981 Image::Loaded(data) => data.exif.clone().unwrap_or_default(),
5982 Image::Paletted(data) => data.exif.clone().unwrap_or_default(),
5983 Image::Pipeline { source, .. } => source.getexif(),
5984 Image::Bytes { source, .. } => match source.info().format {
5985 ImageFormat::Jpeg => Self::extract_jpeg_exif(source.bytes()).unwrap_or_default(),
5986 ImageFormat::Tiff => {
5987 source.bytes().to_vec()
5991 }
5992 _ => Vec::new(),
5993 },
5994 }
5995 }
5996
5997 pub(crate) fn exif_metadata(&self) -> Option<Vec<u8>> {
6000 let exif = self.getexif();
6001 (!exif.is_empty()).then_some(exif)
6002 }
6003
6004 fn extract_jpeg_exif(data: &[u8]) -> Option<Vec<u8>> {
6011 if data.len() < 4 || data[0] != 0xFF || data[1] != 0xD8 {
6012 return None;
6013 }
6014 let mut offset = 2usize;
6015 while offset + 4 <= data.len() {
6016 if data[offset] != 0xFF {
6017 offset += 1;
6022 continue;
6023 }
6024 let marker = data[offset + 1];
6025 if marker == 0xD8 || (0xD0..=0xD7).contains(&marker) || marker == 0x01 {
6028 offset += 2;
6029 continue;
6030 }
6031 if marker == 0xD9 {
6032 return None;
6033 }
6034 if marker == 0xDA {
6039 return None;
6040 }
6041 let length = usize::from(u16::from_be_bytes([data[offset + 2], data[offset + 3]]));
6042 if length < 2 {
6043 return None;
6044 }
6045 let segment_end = offset + 2 + length;
6046 if segment_end > data.len() {
6047 return None;
6048 }
6049 if marker == 0xE1 {
6050 let payload = &data[offset + 4..segment_end];
6051 if payload.len() > 6 && payload.starts_with(b"Exif\x00\x00") {
6052 return Some(payload.to_vec());
6053 }
6054 return None;
6055 }
6056 offset = segment_end;
6057 }
6058 None
6059 }
6060
6061 pub fn getxmp(&self) -> std::collections::HashMap<String, String> {
6066 std::collections::HashMap::new()
6067 }
6068
6069 pub fn getim(&self) -> Option<u64> {
6075 None
6076 }
6077
6078 pub(crate) fn extract_palette(&self) -> Option<Vec<u8>> {
6080 match self {
6081 Image::Paletted(data) => Some(operational_palette(data)),
6082 Image::Loaded(data) => data.palette.clone(),
6083 Image::Pipeline { palette, .. } => palette.clone(),
6084 Image::Bytes { info, .. } => info
6085 .as_ref()
6086 .and_then(|info| info.palette.as_ref())
6087 .map(|palette| palette.rgb.clone()),
6088 }
6089 }
6090
6091 pub fn to_png_bytes(&self) -> Result<Vec<u8>, PilError> {
6100 let decoded = self.decoded_for_encoding()?;
6101 Ok(image_slash_star::encode_default(
6102 &decoded,
6103 ImageFormat::Png,
6104 )?)
6105 }
6106
6107 fn decoded_for_encoding(&self) -> Result<DecodedImage, PilError> {
6108 if let Image::Paletted(data) = self {
6109 let mut palette_bytes = operational_palette(data);
6110 if palette_bytes.len() < 768 {
6111 palette_bytes.resize(768, 0);
6114 }
6115 let palette = ImagePalette::new(palette_bytes, data.palette_alpha.clone())?;
6116 return Ok(DecodedImage::with_mode(
6117 data.indices.width(),
6118 data.indices.height(),
6119 data.indices.as_raw().to_vec(),
6120 ImageMode::P8,
6121 )
6122 .with_palette(palette));
6123 }
6124 if self.has_palette_mode() {
6125 let indices = self.materialize_indices()?.to_luma8();
6126 let mut palette = self.extract_palette().ok_or_else(|| {
6127 PilError::PaletteError("P-mode pipeline has no retained palette".to_owned())
6128 })?;
6129 if palette.len() < 768 {
6130 palette.resize(768, 0);
6131 }
6132 let alpha = self.palette_alpha().unwrap_or_default();
6133 return Ok(DecodedImage::with_mode(
6134 indices.width(),
6135 indices.height(),
6136 indices.into_raw(),
6137 ImageMode::P8,
6138 )
6139 .with_palette(ImagePalette::new(palette, alpha)?));
6140 }
6141 Ok(self.materialize()?.into_decoded())
6142 }
6143
6144 pub fn materialize_for_ops(&self) -> Result<DynamicImage, PilError> {
6154 if let Some(rgb) = self.paletted_to_rgb() {
6156 return Ok(rgb);
6157 }
6158 if matches!(self, Image::Pipeline { .. }) && self.explicit_mode() == Some("P") {
6160 let img = self.materialize()?; if let Some(palette) = self.palette() {
6162 let indices = img.to_luma8();
6163 let palette_alpha = self.palette_alpha().unwrap_or_default();
6164 return Ok(expand_palette(&indices, &palette, &palette_alpha));
6165 }
6166 }
6167 self.materialize()
6168 }
6169
6170 pub(crate) fn paletted_to_rgb(&self) -> Option<DynamicImage> {
6172 if let Image::Paletted(data) = self {
6173 Some(expand_palette(
6174 &data.indices,
6175 &data.palette,
6176 &data.palette_alpha,
6177 ))
6178 } else {
6179 None
6180 }
6181 }
6182
6183 pub fn size(&self) -> Result<(u32, u32), PilError> {
6190 match self {
6191 Image::Loaded(data) => return Ok(data.image.dimensions()),
6192 Image::Paletted(data) => return Ok(data.indices.dimensions()),
6193 Image::Bytes {
6194 info: Some(info), ..
6195 } => return Ok((info.width, info.height)),
6196 Image::Pipeline {
6197 source, ops, shape, ..
6198 } => {
6199 let planned = shape.get_or_init(|| {
6200 let mut dimensions = source.size()?;
6201 for op in ops.iter() {
6202 let Some(next) = known_pipeline_op_dimensions(op, dimensions) else {
6203 return Ok(None);
6204 };
6205 dimensions = next;
6206 }
6207 Ok(Some(dimensions))
6208 });
6209 if let Some(dimensions) = planned.as_ref().map_err(Clone::clone)? {
6210 return Ok(*dimensions);
6211 }
6212 }
6213 _ => {}
6214 }
6215 let img = self.materialized_shared()?;
6216 Ok((img.width(), img.height()))
6217 }
6218
6219 pub fn mode(&self) -> Result<String, PilError> {
6226 match self {
6227 Image::Paletted(_) => return Ok("P".to_owned()),
6228 Image::Loaded(data) => {
6229 return Ok(data
6230 .explicit_mode
6231 .clone()
6232 .unwrap_or_else(|| image_mode_name(data.decoded_mode).to_owned()));
6233 }
6234 Image::Bytes {
6235 info: Some(info), ..
6236 } => return Ok(image_mode_name(info.mode).to_owned()),
6237 Image::Pipeline {
6238 explicit_mode: Some(mode),
6239 ..
6240 } => return Ok(mode.clone()),
6241 Image::Pipeline {
6242 source,
6243 ops,
6244 explicit_mode: None,
6245 mode,
6246 ..
6247 } => {
6248 let planned = mode.get_or_init(|| {
6249 let mut current = source.mode()?;
6250 if ops.mode_preserving() {
6251 return Ok(Some(current));
6252 }
6253 for op in ops.iter() {
6254 let Some(next) = known_pipeline_op_mode(op, ¤t) else {
6255 return Ok(None);
6256 };
6257 current = next;
6258 }
6259 Ok(Some(current))
6260 });
6261 if let Some(mode) = planned.as_ref().map_err(Clone::clone)? {
6262 return Ok(mode.clone());
6263 }
6264 }
6265 _ => {}
6266 }
6267 let img = self.materialized_shared()?;
6268 Ok(self.mode_from_materialized(&img))
6269 }
6270
6271 pub(crate) fn mode_from_materialized(&self, image: &DynamicImage) -> String {
6278 match self {
6279 Image::Paletted(_) => "P".to_owned(),
6280 Image::Loaded(data) => data
6281 .explicit_mode
6282 .clone()
6283 .unwrap_or_else(|| image_mode_name(data.decoded_mode).to_owned()),
6284 Image::Bytes {
6285 info: Some(info), ..
6286 } => image_mode_name(info.mode).to_owned(),
6287 Image::Pipeline {
6288 explicit_mode: Some(mode),
6289 ..
6290 } => mode.clone(),
6291 _ => color_type_to_mode(image.color()).to_owned(),
6292 }
6293 }
6294
6295 pub fn format_name(&self) -> Option<String> {
6297 match self {
6298 Image::Loaded(data) => data.source_format.map(|format| format.as_str().to_owned()),
6299 Image::Paletted(data) => data.source_format.map(|format| format.as_str().to_owned()),
6300 Image::Bytes { format, .. } | Image::Pipeline { format, .. } => {
6301 format.map(|format| format.as_str().to_owned())
6302 }
6303 }
6304 }
6305
6306 pub fn load(&mut self) -> Result<(), PilError> {
6312 let loaded = match &*self {
6313 Image::Loaded(_) | Image::Paletted(_) => return Ok(()),
6314 Image::Bytes { format, info, .. } => image_from_materialized(
6315 self.materialized_shared()?,
6316 *format,
6317 info.clone(),
6318 self.exif_metadata(),
6319 )?,
6320 Image::Pipeline {
6321 source,
6322 explicit_mode,
6323 format,
6324 palette,
6325 palette_alpha,
6326 ..
6327 } => {
6328 if explicit_mode.as_deref() == Some("P") {
6329 if let Some(palette) = palette {
6330 let indices = self.materialized_shared()?.as_ref().clone().to_luma8();
6331 Image::Paletted(PalettedData {
6332 indices,
6333 palette: palette.clone(),
6334 palette_alpha: palette_alpha.clone().unwrap_or_default(),
6335 source_format: *format,
6336 info: source.image_info(),
6337 exif: source.exif_metadata(),
6338 materialized: materialization_cache(),
6339 })
6340 } else {
6341 return Err(PilError::PaletteError(
6342 "P-mode pipeline has no retained palette".to_owned(),
6343 ));
6344 }
6345 } else {
6346 let image = self.materialized_shared()?;
6347 let decoded_mode = image.color().into();
6348 Image::Loaded(LoadedData {
6349 image,
6350 known_zero_fill: false,
6351 explicit_mode: explicit_mode.clone(),
6352 decoded_mode,
6353 palette: palette.clone(),
6354 palette_alpha: palette_alpha.clone(),
6355 source_format: *format,
6356 info: source.image_info(),
6357 exif: source.exif_metadata(),
6358 })
6359 }
6360 }
6361 };
6362 *self = loaded;
6363 Ok(())
6364 }
6365
6366 pub(crate) fn with_exif_metadata(mut self, exif: Option<Vec<u8>>) -> Result<Self, PilError> {
6372 self.load()?;
6373 match &mut self {
6374 Image::Loaded(data) => data.exif = exif,
6375 Image::Paletted(data) => data.exif = exif,
6376 Image::Bytes { .. } | Image::Pipeline { .. } => {
6377 unreachable!("load must materialize EXIF metadata target")
6378 }
6379 }
6380 Ok(self)
6381 }
6382
6383 pub fn is_materialized(&self) -> bool {
6385 match self {
6386 Image::Loaded(_) | Image::Paletted(_) => true,
6387 Image::Bytes { materialized, .. } | Image::Pipeline { materialized, .. } => {
6388 matches!(materialized.get(), Some(Ok(_)))
6389 }
6390 }
6391 }
6392
6393 pub fn verify(&self) -> Result<(), PilError> {
6399 match self {
6400 Image::Bytes { source, .. } => source
6401 .verify()
6402 .map_err(|error| map_codec_error(error, "memory"))?,
6403 Image::Pipeline {
6404 source,
6405 ops,
6406 explicit_mode,
6407 backend,
6408 palette,
6409 palette_alpha,
6410 ..
6411 } => {
6412 Self::evaluate_pipeline_uncached(
6413 source,
6414 ops,
6415 explicit_mode,
6416 *backend,
6417 palette,
6418 palette_alpha,
6419 )?;
6420 }
6421 Image::Loaded(_) | Image::Paletted(_) => {}
6422 }
6423 Ok(())
6424 }
6425
6426 pub fn copy(&self) -> Self {
6428 let mut copy = self.clone();
6432 match &mut copy {
6433 Image::Loaded(data) => data.source_format = None,
6434 Image::Paletted(data) => data.source_format = None,
6435 Image::Bytes { format, .. } => *format = None,
6436 Image::Pipeline { format, .. } => *format = None,
6437 }
6438 copy
6439 }
6440
6441 pub fn getdata(&self, band: Option<i32>) -> Result<Vec<u8>, PilError> {
6451 let img = self.materialized_shared()?;
6452 if let Some(band) = band {
6453 let mode = self.mode_from_materialized(&img);
6457 let band_count = pillow_band_count(&mode);
6458 if band < 0 || band as usize >= band_count {
6459 return Err(PilError::ValueError("band index out of range".into()));
6460 }
6461 let band = band as usize;
6462 if mode == "LAB" {
6463 if let DynamicImage::ImageRgb8(image) = img.as_ref() {
6464 return Ok(select_lab_band(image.as_raw(), band));
6465 }
6466 return Ok(select_lab_band(img.to_rgb8().as_raw(), band));
6467 }
6468 match img.as_ref() {
6473 DynamicImage::ImageLuma8(image) if band == 0 => {
6474 return Ok(image.as_raw().clone());
6475 }
6476 DynamicImage::ImageLumaA8(image) if band < 2 => {
6477 return Ok(select_interleaved_band(image.as_raw(), 2, band));
6478 }
6479 DynamicImage::ImageRgb8(image) if band < 3 => {
6480 return Ok(select_interleaved_band(image.as_raw(), 3, band));
6481 }
6482 DynamicImage::ImageRgba8(image) if band < 4 => {
6483 return Ok(select_interleaved_band(image.as_raw(), 4, band));
6484 }
6485 _ => {}
6486 }
6487 let rgba = img.to_rgba8();
6488 return Ok(rgba.pixels().map(|p| p[band]).collect());
6489 }
6490 let mode = self.mode_from_materialized(&img);
6491 if mode == "LAB" {
6492 let mut data = img.to_rgb8().into_raw();
6493 for pixel in data.chunks_exact_mut(3) {
6494 pixel[1] = pixel[1].wrapping_sub(128);
6495 pixel[2] = pixel[2].wrapping_sub(128);
6496 }
6497 return Ok(data);
6498 }
6499 match img.color() {
6500 crate::raster::ColorType::L8 | crate::raster::ColorType::L16 => {
6501 let gray = img.to_luma8();
6502 Ok(gray.into_raw())
6503 }
6504 crate::raster::ColorType::La8 | crate::raster::ColorType::La16 => {
6505 let ga = img.to_luma_alpha8();
6506 let mut out = Vec::with_capacity((ga.width() * ga.height() * 2) as usize);
6507 for p in ga.pixels() {
6508 out.push(p[0]);
6509 out.push(p[1]);
6510 }
6511 Ok(out)
6512 }
6513 crate::raster::ColorType::Rgb8
6514 | crate::raster::ColorType::Rgb16
6515 | crate::raster::ColorType::Rgb32F => {
6516 let rgb = img.to_rgb8();
6517 Ok(rgb.into_raw())
6518 }
6519 _ => {
6520 let rgba = img.to_rgba8();
6521 Ok(rgba.into_raw())
6522 }
6523 }
6524 }
6525
6526 pub fn getdata_band_len(&self, band: i32) -> Result<usize, PilError> {
6540 let mode = self.mode()?;
6541 self.getdata_band_len_for_mode(&mode, band)
6542 }
6543
6544 fn getdata_band_len_for_mode(&self, mode: &str, band: i32) -> Result<usize, PilError> {
6545 if is_l16_mode(mode) || mode == "I" || mode == "F" {
6546 return Err(PilError::ValueError("image has wrong mode".into()));
6547 }
6548 let band_count = pillow_band_count(mode);
6549 if band < 0 || band as usize >= band_count {
6550 return Err(PilError::ValueError("band index out of range".into()));
6551 }
6552 let (width, height) = self.size()?;
6553 Ok(crate::checked_dims::CheckedDims::new_allow_empty(width, height, 1)?.total_pixels())
6554 }
6555
6556 pub fn getdata_band_view(&self, band: i32) -> Result<Option<&[u8]>, PilError> {
6564 if band != 0 {
6565 return Ok(None);
6566 }
6567 let requested_backend = match self.backend() {
6568 Some(backend) => Some(backend),
6569 None => crate::compute::preferred_active_backend()?.map(|(backend, _)| backend),
6570 };
6571 if requested_backend.is_some_and(|backend| backend != crate::compute::Backend::Cpu) {
6572 return Ok(None);
6573 }
6574 match self {
6575 Image::Paletted(data) => {
6576 crate::compute::record_eager_cpu_operation_receipt(
6577 "GetData",
6578 requested_backend,
6579 data.indices.as_raw().len(),
6580 );
6581 Ok(Some(data.indices.as_raw()))
6582 }
6583 Image::Loaded(data)
6586 if matches!(
6587 data.explicit_mode
6588 .as_deref()
6589 .unwrap_or_else(|| image_mode_name(data.decoded_mode)),
6590 "1" | "L"
6591 ) =>
6592 {
6593 let values: Option<&[u8]> = match data.image.as_ref() {
6594 DynamicImage::ImageLuma8(image) => Some(image.as_raw().as_slice()),
6595 _ => None,
6596 };
6597 if let Some(values) = values {
6598 crate::compute::record_eager_cpu_operation_receipt(
6599 "GetData",
6600 requested_backend,
6601 values.len(),
6602 );
6603 }
6604 Ok(values)
6605 }
6606 _ => Ok(None),
6607 }
6608 }
6609
6610 pub fn getdata_band_into(&self, band: i32, output: &mut [u8]) -> Result<(), PilError> {
6623 let mode_name = self.mode()?;
6624 let mode = mode_name.as_str();
6625 let expected = self.getdata_band_len_for_mode(mode, band)?;
6626 if output.len() != expected {
6627 return Err(PilError::InternalError(
6628 "getdata band output length mismatch".into(),
6629 ));
6630 }
6631 let selected_backend = match self.backend() {
6632 Some(backend) => Some(backend),
6633 None => crate::compute::preferred_active_backend()?.map(|(backend, _)| backend),
6634 };
6635 let backend_native = match selected_backend {
6636 Some(crate::compute::Backend::Simd) => matches!(
6637 mode,
6638 "LA" | "PA" | "RGB" | "RGBA" | "RGBa" | "RGBX" | "CMYK" | "HSV" | "YCbCr"
6639 ),
6640 Some(crate::compute::Backend::Gpu) => !matches!(mode, "P" | "LAB" | "I" | "F"),
6641 Some(crate::compute::Backend::Cpu) | None => false,
6642 };
6643 if backend_native
6644 && let Some(backend @ (crate::compute::Backend::Simd | crate::compute::Backend::Gpu)) =
6645 selected_backend
6646 {
6647 if backend == crate::compute::Backend::Simd && matches!(self, Image::Loaded(_)) {
6648 let image = self.materialized_shared()?;
6653 return crate::compute::execute_eager_simd_bytes(
6654 "GetData",
6655 image.as_ref(),
6656 output,
6657 |output| {
6658 crate::compute::simd_extract_band_into(
6659 image.as_ref(),
6660 band as u8,
6661 Some(mode),
6662 output,
6663 )
6664 },
6665 );
6666 }
6667
6668 let extracted = Image::push_op(self, PipelineOp::ExtractBand { index: band as u8 })
6674 .use_backend(backend);
6675 let image = extracted.materialized_shared()?;
6676 let values = image.as_bytes();
6677 if values.len() != output.len() {
6678 return Err(PilError::InternalError(
6679 "getdata band backend output length mismatch".into(),
6680 ));
6681 }
6682 output.copy_from_slice(values);
6683 return Ok(());
6684 }
6685
6686 let telemetry =
6687 crate::compute::begin_eager_cpu_operation_telemetry("GetData", selected_backend);
6688 let result = (|| {
6689 if let Image::Paletted(data) = self {
6690 output.copy_from_slice(data.indices.as_raw());
6691 return Ok(());
6692 }
6693
6694 let img = self.materialized_shared()?;
6695 let materialized_mode = self.mode_from_materialized(&img);
6696 let band = band as usize;
6697 if materialized_mode == "LAB" {
6698 if let DynamicImage::ImageRgb8(image) = img.as_ref() {
6699 select_lab_band_into(image.as_raw(), band, output);
6700 } else {
6701 select_lab_band_into(img.to_rgb8().as_raw(), band, output);
6702 }
6703 return Ok(());
6704 }
6705
6706 match img.as_ref() {
6707 DynamicImage::ImageLuma8(image) if band == 0 => {
6708 output.copy_from_slice(image.as_raw());
6709 return Ok(());
6710 }
6711 DynamicImage::ImageLumaA8(image) if band < 2 => {
6712 select_interleaved_band_into(image.as_raw(), 2, band, output);
6713 return Ok(());
6714 }
6715 DynamicImage::ImageRgb8(image) if band < 3 => {
6716 select_interleaved_band_into(image.as_raw(), 3, band, output);
6717 return Ok(());
6718 }
6719 DynamicImage::ImageRgba8(image) if band < 4 => {
6720 select_interleaved_band_into(image.as_raw(), 4, band, output);
6721 return Ok(());
6722 }
6723 _ => {}
6724 }
6725
6726 let rgba = img.to_rgba8();
6727 for (destination, pixel) in output.iter_mut().zip(rgba.pixels()) {
6728 *destination = pixel[band];
6729 }
6730 Ok(())
6731 })();
6732 if result.is_ok() {
6733 crate::compute::finish_eager_cpu_operation_telemetry(telemetry, output.len());
6734 } else {
6735 crate::compute::cancel_eager_cpu_operation_telemetry(telemetry);
6736 }
6737 result
6738 }
6739
6740 pub fn getdata_formatted(&self, band: Option<i32>) -> Result<FormattedImageData, PilError> {
6746 let mode = self.mode()?;
6747 if is_l16_mode(&mode) {
6748 if band.is_some() {
6749 return Err(PilError::ValueError("image has wrong mode".into()));
6753 }
6754 return Ok(FormattedImageData::IntegerScalars(
6755 self.materialized_shared()?
6756 .to_luma16()
6757 .as_raw()
6758 .iter()
6759 .copied()
6760 .map(i32::from)
6761 .collect(),
6762 ));
6763 }
6764 if mode == "I" || mode == "F" {
6765 if band.is_some() {
6766 return Err(PilError::ValueError("image has wrong mode".into()));
6767 }
6768 return Ok(match self.scalar_samples(&mode)? {
6769 ScalarImageSamples::Integer(values) => FormattedImageData::IntegerScalars(values),
6770 ScalarImageSamples::Float(values) => FormattedImageData::FloatScalars(values),
6771 });
6772 }
6773 let raw = self.getdata(band)?;
6774 if band.is_some() {
6775 return Ok(FormattedImageData::Scalars(raw));
6776 }
6777
6778 let band_count = pillow_band_count(&mode);
6779 if band_count == 1 {
6780 return Ok(FormattedImageData::Scalars(raw));
6781 }
6782
6783 Ok(FormattedImageData::Components(
6784 raw.chunks_exact(band_count)
6785 .map(|pixel| pixel.to_vec())
6786 .collect(),
6787 ))
6788 }
6789
6790 pub fn putdata(&mut self, data: &[u8]) -> Result<(), PilError> {
6800 let mode_name = self.mode()?;
6801 let mode = crate::pipeline::PixelMode::from_name(&mode_name).ok_or_else(|| {
6802 PilError::ValueError(format!("unsupported putdata mode: {mode_name}"))
6803 })?;
6804 let new_self = Image::push_op(
6805 self,
6806 PipelineOp::PutData {
6807 data: Bytes::copy_from_slice(data),
6808 mode,
6809 },
6810 );
6811 *self = new_self;
6812 Ok(())
6813 }
6814
6815 pub fn putdata_shared_bytes_fast_path(
6825 &mut self,
6826 data: Bytes,
6827 entry_count: usize,
6828 scale: f64,
6829 offset: f64,
6830 ) -> Result<bool, PilError> {
6831 if scale != 1.0 || offset != 0.0 || data.len() != entry_count {
6832 return Ok(false);
6833 }
6834 let mode_name = self.mode()?;
6835 if !matches!(mode_name.as_str(), "1" | "L" | "P") {
6836 return Ok(false);
6837 }
6838 self.validate_putdata_length(entry_count)?;
6839 let mode = PixelMode::from_name(&mode_name).ok_or_else(|| {
6840 PilError::ValueError(format!("unsupported putdata mode: {mode_name}"))
6841 })?;
6842 let new_self = Image::push_op(self, PipelineOp::PutData { data, mode });
6843 *self = new_self;
6844 Ok(true)
6845 }
6846
6847 pub fn putdata_values(
6860 &mut self,
6861 values: &[PutDataValue],
6862 scale: f64,
6863 offset: f64,
6864 ) -> Result<(), PilError> {
6865 self.validate_putdata_length(values.len())?;
6866
6867 let mode_name = self.mode()?;
6868 if is_l16_mode(&mode_name) {
6869 for (pixel_index, value) in values.iter().enumerate() {
6872 self.putdata_value_at(pixel_index, value, scale, offset)?;
6873 }
6874 return Ok(());
6875 }
6876 let mode = crate::pipeline::PixelMode::from_name(&mode_name).ok_or_else(|| {
6877 PilError::ValueError(format!("unsupported putdata mode: {mode_name}"))
6878 })?;
6879 let data = putdata_bytes(mode, values, scale, offset)?;
6880 self.putdata(&data)
6881 }
6882
6883 pub fn putdata_value_kind(&self) -> Result<PutDataValueKind, PilError> {
6889 let mode_name = self.mode()?;
6890 if matches!(
6891 mode_name.as_str(),
6892 "1" | "L" | "P" | "I" | "I;16" | "I;16L" | "I;16B" | "I;16N" | "F"
6893 ) {
6894 return Ok(PutDataValueKind::Numeric);
6895 }
6896 let mode = crate::pipeline::PixelMode::from_name(&mode_name).ok_or_else(|| {
6897 PilError::ValueError(format!("unsupported putdata mode: {mode_name}"))
6898 })?;
6899 Ok(PutDataValueKind::Components {
6900 channels: mode.channels(),
6901 })
6902 }
6903
6904 pub fn putdata_input(
6907 &mut self,
6908 input: PutDataInput<'_>,
6909 scale: f64,
6910 offset: f64,
6911 ) -> Result<(), PilError> {
6912 match input {
6913 PutDataInput::Integers(values) => self.putdata_integer_values(values, scale, offset),
6914 PutDataInput::Numbers(values) => self.putdata_numeric_values(values, scale, offset),
6915 }
6916 }
6917
6918 pub fn putdata_numeric_values(
6925 &mut self,
6926 values: &[f64],
6927 scale: f64,
6928 offset: f64,
6929 ) -> Result<(), PilError> {
6930 let values = values
6931 .iter()
6932 .copied()
6933 .map(PutDataValue::Number)
6934 .collect::<Vec<_>>();
6935 self.putdata_values(&values, scale, offset)
6936 }
6937
6938 pub fn putdata_integer_values(
6947 &mut self,
6948 values: &[i64],
6949 scale: f64,
6950 offset: f64,
6951 ) -> Result<(), PilError> {
6952 match self.putdata_value_kind()? {
6953 PutDataValueKind::Numeric => {
6954 let values = values
6955 .iter()
6956 .copied()
6957 .map(|value| PutDataValue::Number(value as f64))
6958 .collect::<Vec<_>>();
6959 self.putdata_values(&values, scale, offset)
6960 }
6961 PutDataValueKind::Components { .. } => {
6962 let values = values
6963 .iter()
6964 .copied()
6965 .map(PutDataValue::Packed)
6966 .collect::<Vec<_>>();
6967 self.putdata_values(&values, scale, offset)
6968 }
6969 }
6970 }
6971
6972 pub fn validate_putdata_length(&self, entry_count: usize) -> Result<(), PilError> {
6979 let (width, height) = self.size()?;
6980 let pixel_count = (width as usize)
6981 .checked_mul(height as usize)
6982 .ok_or_else(|| PilError::DimensionError("pixel count overflow".into()))?;
6983 if entry_count > pixel_count {
6984 return Err(PilError::TypeError("too many data entries".into()));
6985 }
6986 Ok(())
6987 }
6988
6989 pub fn putdata_bytes_fast_path(
6995 &mut self,
6996 data: &[u8],
6997 entry_count: usize,
6998 scale: f64,
6999 offset: f64,
7000 ) -> Result<bool, PilError> {
7001 let mode_name = self.mode()?;
7002 if is_l16_mode(&mode_name) {
7003 self.putdata_l16_bytes(data, scale, offset)?;
7004 return Ok(true);
7005 }
7006 if matches!(mode_name.as_str(), "1" | "L" | "P") {
7007 if scale == 1.0 && offset == 0.0 && data.len() == entry_count {
7008 self.putdata(data)?;
7012 return Ok(true);
7013 }
7014 let values = data
7015 .iter()
7016 .copied()
7017 .chain(std::iter::repeat(0))
7022 .take(entry_count)
7023 .map(|value| PutDataValue::Number(f64::from(value)))
7024 .collect::<Vec<_>>();
7025 self.putdata_values(&values, scale, offset)?;
7026 return Ok(true);
7027 }
7028 Ok(false)
7029 }
7030
7031 pub fn putdata_l16_bytes(
7040 &mut self,
7041 data: &[u8],
7042 scale: f64,
7043 offset: f64,
7044 ) -> Result<(), PilError> {
7045 self.validate_putdata_length(data.len())?;
7046 let (width, height) = self.size()?;
7047 let dimensions = CheckedDims::new(width, height, 2)?;
7048 let mode = self.mode()?;
7049 let mut raw = dimensions.alloc_buffer();
7050 let width = width as usize;
7051 let row_stride = width
7052 .checked_mul(2)
7053 .ok_or_else(|| PilError::DimensionError("putdata row stride overflow".into()))?;
7054 for (index, byte) in data.iter().copied().enumerate() {
7055 let row = index / width;
7056 let column = index % width;
7057 raw[row * row_stride + column] = if scale == 1.0 && offset == 0.0 {
7058 byte
7059 } else {
7060 putdata_clip_u8(f64::from(byte) * scale + offset)
7061 };
7062 }
7063 self.load()?;
7064 if let Image::Loaded(image_data) = self {
7065 let image = Arc::make_mut(&mut image_data.image);
7066 let destination = image
7067 .as_mut_luma16()
7068 .ok_or_else(|| PilError::InternalError("putdata I;16 storage mismatch".into()))?;
7069 for (pixel, sample) in destination.as_mut().iter_mut().zip(raw.chunks_exact(2)) {
7070 *pixel = if l16_uses_big_endian(&mode) {
7071 u16::from_be_bytes([sample[0], sample[1]])
7072 } else {
7073 u16::from_le_bytes([sample[0], sample[1]])
7074 };
7075 }
7076 image_data.known_zero_fill = false;
7077 return Ok(());
7078 }
7079 Err(PilError::InternalError(
7080 "putdata I;16 did not materialize writable storage".into(),
7081 ))
7082 }
7083
7084 pub fn putdata_value_at(
7101 &mut self,
7102 pixel_index: usize,
7103 value: &PutDataValue,
7104 scale: f64,
7105 offset: f64,
7106 ) -> Result<(), PilError> {
7107 let (width, height) = self.size()?;
7108 let pixel_count = (width as usize)
7109 .checked_mul(height as usize)
7110 .ok_or_else(|| PilError::DimensionError("pixel count overflow".into()))?;
7111 if pixel_index >= pixel_count {
7112 return Err(PilError::TypeError("too many data entries".into()));
7113 }
7114
7115 let mode_name = self.mode()?;
7116 if is_l16_mode(&mode_name) {
7117 let sample = putdata_l16_sample(value, scale, offset)?;
7118 self.load()?;
7119 if let Image::Loaded(data) = self {
7120 let image = Arc::make_mut(&mut data.image);
7121 let destination = image.as_mut_luma16().ok_or_else(|| {
7122 PilError::InternalError("putdata I;16 storage mismatch".into())
7123 })?;
7124 let pixel = destination.as_mut().get_mut(pixel_index).ok_or_else(|| {
7125 PilError::InternalError("putdata I;16 offset out of bounds".into())
7126 })?;
7127 *pixel = sample;
7128 data.known_zero_fill = false;
7129 return Ok(());
7130 }
7131 return Err(PilError::InternalError(
7132 "putdata I;16 did not materialize writable storage".into(),
7133 ));
7134 }
7135 let mode = crate::pipeline::PixelMode::from_name(&mode_name).ok_or_else(|| {
7136 PilError::ValueError(format!("unsupported putdata mode: {mode_name}"))
7137 })?;
7138 let bytes = putdata_bytes(mode, std::slice::from_ref(value), scale, offset)?;
7139 let start = pixel_index
7140 .checked_mul(mode.channels())
7141 .ok_or_else(|| PilError::DimensionError("putdata byte offset overflow".into()))?;
7142 let end = start
7143 .checked_add(bytes.len())
7144 .ok_or_else(|| PilError::DimensionError("putdata byte offset overflow".into()))?;
7145
7146 self.load()?;
7147 match self {
7148 Image::Paletted(data) if mode == crate::pipeline::PixelMode::P => {
7149 data.indices.as_mut()[pixel_index] = bytes[0];
7150 data.materialized = materialization_cache();
7151 }
7152 Image::Loaded(data) => {
7153 let image = Arc::make_mut(&mut data.image);
7154 let samples: &mut [u8] = match mode {
7155 crate::pipeline::PixelMode::Mode1
7156 | crate::pipeline::PixelMode::L
7157 | crate::pipeline::PixelMode::P => image
7158 .as_mut_luma8()
7159 .ok_or_else(|| {
7160 PilError::InternalError("putdata L storage mismatch".into())
7161 })?
7162 .as_mut(),
7163 crate::pipeline::PixelMode::LA | crate::pipeline::PixelMode::PA => image
7164 .as_mut_luma_alpha8()
7165 .ok_or_else(|| {
7166 PilError::InternalError("putdata LA storage mismatch".into())
7167 })?
7168 .as_mut(),
7169 crate::pipeline::PixelMode::RGB
7170 | crate::pipeline::PixelMode::YCbCr
7171 | crate::pipeline::PixelMode::HSV => image
7172 .as_mut_rgb8()
7173 .ok_or_else(|| {
7174 PilError::InternalError("putdata RGB storage mismatch".into())
7175 })?
7176 .as_mut(),
7177 crate::pipeline::PixelMode::RGBA
7178 | crate::pipeline::PixelMode::CMYK
7179 | crate::pipeline::PixelMode::I
7180 | crate::pipeline::PixelMode::F => image
7181 .as_mut_rgba8()
7182 .ok_or_else(|| {
7183 PilError::InternalError("putdata RGBA storage mismatch".into())
7184 })?
7185 .as_mut(),
7186 };
7187 let destination = samples.get_mut(start..end).ok_or_else(|| {
7188 PilError::InternalError("putdata storage offset out of bounds".into())
7189 })?;
7190 destination.copy_from_slice(&bytes);
7191 data.known_zero_fill = false;
7192 }
7193 _ => {
7194 return Err(PilError::InternalError(
7195 "putdata did not materialize writable storage".into(),
7196 ));
7197 }
7198 }
7199 Ok(())
7200 }
7201
7202 pub(crate) fn try_grayscale_eager_rgb(&self) -> Result<Option<Image>, PilError> {
7205 if cfg!(feature = "parallel") {
7206 return Ok(None);
7207 }
7208 let Image::Loaded(data) = self else {
7209 return Ok(None);
7210 };
7211 let logical_mode = data
7212 .explicit_mode
7213 .as_deref()
7214 .unwrap_or_else(|| image_mode_name(data.decoded_mode));
7215 if logical_mode != "RGB" {
7216 return Ok(None);
7217 }
7218
7219 let image = self.materialized_shared()?;
7220 if !matches!(image.as_ref(), DynamicImage::ImageRgb8(_)) {
7221 return Ok(None);
7222 }
7223 let dims =
7224 crate::checked_dims::CheckedDims::new_allow_empty(image.width(), image.height(), 3)?;
7225 let pixels = dims.total_pixels();
7226 if pixels == 0 || pixels > 256 || image.as_bytes().len() != dims.total_bytes() {
7227 return Ok(None);
7228 }
7229
7230 let Some((backend, _)) = crate::compute::preferred_active_backend()? else {
7231 return Ok(None);
7232 };
7233 let operation = PipelineOp::Grayscale;
7234 let grayscale = match backend {
7235 crate::compute::Backend::Cpu => crate::compute::execute_eager_cpu_image_operation(
7236 "Grayscale",
7237 image.as_ref(),
7238 false,
7239 || crate::compute::registry::execute_cpu(&operation, image.as_ref(), Some("RGB")),
7240 )?,
7241 crate::compute::Backend::Simd => crate::compute::execute_eager_simd_image_operation(
7242 "Grayscale",
7243 image.as_ref(),
7244 || {
7245 crate::compute::simd_grayscale_with_evidence(
7246 image.as_ref(),
7247 &operation,
7248 Some("RGB"),
7249 )
7250 },
7251 )?,
7252 crate::compute::Backend::Gpu => return Ok(None),
7253 };
7254
7255 let mut result = Image::from_dynamic(grayscale, None);
7256 if let Image::Loaded(data) = &mut result {
7257 data.info = self.image_info();
7258 data.exif = self.exif_metadata();
7259 }
7260 Ok(Some(result))
7261 }
7262
7263 pub fn getchannel(&self, channel: i32) -> Result<Image, PilError> {
7270 let mode = self.mode()?;
7271 if matches!(mode.as_str(), "I" | "F") {
7275 return Err(PilError::ValueError("image has wrong mode".into()));
7276 }
7277 let img = self.materialized_shared()?;
7279 let bands = img.color().channel_count();
7280 if channel < 0 || channel >= bands as i32 {
7281 return Err(PilError::ValueError("band index out of range".into()));
7282 }
7283 let ch = channel as usize;
7284 if self.has_palette_mode() {
7291 return Ok(self.copy());
7292 }
7293 if mode == "L" && ch == 0 && matches!(self, Image::Loaded(_)) && !cfg!(feature = "parallel")
7300 {
7301 if let Some((crate::compute::Backend::Cpu, _)) =
7302 crate::compute::preferred_active_backend()?
7303 {
7304 let pixel_count = crate::checked_dims::CheckedDims::new_allow_empty(
7305 img.width(),
7306 img.height(),
7307 1,
7308 )?
7309 .total_pixels();
7310 if img.as_bytes().len() == pixel_count {
7311 return crate::compute::execute_eager_cpu_shared_result(
7312 "ExtractBand",
7313 img.as_ref(),
7314 || Ok(self.copy()),
7315 );
7316 }
7317 }
7318 }
7319 if matches!(self, Image::Loaded(_))
7324 && !cfg!(feature = "parallel")
7325 && mode == "RGB"
7326 && u64::from(img.width()) * u64::from(img.height()) <= 256
7327 {
7328 if let Some((backend, _)) = crate::compute::preferred_active_backend()? {
7329 let operation = PipelineOp::ExtractBand { index: ch as u8 };
7330 let extracted = match backend {
7331 crate::compute::Backend::Cpu => {
7332 Some(crate::compute::execute_eager_cpu_image_operation(
7333 "ExtractBand",
7334 img.as_ref(),
7335 false,
7338 || {
7339 crate::compute::registry::execute_cpu(
7340 &operation,
7341 img.as_ref(),
7342 Some(&mode),
7343 )
7344 },
7345 )?)
7346 }
7347 crate::compute::Backend::Simd => {
7348 Some(crate::compute::execute_eager_simd_image_operation(
7349 "ExtractBand",
7350 img.as_ref(),
7351 || {
7352 let (width, height) = img.dimensions();
7353 let mut output = crate::checked_dims::CheckedDims::new_allow_empty(
7354 width, height, 1,
7355 )?
7356 .alloc_buffer();
7357 let (vector_blocks, scalar_tail, path) =
7358 crate::compute::simd_extract_band_into(
7359 img.as_ref(),
7360 ch as u8,
7361 Some(&mode),
7362 &mut output,
7363 )?;
7364 let output =
7365 crate::raster::GrayImage::from_raw(width, height, output)
7366 .ok_or_else(|| {
7367 PilError::InternalError(
7368 "SIMD ExtractBand buffer shape mismatch".into(),
7369 )
7370 })?;
7371 Ok((
7372 DynamicImage::ImageLuma8(output),
7373 vector_blocks,
7374 scalar_tail,
7375 path,
7376 ))
7377 },
7378 )?)
7379 }
7380 crate::compute::Backend::Gpu => None,
7381 };
7382 if let Some(extracted) = extracted {
7383 let mut result = Image::from_dynamic(extracted, None);
7384 if let Image::Loaded(data) = &mut result {
7385 data.info = self.image_info();
7386 data.exif = self.exif_metadata();
7387 }
7388 return Ok(result);
7389 }
7390 }
7391 }
7392 let extraction_source =
7396 if matches!(self, Image::Pipeline { .. }) && !self.has_palette_samples() {
7397 self.materialized_branch()?
7398 } else {
7399 self.clone()
7400 };
7401 let extracted = Image::push_op(
7402 &extraction_source,
7403 PipelineOp::ExtractBand { index: ch as u8 },
7404 );
7405 Ok(match self.backend() {
7406 Some(backend) => extracted.use_backend(backend),
7407 None => extracted,
7408 })
7409 }
7410
7411 pub fn getchannel_selector(&self, selector: ChannelSelector) -> Result<Image, PilError> {
7413 let channel = match selector {
7414 ChannelSelector::Index(channel) => channel,
7415 ChannelSelector::Name(name) => {
7416 let bands = self.getbands()?;
7417 bands.iter().position(|band| band == &name).map_or_else(
7418 || {
7419 Err(PilError::ValueError(format!(
7420 "The image has no channel \"{name}\""
7421 )))
7422 },
7423 |index| Ok(index as i32),
7424 )?
7425 }
7426 ChannelSelector::Invalid(type_name) => {
7427 return Err(PilError::TypeError(format!(
7428 "'{type_name}' object cannot be interpreted as an integer"
7429 )));
7430 }
7431 };
7432 self.getchannel(channel)
7433 }
7434
7435 pub fn putalpha(&mut self, alpha: u8) -> Result<(), PilError> {
7445 let mode_name = self.mode()?;
7446 if let Some(target) = putalpha_conversion_target(&mode_name) {
7447 return Err(PilError::ValueError(format!(
7451 "conversion from {mode_name} to {target} not supported"
7452 )));
7453 }
7454 let mode = crate::pipeline::PixelMode::from_name(&mode_name).ok_or_else(|| {
7455 PilError::ValueError(format!("unsupported putalpha mode: {mode_name}"))
7456 })?;
7457 let new_self = Image::push_op(self, PipelineOp::PutAlpha { alpha, mode });
7458 *self = new_self;
7459 Ok(())
7460 }
7461
7462 pub fn putalpha_with_input(&mut self, input: PutAlphaInput) -> Result<(), PilError> {
7464 match input {
7465 PutAlphaInput::Integer(value) => self.putalpha(value.clamp(0, 255) as u8),
7466 PutAlphaInput::Image(mask) => self.putalpha_data(&mask),
7467 PutAlphaInput::Invalid(type_name) => Err(PilError::TypeError(format!(
7468 "'{type_name}' object cannot be interpreted as an integer"
7469 ))),
7470 }
7471 }
7472
7473 pub fn putalpha_data(&mut self, mask: &Image) -> Result<(), PilError> {
7476 let mask_img = mask.materialize()?;
7477 let mask_mode = mask.mode()?;
7478 if mask_mode != "1" && mask_mode != "L" {
7479 return Err(PilError::ValueError("illegal image mode".into()));
7480 }
7481 if (mask_img.width(), mask_img.height()) != (self.size()?.0, self.size()?.1) {
7482 return Err(PilError::ValueError("images do not match".into()));
7483 }
7484 let mask_luma = mask_img.to_luma8();
7485 let mode_name = self.mode()?;
7486 if let Some(target) = putalpha_conversion_target(&mode_name) {
7487 return Err(PilError::ValueError(format!(
7491 "conversion from {mode_name} to {target} not supported"
7492 )));
7493 }
7494 let mode = crate::pipeline::PixelMode::from_name(&mode_name).ok_or_else(|| {
7495 PilError::ValueError(format!("unsupported putalpha mode: {mode_name}"))
7496 })?;
7497 let new_self = Image::push_op(
7498 self,
7499 PipelineOp::PutAlphaData {
7500 mask: Arc::new(crate::raster::DynamicImage::ImageLuma8(mask_luma)),
7501 mode,
7502 },
7503 );
7504 *self = new_self;
7505 Ok(())
7506 }
7507
7508 #[allow(clippy::type_complexity)]
7520 pub fn getcolors(
7521 &self,
7522 maxcolors: u32,
7523 ) -> Result<Option<Vec<(u32, FormattedPixelValue)>>, PilError> {
7524 let eager_receipt_eligible =
7529 crate::compute::Backend::pipeline_telemetry_enabled() && self.is_materialized();
7530 let mode = self.mode()?;
7531 if is_l16_mode(&mode) {
7532 return Err(PilError::ValueError("image has wrong mode".into()));
7535 }
7536 let img = self.materialized_shared()?;
7537 if mode == "I" || mode == "F" {
7538 let telemetry = if eager_receipt_eligible {
7539 match crate::compute::preferred_active_backend() {
7540 Ok(selected) => Some(crate::compute::begin_eager_cpu_operation_telemetry(
7541 "GetColors",
7542 selected.map(|(backend, _)| backend),
7543 )),
7544 Err(_) => None,
7545 }
7546 } else {
7547 None
7548 };
7549 let result = Self::getcolors_scalar(maxcolors, &mode, &img);
7550 if let Some(telemetry) = telemetry {
7551 if result.is_ok() {
7552 crate::compute::finish_eager_cpu_operation_telemetry(telemetry, 0);
7553 } else {
7554 crate::compute::cancel_eager_cpu_operation_telemetry(telemetry);
7555 }
7556 }
7557 return result;
7558 }
7559 if mode == "1" || mode == "L" || mode == "P" {
7561 return Self::getcolors_histogram(maxcolors, &img);
7562 }
7563 let n_bands = match img.color() {
7565 crate::raster::ColorType::La8 | crate::raster::ColorType::La16 => 2,
7566 crate::raster::ColorType::Rgb8 | crate::raster::ColorType::Rgb16 => 3,
7567 _ => 4,
7568 };
7569 let (code_mask, code_polynomial) = pillow_color_table_parameters(maxcolors)
7570 .ok_or_else(|| PilError::MemoryError(String::new()))?;
7571 let max_distinct_colors = maxcolors as usize;
7575 let initial_capacity = if maxcolors <= 256 && img.as_bytes().len() >= 64 * 1024 {
7578 max_distinct_colors + 1
7579 } else {
7580 0
7581 };
7582 let pixel_count = pillow_image_pixel_count(img.as_ref());
7583 if maxcolors > 1023 && pixel_count >= 64 * 1024 {
7584 if let DynamicImage::ImageRgb8(rgb) = img.as_ref() {
7585 match getcolors_rgb8_grayscale(rgb, max_distinct_colors, code_mask, code_polynomial)
7586 {
7587 RgbGrayscaleColorCounts::NotGrayscale => {}
7588 RgbGrayscaleColorCounts::TooManyColors => return Ok(None),
7589 RgbGrayscaleColorCounts::Colors(result) => return Ok(Some(result)),
7590 }
7591 }
7592 }
7593 let mut counts = PillowColorCounts::new(code_mask, initial_capacity, pixel_count);
7594 let mut distinct_colors = 0usize;
7595 let mut count_pixel = |pixel: u32| {
7596 counts.count(
7597 &mut distinct_colors,
7598 pixel,
7599 max_distinct_colors,
7600 code_mask,
7601 code_polynomial,
7602 )
7603 };
7604 match (n_bands, img.as_ref()) {
7605 (2, crate::raster::DynamicImage::ImageLumaA8(image)) => {
7606 for pixel in image.pixels() {
7607 if !count_pixel(pillow_color_pixel(&pixel.0)) {
7608 return Ok(None);
7609 }
7610 }
7611 }
7612 (3, crate::raster::DynamicImage::ImageRgb8(image)) => {
7613 for pixel in image.pixels() {
7614 if !count_pixel(pillow_color_pixel(&pixel.0)) {
7615 return Ok(None);
7616 }
7617 }
7618 }
7619 (4, crate::raster::DynamicImage::ImageRgba8(image)) => {
7620 for pixel in image.pixels() {
7621 if !count_pixel(pillow_color_pixel(&pixel.0)) {
7622 return Ok(None);
7623 }
7624 }
7625 }
7626 (2, _) => {
7627 let la = img.to_luma_alpha8();
7628 for pixel in la.pixels() {
7629 if !count_pixel(pillow_color_pixel(&pixel.0)) {
7630 return Ok(None);
7631 }
7632 }
7633 }
7634 (3, _) => {
7635 let rgb = img.to_rgb8();
7636 for pixel in rgb.pixels() {
7637 if !count_pixel(pillow_color_pixel(&pixel.0)) {
7638 return Ok(None);
7639 }
7640 }
7641 }
7642 (4, _) => {
7643 let rgba = img.to_rgba8();
7644 for pixel in rgba.pixels() {
7645 if !count_pixel(pillow_color_pixel(&pixel.0)) {
7646 return Ok(None);
7647 }
7648 }
7649 }
7650 _ => unreachable!("getcolors only supports one through four bands"),
7651 }
7652 let result = counts.into_slot_order(distinct_colors);
7653 Ok(Some(
7654 result
7655 .into_iter()
7656 .map(|(_, (pixel, count))| (count, pillow_color_components(pixel, n_bands)))
7657 .collect(),
7658 ))
7659 }
7660
7661 pub fn getcolors_with_signed_limit(
7664 &self,
7665 maxcolors: i32,
7666 ) -> Result<Option<Vec<(u32, FormattedPixelValue)>>, PilError> {
7667 if maxcolors >= 0 {
7668 return self.getcolors(maxcolors as u32);
7669 }
7670 let mode = self.mode()?;
7671 if is_l16_mode(&mode) {
7672 return Err(PilError::ValueError("image has wrong mode".into()));
7673 }
7674 self.materialized_shared()?;
7675 Ok(None)
7676 }
7677
7678 pub fn getcolors_formatted(
7684 &self,
7685 maxcolors: u32,
7686 ) -> Result<Option<Vec<(u32, FormattedPixelValue)>>, PilError> {
7687 self.getcolors(maxcolors)
7688 }
7689
7690 pub fn getcolors_formatted_with_signed_limit(
7692 &self,
7693 maxcolors: i32,
7694 ) -> Result<Option<Vec<(u32, FormattedPixelValue)>>, PilError> {
7695 self.getcolors_with_signed_limit(maxcolors)
7696 }
7697
7698 pub fn getextrema_formatted(&self) -> Result<FormattedExtrema, PilError> {
7700 let (width, height) = self.size()?;
7701 if width == 0 || height == 0 {
7702 let bands = pillow_band_count(&self.mode()?);
7703 return Ok(if bands == 1 {
7704 FormattedExtrema::Empty
7705 } else {
7706 FormattedExtrema::EmptyMultiple(bands)
7707 });
7708 }
7709
7710 let mode = self.mode()?;
7711 if mode == "I" {
7712 let image = self.materialized_shared()?;
7713 let (minimum, maximum) = image
7714 .as_bytes()
7715 .chunks_exact(4)
7716 .map(|sample| i32::from_le_bytes([sample[0], sample[1], sample[2], sample[3]]))
7717 .fold(None, |extrema: Option<(i32, i32)>, value| {
7718 Some(match extrema {
7719 Some((minimum, maximum)) => (minimum.min(value), maximum.max(value)),
7720 None => (value, value),
7721 })
7722 })
7723 .ok_or_else(|| PilError::InternalError("I image has no scalar samples".into()))?;
7724 return Ok(FormattedExtrema::Integer((minimum, maximum)));
7725 }
7726 if matches!(mode.as_str(), "I;16L" | "I;16B" | "I;16N") {
7727 return Err(PilError::ValueError("image has wrong mode".into()));
7731 }
7732 if is_l16_mode(&mode) {
7733 let image = self.materialized_shared()?;
7734 let luma = image.to_luma16();
7735 let values = luma.as_raw().iter().copied().map(i32::from);
7736 let (minimum, maximum) = values
7737 .fold(None, |extrema: Option<(i32, i32)>, value| {
7738 Some(match extrema {
7739 Some((minimum, maximum)) => (minimum.min(value), maximum.max(value)),
7740 None => (value, value),
7741 })
7742 })
7743 .ok_or_else(|| PilError::InternalError("I;16 image has no samples".into()))?;
7744 return Ok(FormattedExtrema::Integer((minimum, maximum)));
7745 }
7746 if mode == "F" {
7747 let image = self.materialized_shared()?;
7748 let (minimum, maximum) = image
7749 .as_bytes()
7750 .chunks_exact(4)
7751 .map(|sample| {
7752 f32::from_le_bytes([sample[0], sample[1], sample[2], sample[3]]) as f64
7753 })
7754 .fold(None, |extrema: Option<(f64, f64)>, value| {
7755 Some(match extrema {
7756 Some((minimum, maximum)) => (minimum.min(value), maximum.max(value)),
7757 None => (value, value),
7758 })
7759 })
7760 .ok_or_else(|| PilError::InternalError("F image has no scalar samples".into()))?;
7761 return Ok(FormattedExtrema::Float((minimum, maximum)));
7762 }
7763
7764 let extrema = self.getextrema()?;
7765 if extrema.len() == 1 {
7766 Ok(FormattedExtrema::Single(extrema[0]))
7767 } else {
7768 Ok(FormattedExtrema::Multiple(extrema))
7769 }
7770 }
7771
7772 fn getcolors_histogram(
7777 maxcolors: u32,
7778 img: &DynamicImage,
7779 ) -> Result<Option<Vec<(u32, FormattedPixelValue)>>, PilError> {
7780 let mut hist = [0u32; 256];
7785 let luma = img.to_luma8();
7786 let max_distinct_colors = maxcolors as usize;
7787 let mut distinct_colors = 0usize;
7788 for p in luma.pixels() {
7789 let count = &mut hist[p[0] as usize];
7790 if *count == 0 {
7791 distinct_colors += 1;
7792 if distinct_colors > max_distinct_colors {
7793 return Ok(None);
7794 }
7795 }
7796 *count += 1;
7797 }
7798 let result: Vec<(u32, FormattedPixelValue)> = (0..=255u8)
7800 .filter(|&i| hist[i as usize] > 0)
7801 .map(|i| (hist[i as usize], FormattedPixelValue::Scalar(i)))
7802 .collect();
7803 if result.len() > maxcolors as usize {
7804 return Ok(None);
7805 }
7806 Ok(Some(result))
7807 }
7808
7809 fn getcolors_scalar(
7812 maxcolors: u32,
7813 mode: &str,
7814 img: &DynamicImage,
7815 ) -> Result<Option<Vec<(u32, FormattedPixelValue)>>, PilError> {
7816 let (code_mask, code_polynomial) = pillow_color_table_parameters(maxcolors)
7817 .ok_or_else(|| PilError::MemoryError(String::new()))?;
7818 let max_distinct_colors = maxcolors as usize;
7819 let bytes = img.as_bytes();
7820 let pixel_count = pillow_image_pixel_count(img);
7821 let has_repeated_prefix = if mode == "I" {
7822 scalar_i_prefix_has_long_run(bytes)
7823 } else {
7824 scalar_prefix_has_repeated_samples(bytes)
7825 };
7826 let direct_table_slots = pillow_color_direct_table_slots(code_mask, pixel_count);
7827 if mode == "I"
7828 && pixel_count >= 4096
7829 && has_repeated_prefix
7830 && direct_table_slots
7831 .is_some_and(|slots| slots > SCALAR_I_REPEATED_RUN_MIN_DIRECT_SLOTS)
7832 && scalar_byte_domain_is_plausible("I", bytes)
7833 {
7834 match getcolors_scalar_i_repeated_runs(
7835 bytes,
7836 max_distinct_colors,
7837 code_mask,
7838 code_polynomial,
7839 ) {
7840 ScalarColorDomainCounts::NotApplicable => {}
7841 ScalarColorDomainCounts::TooManyColors => return Ok(None),
7842 ScalarColorDomainCounts::Colors(colors) => return Ok(Some(colors)),
7843 }
7844 }
7845 if pixel_count >= 4096
7846 && !has_repeated_prefix
7847 && scalar_byte_domain_is_plausible(mode, bytes)
7848 {
7849 match getcolors_scalar_byte_domain(
7850 mode,
7851 bytes,
7852 max_distinct_colors,
7853 code_mask,
7854 code_polynomial,
7855 ) {
7856 ScalarColorDomainCounts::NotApplicable => {}
7857 ScalarColorDomainCounts::TooManyColors => return Ok(None),
7858 ScalarColorDomainCounts::Colors(colors) => return Ok(Some(colors)),
7859 }
7860 }
7861 let initial_capacity = if maxcolors <= 256 && bytes.len() >= 64 * 1024 {
7862 max_distinct_colors + 1
7863 } else {
7864 0
7865 };
7866 let mut counts = PillowColorCounts::new(code_mask, initial_capacity, pixel_count);
7867 let mut distinct_colors = 0usize;
7868 if has_repeated_prefix {
7869 let mut samples = bytes.chunks_exact(4).peekable();
7870 while let Some(sample) = samples.next() {
7871 let pixel = u32::from_ne_bytes([sample[0], sample[1], sample[2], sample[3]]);
7872 let mut repetitions = 1usize;
7873 while let Some(next) = samples.peek() {
7874 if *next != sample {
7875 break;
7876 }
7877 samples.next();
7878 repetitions += 1;
7879 }
7880
7881 if repetitions == 1 {
7882 if !counts.count(
7883 &mut distinct_colors,
7884 pixel,
7885 max_distinct_colors,
7886 code_mask,
7887 code_polynomial,
7888 ) {
7889 return Ok(None);
7890 }
7891 continue;
7892 }
7893
7894 match counts.count_repeated(
7895 &mut distinct_colors,
7896 pixel,
7897 repetitions,
7898 max_distinct_colors,
7899 code_mask,
7900 code_polynomial,
7901 ) {
7902 Some(true) => {}
7903 Some(false) => return Ok(None),
7904 None => {
7905 for _ in 0..repetitions {
7906 if !counts.count(
7907 &mut distinct_colors,
7908 pixel,
7909 max_distinct_colors,
7910 code_mask,
7911 code_polynomial,
7912 ) {
7913 return Ok(None);
7914 }
7915 }
7916 }
7917 }
7918 }
7919 } else {
7920 if !count_pillow_color_scalar_samples(
7921 &mut counts,
7922 &mut distinct_colors,
7923 bytes,
7924 max_distinct_colors,
7925 code_mask,
7926 code_polynomial,
7927 ) {
7928 return Ok(None);
7929 }
7930 }
7931 let result = counts.into_slot_order(distinct_colors);
7932 Ok(Some(
7933 result
7934 .into_iter()
7935 .map(|(_, (pixel, count))| {
7936 let value = if mode == "I" {
7937 FormattedPixelValue::Integer(i32::from_ne_bytes(pixel.to_ne_bytes()))
7938 } else {
7939 FormattedPixelValue::Float(f32::from_bits(pixel) as f64)
7940 };
7941 (count, value)
7942 })
7943 .collect(),
7944 ))
7945 }
7946
7947 pub(crate) fn scalar_samples(&self, mode: &str) -> Result<ScalarImageSamples, PilError> {
7949 if mode == "I" {
7950 return self
7951 .read_scalar_storage(mode, decode_integer_samples)
7952 .map(ScalarImageSamples::Integer);
7953 }
7954 self.read_scalar_storage(mode, decode_float_samples)
7955 .map(ScalarImageSamples::Float)
7956 }
7957
7958 fn read_scalar_storage<T>(
7959 &self,
7960 mode: &str,
7961 decode: impl FnOnce(&[u8]) -> T,
7962 ) -> Result<T, PilError> {
7963 let img = self.materialized_shared()?;
7964 let expected = CheckedDims::new(img.width(), img.height(), 4)?.total_bytes();
7965 let raw = img.as_bytes();
7966 if raw.len() != expected {
7967 return Err(PilError::InternalError(format!(
7968 "{mode} image has invalid scalar storage"
7969 )));
7970 }
7971 Ok(decode(raw))
7972 }
7973
7974 pub fn entropy(&self) -> Result<f64, PilError> {
7980 self.entropy_with_mask(None)
7981 }
7982
7983 pub fn entropy_with_mask(&self, mask: Option<&Image>) -> Result<f64, PilError> {
7986 let img = self.materialized_shared()?;
7987 let mask_image = if let Some(mask) = mask {
7988 let mask_image = mask.materialized_shared()?;
7989 if (mask_image.width(), mask_image.height()) != (img.width(), img.height()) {
7990 return Err(PilError::ValueError("images do not match".into()));
7991 }
7992 let mode = mask.mode()?;
7993 if mode != "1" && mode != "L" {
7994 return Err(PilError::ValueError("bad transparency mask".into()));
7995 }
7996 Some(mask_image)
7997 } else {
7998 None
7999 };
8000 let owned_mask_luma =
8003 mask_image
8004 .as_ref()
8005 .and_then(|mask_image| match mask_image.as_ref() {
8006 crate::raster::DynamicImage::ImageLuma8(_) => None,
8007 _ => Some(mask_image.to_luma8().into_raw()),
8008 });
8009 let mask_raw: Option<&[u8]> = match (&mask_image, &owned_mask_luma) {
8010 (Some(mask_image), None) => match mask_image.as_ref() {
8011 crate::raster::DynamicImage::ImageLuma8(luma) => Some(luma.as_raw().as_slice()),
8012 _ => unreachable!("native mask must use L8 storage"),
8013 },
8014 (_, Some(raw)) => Some(raw.as_slice()),
8015 _ => None,
8016 };
8017 let width = img.width() as usize;
8018 let masked = |index: usize| -> bool {
8019 match mask_raw {
8020 Some(mask) => mask[index] != 0,
8021 None => true,
8022 }
8023 };
8024 let n_bands = match img.color() {
8025 crate::raster::ColorType::L8 | crate::raster::ColorType::L16 => 1,
8026 crate::raster::ColorType::La8 | crate::raster::ColorType::La16 => 2,
8027 crate::raster::ColorType::Rgb8 | crate::raster::ColorType::Rgb16 => 3,
8028 _ => 4,
8029 };
8030 let mut hists = vec![[0u32; 256]; n_bands];
8031 match img.color() {
8033 crate::raster::ColorType::La8 => {
8034 let crate::raster::DynamicImage::ImageLumaA8(la) = img.as_ref() else {
8035 unreachable!("La8 color must use native LA storage");
8036 };
8037 let raw = la.as_raw();
8038 match mask_raw {
8039 Some(mask) => {
8040 for (index, px) in raw.chunks_exact(2).enumerate() {
8041 if mask[index] == 0 {
8042 continue;
8043 }
8044 hists[0][px[0] as usize] += 1;
8045 hists[1][px[1] as usize] += 1;
8046 }
8047 }
8048 None => {
8049 for px in raw.chunks_exact(2) {
8050 hists[0][px[0] as usize] += 1;
8051 hists[1][px[1] as usize] += 1;
8052 }
8053 }
8054 }
8055 }
8056 crate::raster::ColorType::La16 => {
8057 let la = img.to_luma_alpha8();
8058 for (y, row) in la.rows().enumerate() {
8059 for (x, px) in row.enumerate() {
8060 if !masked(y * width + x) {
8061 continue;
8062 }
8063 hists[0][px[0] as usize] += 1;
8064 hists[1][px[1] as usize] += 1;
8065 }
8066 }
8067 }
8068 crate::raster::ColorType::L8 | crate::raster::ColorType::L16 => {
8069 let luma = img.to_luma8();
8070 for (y, row) in luma.rows().enumerate() {
8071 for (x, px) in row.enumerate() {
8072 if !masked(y * width + x) {
8073 continue;
8074 }
8075 hists[0][px[0] as usize] += 1;
8076 }
8077 }
8078 }
8079 crate::raster::ColorType::Rgb8 => {
8080 let crate::raster::DynamicImage::ImageRgb8(rgb) = img.as_ref() else {
8085 unreachable!("Rgb8 color must use native RGB storage");
8086 };
8087 for (y, row) in rgb.rows().enumerate() {
8088 for (x, px) in row.enumerate() {
8089 if !masked(y * width + x) {
8090 continue;
8091 }
8092 hists[0][px[0] as usize] += 1;
8093 hists[1][px[1] as usize] += 1;
8094 hists[2][px[2] as usize] += 1;
8095 }
8096 }
8097 }
8098 crate::raster::ColorType::Rgba8 => {
8099 let crate::raster::DynamicImage::ImageRgba8(rgba) = img.as_ref() else {
8104 unreachable!("Rgba8 color must use native RGBA storage");
8105 };
8106 let raw = rgba.as_raw();
8107 match mask_raw {
8108 Some(mask) => {
8109 for (index, px) in raw.chunks_exact(4).enumerate() {
8110 if mask[index] == 0 {
8111 continue;
8112 }
8113 for band in 0..n_bands {
8114 hists[band][px[band] as usize] += 1;
8115 }
8116 }
8117 }
8118 None => {
8119 for px in raw.chunks_exact(4) {
8120 for band in 0..n_bands {
8121 hists[band][px[band] as usize] += 1;
8122 }
8123 }
8124 }
8125 }
8126 }
8127 _ => {
8128 let rgba = img.to_rgba8();
8129 for (y, row) in rgba.rows().enumerate() {
8130 for (x, px) in row.enumerate() {
8131 if !masked(y * width + x) {
8132 continue;
8133 }
8134 for b in 0..n_bands {
8135 hists[b][px[b] as usize] += 1;
8136 }
8137 }
8138 }
8139 }
8140 }
8141 let counted: u32 = hists.iter().map(|band| band.iter().sum::<u32>()).sum();
8142 let total = counted as f64;
8143 let mut entropy = 0.0f64;
8144 for band_hist in &hists {
8145 for &h in band_hist {
8146 if h > 0 {
8147 let p = h as f64 / total;
8148 entropy = (p * p.ln()).mul_add(std::f64::consts::LOG2_E, entropy);
8155 }
8156 }
8157 }
8158 Ok(-entropy)
8159 }
8160
8161 fn cmyk_projection(image: &crate::raster::RgbaImage) -> (Vec<u32>, Vec<u32>) {
8162 Self::cmyk_projection_with_blocks(image, 16, |samples| {
8163 let mut packed = [0; 16];
8164 packed.copy_from_slice(samples);
8165 u128::from_ne_bytes(packed) != 0
8166 })
8167 .0
8168 }
8169
8170 fn rgb_projection(image: &crate::raster::RgbImage) -> (Vec<u32>, Vec<u32>) {
8171 let (width, height) = (image.width() as usize, image.height() as usize);
8172 let mut horizontal = vec![0u32; width];
8173 let mut vertical = vec![0u32; height];
8174 for (y, row) in image.rows().enumerate() {
8175 let mut row_nonzero = false;
8176 for (x, pixel) in row.enumerate() {
8177 if pixel[0] != 0 || pixel[1] != 0 || pixel[2] != 0 {
8178 horizontal[x] = 1;
8179 row_nonzero = true;
8180 }
8181 }
8182 vertical[y] = u32::from(row_nonzero);
8183 }
8184 (horizontal, vertical)
8185 }
8186
8187 pub(crate) fn cmyk_projection_with_blocks(
8191 image: &crate::raster::RgbaImage,
8192 block_bytes: usize,
8193 mut block_has_nonzero: impl FnMut(&[u8]) -> bool,
8194 ) -> ((Vec<u32>, Vec<u32>), u64) {
8195 let (w, h) = (image.width() as usize, image.height() as usize);
8196 let mut h_proj = vec![0u32; w];
8197 let mut v_proj = vec![0u32; h];
8198 let mut covered_columns = 0usize;
8199 let mut all_columns_covered = w == 0;
8200 let row_bytes = w * 4;
8201 let bytes = image.as_raw();
8202 debug_assert!(block_bytes >= 4 && block_bytes.is_multiple_of(4));
8203 let nonzero_4 = |samples: &[u8]| {
8204 let mut packed = [0; 4];
8205 packed.copy_from_slice(samples);
8206 u32::from_ne_bytes(packed) != 0
8207 };
8208 let pixels_per_block = block_bytes / 4;
8209 let mut scalar_tail_pixels = 0u64;
8210 for y in 0..h {
8211 let row = &bytes[y * row_bytes..(y + 1) * row_bytes];
8212 let blocks = row.chunks_exact(block_bytes);
8213 scalar_tail_pixels =
8214 scalar_tail_pixels.saturating_add((blocks.remainder().len() / 4) as u64);
8215 let row_nonzero = if all_columns_covered {
8216 blocks.clone().any(|block| block_has_nonzero(block))
8217 || blocks.remainder().chunks_exact(4).any(nonzero_4)
8218 } else {
8219 let mut any = false;
8220 for (block_index, block) in blocks.clone().enumerate() {
8221 if !block_has_nonzero(block) {
8222 continue;
8223 }
8224 for (lane, pixel) in block.chunks_exact(4).enumerate() {
8225 if !nonzero_4(pixel) {
8226 continue;
8227 }
8228 let x = block_index * pixels_per_block + lane;
8229 if h_proj[x] == 0 {
8230 h_proj[x] = 1;
8231 covered_columns += 1;
8232 all_columns_covered = covered_columns == w;
8233 }
8234 any = true;
8235 }
8236 }
8237 let tail_start = blocks.len() * block_bytes;
8238 for (tail_index, pixel) in row[tail_start..].chunks_exact(4).enumerate() {
8239 if !nonzero_4(pixel) {
8240 continue;
8241 }
8242 let x = tail_start / 4 + tail_index;
8243 if h_proj[x] == 0 {
8244 h_proj[x] = 1;
8245 covered_columns += 1;
8246 all_columns_covered = covered_columns == w;
8247 }
8248 any = true;
8249 }
8250 any
8251 };
8252 if row_nonzero {
8253 v_proj[y] = 1;
8254 }
8255 }
8256 ((h_proj, v_proj), scalar_tail_pixels)
8257 }
8258
8259 fn cmyk_projection_with_putpixel_ops(
8260 image: &crate::raster::RgbaImage,
8261 ops: &[PipelineOp],
8262 source_is_known_zero: bool,
8263 ) -> Result<(Vec<u32>, Vec<u32>), PilError> {
8264 Self::cmyk_projection_with_putpixel_ops_using(image, ops, source_is_known_zero, |image| {
8265 let (horizontal, vertical) = Self::cmyk_projection(image);
8266 (horizontal, vertical, 0, 0)
8267 })
8268 .map(|(horizontal, vertical, _, _)| (horizontal, vertical))
8269 }
8270
8271 fn rgb_projection_with_putpixel_ops(
8272 image: &crate::raster::RgbImage,
8273 ops: &[PipelineOp],
8274 source_is_known_zero: bool,
8275 ) -> Result<(Vec<u32>, Vec<u32>), PilError> {
8276 Self::rgb_projection_with_putpixel_ops_using(image, ops, source_is_known_zero, |image| {
8277 let (horizontal, vertical) = Self::rgb_projection(image);
8278 (horizontal, vertical, 0, 0)
8279 })
8280 .map(|(horizontal, vertical, _, _)| (horizontal, vertical))
8281 }
8282
8283 fn cmyk_projection_with_putpixel_ops_using(
8284 image: &crate::raster::RgbaImage,
8285 ops: &[PipelineOp],
8286 source_is_known_zero: bool,
8287 project: impl FnOnce(&crate::raster::RgbaImage) -> (Vec<u32>, Vec<u32>, u64, u64),
8288 ) -> Result<(Vec<u32>, Vec<u32>, u64, u64), PilError> {
8289 Self::projection_with_putpixel_ops_using(
8290 image.width(),
8291 image.height(),
8292 image.as_raw(),
8293 4,
8294 "CMYK",
8295 ops,
8296 source_is_known_zero,
8297 || project(image),
8298 )
8299 }
8300
8301 fn rgb_projection_with_putpixel_ops_using(
8302 image: &crate::raster::RgbImage,
8303 ops: &[PipelineOp],
8304 source_is_known_zero: bool,
8305 project: impl FnOnce(&crate::raster::RgbImage) -> (Vec<u32>, Vec<u32>, u64, u64),
8306 ) -> Result<(Vec<u32>, Vec<u32>, u64, u64), PilError> {
8307 Self::projection_with_putpixel_ops_using(
8308 image.width(),
8309 image.height(),
8310 image.as_raw(),
8311 3,
8312 "RGB",
8313 ops,
8314 source_is_known_zero,
8315 || project(image),
8316 )
8317 }
8318
8319 fn projection_with_putpixel_ops_using(
8320 width: u32,
8321 height: u32,
8322 bytes: &[u8],
8323 channels: usize,
8324 mode: &str,
8325 ops: &[PipelineOp],
8326 source_is_known_zero: bool,
8327 project: impl FnOnce() -> (Vec<u32>, Vec<u32>, u64, u64),
8328 ) -> Result<(Vec<u32>, Vec<u32>, u64, u64), PilError> {
8329 let (w, h) = (width as usize, height as usize);
8330 let mut pending_writes = Vec::with_capacity(ops.len());
8331 for (order, op) in ops.iter().enumerate() {
8332 let PipelineOp::PutPixel { x, y, color, .. } = op else {
8333 return Err(PilError::InternalError(format!(
8334 "{mode} projection fusion received a non-pixel operation"
8335 )));
8336 };
8337 if *x >= width || *y >= height {
8338 return Err(PilError::IndexError("image index out of range".into()));
8339 }
8340 let index = *y as usize * w + *x as usize;
8341 pending_writes.push((index, order, [color.0, color.1, color.2, color.3]));
8342 }
8343 pending_writes.sort_unstable_by_key(|(index, order, _)| (*index, *order));
8344 let mut writes: Vec<(usize, [u8; 4])> = Vec::with_capacity(pending_writes.len());
8345 for (index, _, color) in pending_writes {
8346 if let Some((previous_index, previous_color)) = writes.last_mut()
8347 && *previous_index == index
8348 {
8349 *previous_color = color;
8350 } else {
8351 writes.push((index, color));
8352 }
8353 }
8354
8355 let (mut h_proj, mut v_proj, vector_blocks, scalar_tail) = if source_is_known_zero {
8360 (vec![0; w], vec![0; h], 0, 0)
8361 } else {
8362 project()
8363 };
8364 let mut cleared_columns = Vec::new();
8365 let mut cleared_rows = Vec::new();
8366 if source_is_known_zero {
8367 for &(index, color) in &writes {
8368 if color[..channels].iter().any(|value| *value != 0) {
8369 h_proj[index % w] = 1;
8370 v_proj[index / w] = 1;
8371 }
8372 }
8373 } else {
8374 for &(index, color) in &writes {
8375 let x = index % w;
8376 let y = index / w;
8377 if color[..channels].iter().any(|value| *value != 0) {
8378 h_proj[x] = 1;
8379 v_proj[y] = 1;
8380 } else {
8381 cleared_columns.push(x);
8382 cleared_rows.push(y);
8383 }
8384 }
8385 }
8386 cleared_columns.sort_unstable();
8387 cleared_columns.dedup();
8388 cleared_rows.sort_unstable();
8389 cleared_rows.dedup();
8390
8391 let pixel_is_nonzero = |index: usize| {
8392 if let Ok(write) = writes.binary_search_by_key(&index, |(write_index, _)| *write_index)
8393 {
8394 writes[write].1[..channels].iter().any(|value| *value != 0)
8395 } else {
8396 let offset = index * channels;
8397 bytes[offset..offset + channels]
8398 .iter()
8399 .any(|value| *value != 0)
8400 }
8401 };
8402 for x in cleared_columns {
8403 h_proj[x] = u32::from((0..h).any(|y| pixel_is_nonzero(y * w + x)));
8404 }
8405 for y in cleared_rows {
8406 v_proj[y] = u32::from((0..w).any(|x| pixel_is_nonzero(y * w + x)));
8407 }
8408 Ok((h_proj, v_proj, vector_blocks, scalar_tail))
8409 }
8410
8411 fn try_getprojection_putpixel_pipeline(
8412 &self,
8413 ) -> Result<Option<(Vec<u32>, Vec<u32>)>, PilError> {
8414 let Image::Pipeline {
8419 source,
8420 ops,
8421 explicit_mode,
8422 backend,
8423 ..
8424 } = self
8425 else {
8426 return Ok(None);
8427 };
8428 if !matches!(source.as_ref(), Image::Loaded(_) | Image::Bytes { .. }) {
8429 return Ok(None);
8430 }
8431 let mode = match explicit_mode.as_deref() {
8432 Some("RGB") => "RGB",
8433 Some("CMYK") => "CMYK",
8434 Some(_) => return Ok(None),
8435 None if source.mode()? == "RGB" => "RGB",
8439 None => return Ok(None),
8440 };
8441 if ops.is_empty() {
8442 return Ok(None);
8443 }
8444 let terminal_backend = match backend {
8445 Some(crate::compute::Backend::Cpu) => Some(crate::compute::Backend::Cpu),
8446 Some(crate::compute::Backend::Simd) => Some(crate::compute::Backend::Simd),
8447 #[cfg(feature = "gpu")]
8448 Some(crate::compute::Backend::Gpu) => Some(crate::compute::Backend::Gpu),
8449 #[cfg(not(feature = "gpu"))]
8450 Some(crate::compute::Backend::Gpu) => None,
8451 None => match crate::compute::preferred_active_backend()? {
8456 Some((backend, true)) => Some(backend),
8457 _ => None,
8458 },
8459 };
8460 let Some(terminal_backend) = terminal_backend else {
8461 return Ok(None);
8462 };
8463 if !ops
8464 .as_slice()
8465 .iter()
8466 .all(|op| matches!(op, PipelineOp::PutPixel { .. }))
8467 {
8468 return Ok(None);
8469 }
8470 let prepared = crate::compute::prepare_execution(ops.as_slice(), Some(terminal_backend))?;
8471 let backend_matches = match terminal_backend {
8472 crate::compute::Backend::Cpu => prepared.is_serial_cpu_without_fallback(),
8473 crate::compute::Backend::Simd => prepared.is_simd_without_fallback(),
8474 crate::compute::Backend::Gpu => prepared.is_gpu_without_fallback(),
8475 };
8476 if !backend_matches {
8477 return Ok(None);
8478 }
8479 let source_is_known_zero = matches!(
8480 source.as_ref(),
8481 Image::Loaded(data) if data.known_zero_fill
8482 );
8483 let input = source.materialized_shared()?;
8484 if source.mode_from_materialized(&input) != mode {
8485 return Ok(None);
8486 }
8487 #[cfg(feature = "gpu")]
8488 if terminal_backend == crate::compute::Backend::Gpu {
8489 let supported = match mode {
8490 "RGB" => crate::compute::gpu_rgb_projection_terminal_supported(
8491 input.as_ref(),
8492 ops.as_slice(),
8493 ),
8494 "CMYK" => crate::compute::gpu_cmyk_projection_terminal_supported(
8495 input.as_ref(),
8496 ops.as_slice(),
8497 ),
8498 _ => false,
8499 };
8500 if !supported {
8501 return Ok(None);
8502 }
8503 }
8504 let (width, height) = (input.width() as usize, input.height() as usize);
8505 let output_sizes = [
8506 width * std::mem::size_of::<u32>(),
8507 height * std::mem::size_of::<u32>(),
8508 ];
8509 let result = match (mode, terminal_backend) {
8510 ("CMYK", crate::compute::Backend::Cpu) => {
8511 let DynamicImage::ImageRgba8(image) = input.as_ref() else {
8512 return Ok(None);
8513 };
8514 crate::compute::execute_prepared_cpu_terminal(
8515 &prepared,
8516 ops.as_slice(),
8517 input.as_ref(),
8518 output_sizes,
8519 || {
8520 Self::cmyk_projection_with_putpixel_ops(
8521 image,
8522 ops.as_slice(),
8523 source_is_known_zero,
8524 )
8525 },
8526 )?
8527 }
8528 ("RGB", crate::compute::Backend::Cpu) => {
8529 let DynamicImage::ImageRgb8(image) = input.as_ref() else {
8530 return Ok(None);
8531 };
8532 crate::compute::execute_prepared_cpu_terminal(
8533 &prepared,
8534 ops.as_slice(),
8535 input.as_ref(),
8536 output_sizes,
8537 || {
8538 Self::rgb_projection_with_putpixel_ops(
8539 image,
8540 ops.as_slice(),
8541 source_is_known_zero,
8542 )
8543 },
8544 )?
8545 }
8546 ("CMYK", crate::compute::Backend::Simd) => {
8547 let DynamicImage::ImageRgba8(image) = input.as_ref() else {
8548 return Ok(None);
8549 };
8550 crate::compute::execute_prepared_simd_terminal(
8551 &prepared,
8552 ops.as_slice(),
8553 input.as_ref(),
8554 output_sizes,
8555 || {
8556 if let Some((horizontal, vertical, vector_blocks, scalar_tail)) =
8557 source_is_known_zero
8558 .then(|| {
8559 crate::compute::simd_cmyk_projection_from_positive_writes(
8560 image.width(),
8561 image.height(),
8562 ops.as_slice(),
8563 )
8564 })
8565 .flatten()
8566 {
8567 Ok(((horizontal, vertical), vector_blocks, scalar_tail))
8568 } else {
8569 Self::cmyk_projection_with_putpixel_ops_using(
8570 image,
8571 ops.as_slice(),
8572 false,
8573 |image| crate::compute::simd_cmyk_projection(image),
8574 )
8575 .map(
8576 |(horizontal, vertical, vector_blocks, scalar_tail)| {
8577 ((horizontal, vertical), vector_blocks, scalar_tail)
8578 },
8579 )
8580 }
8581 },
8582 )?
8583 }
8584 ("RGB", crate::compute::Backend::Simd) => {
8585 let DynamicImage::ImageRgb8(image) = input.as_ref() else {
8586 return Ok(None);
8587 };
8588 crate::compute::execute_prepared_simd_terminal(
8589 &prepared,
8590 ops.as_slice(),
8591 input.as_ref(),
8592 output_sizes,
8593 || {
8594 Self::rgb_projection_with_putpixel_ops_using(
8595 image,
8596 ops.as_slice(),
8597 false,
8598 |image| crate::compute::simd_rgb_projection(image),
8599 )
8600 .map(
8601 |(horizontal, vertical, vector_blocks, scalar_tail)| {
8602 ((horizontal, vertical), vector_blocks, scalar_tail)
8603 },
8604 )
8605 },
8606 )?
8607 }
8608 #[cfg(feature = "gpu")]
8609 ("CMYK", crate::compute::Backend::Gpu) => {
8610 return crate::compute::execute_prepared_gpu_cmyk_projection_terminal(
8611 &prepared,
8612 ops.as_slice(),
8613 input.as_ref(),
8614 source_is_known_zero,
8615 )
8616 .map(Some);
8617 }
8618 #[cfg(feature = "gpu")]
8619 ("RGB", crate::compute::Backend::Gpu) => {
8620 return crate::compute::execute_prepared_gpu_rgb_projection_terminal(
8621 &prepared,
8622 ops.as_slice(),
8623 input.as_ref(),
8624 source_is_known_zero,
8625 )
8626 .map(Some);
8627 }
8628 #[cfg(not(feature = "gpu"))]
8629 (_, crate::compute::Backend::Gpu) => return Ok(None),
8630 _ => return Ok(None),
8631 };
8632 Ok(Some(result))
8633 }
8634
8635 pub fn getprojection(&self) -> Result<(Vec<u32>, Vec<u32>), PilError> {
8645 if let Some(projection) = self.try_getprojection_putpixel_pipeline()? {
8646 return Ok(projection);
8647 }
8648 let img = self.materialized_shared()?;
8649 let mode = self.mode_from_materialized(&img);
8650 if let Some(projection) =
8651 self.try_getprojection_eager_backend(img.as_ref(), mode.as_str())?
8652 {
8653 return Ok(projection);
8654 }
8655 if !crate::compute::Backend::pipeline_telemetry_enabled() {
8656 return Self::getprojection_from_materialized(img.as_ref(), mode.as_str());
8657 }
8658
8659 let selected = crate::compute::preferred_active_backend().ok().flatten();
8660 let requested_backend = selected
8661 .filter(|(_, only_active_backend)| *only_active_backend)
8662 .map(|(backend, _)| backend);
8663 let fallback_reason = requested_backend
8664 .filter(|backend| *backend != crate::compute::Backend::Cpu)
8665 .map(|backend| {
8666 format!(
8667 "GetProjection materialized pipeline used the host CPU while {backend:?} was requested"
8668 )
8669 });
8670 crate::compute::execute_eager_cpu_getprojection(
8671 img.as_ref(),
8672 requested_backend,
8673 fallback_reason,
8674 || Self::getprojection_from_materialized(img.as_ref(), mode.as_str()),
8675 )
8676 }
8677
8678 fn try_getprojection_eager_backend(
8679 &self,
8680 img: &DynamicImage,
8681 mode: &str,
8682 ) -> Result<Option<(Vec<u32>, Vec<u32>)>, PilError> {
8683 if !matches!(self, Image::Loaded(_) | Image::Paletted(_)) {
8684 return Ok(None);
8685 }
8686 let Some((selected, only_active_backend)) = crate::compute::preferred_active_backend()?
8687 else {
8688 return Ok(None);
8689 };
8690 let requested = only_active_backend.then_some(selected);
8691 match selected {
8692 crate::compute::Backend::Cpu => {
8693 crate::compute::execute_eager_cpu_getprojection(img, requested, None, || {
8694 Self::getprojection_from_materialized(img, mode)
8695 })
8696 .map(Some)
8697 }
8698 crate::compute::Backend::Simd if mode == "RGB" => {
8699 let DynamicImage::ImageRgb8(image) = img else {
8700 return Ok(None);
8701 };
8702 crate::compute::execute_eager_simd_getprojection(img, || {
8703 let (horizontal, vertical, vector_blocks, scalar_tail) =
8704 crate::compute::simd_rgb_projection(image);
8705 Ok(((horizontal, vertical), vector_blocks, scalar_tail))
8706 })
8707 .map(Some)
8708 }
8709 crate::compute::Backend::Simd if mode == "CMYK" => {
8710 let DynamicImage::ImageRgba8(image) = img else {
8711 return Ok(None);
8712 };
8713 crate::compute::execute_eager_simd_getprojection(img, || {
8714 let (horizontal, vertical, vector_blocks, scalar_tail) =
8715 crate::compute::simd_cmyk_projection(image);
8716 Ok(((horizontal, vertical), vector_blocks, scalar_tail))
8717 })
8718 .map(Some)
8719 }
8720 crate::compute::Backend::Simd => crate::compute::execute_eager_cpu_getprojection(
8721 img,
8722 requested,
8723 Some(format!("SIMD getprojection is unsupported for mode {mode}")),
8724 || Self::getprojection_from_materialized(img, mode),
8725 )
8726 .map(Some),
8727 #[cfg(feature = "gpu")]
8728 crate::compute::Backend::Gpu if mode == "RGB" => {
8729 if crate::compute::gpu_rgb_projection_supported(img) {
8730 crate::compute::execute_eager_gpu_rgb_getprojection(img).map(Some)
8731 } else {
8732 crate::compute::execute_eager_cpu_getprojection(
8733 img,
8734 requested,
8735 Some("GPU getprojection is unsupported for this RGB image".into()),
8736 || Self::getprojection_from_materialized(img, mode),
8737 )
8738 .map(Some)
8739 }
8740 }
8741 #[cfg(feature = "gpu")]
8742 crate::compute::Backend::Gpu => crate::compute::execute_eager_cpu_getprojection(
8743 img,
8744 requested,
8745 Some(format!("GPU getprojection is unsupported for mode {mode}")),
8746 || Self::getprojection_from_materialized(img, mode),
8747 )
8748 .map(Some),
8749 #[cfg(not(feature = "gpu"))]
8750 crate::compute::Backend::Gpu => crate::compute::execute_eager_cpu_getprojection(
8751 img,
8752 requested,
8753 Some(format!("GPU getprojection is unsupported for mode {mode}")),
8754 || Self::getprojection_from_materialized(img, mode),
8755 )
8756 .map(Some),
8757 }
8758 }
8759
8760 fn getprojection_from_materialized(
8761 img: &DynamicImage,
8762 mode: &str,
8763 ) -> Result<(Vec<u32>, Vec<u32>), PilError> {
8764 let (w, h) = (img.width() as usize, img.height() as usize);
8765 let mut h_proj = vec![0u32; w];
8766 let mut v_proj = vec![0u32; h];
8767
8768 if matches!(mode, "I" | "F") {
8772 let row_bytes = w.checked_mul(std::mem::size_of::<u32>()).ok_or_else(|| {
8779 PilError::DimensionError("getprojection row byte count overflow".into())
8780 })?;
8781 if row_bytes != 0 {
8782 let raw = img.as_bytes();
8783 let mut remaining_columns = w;
8784 for (y, row) in raw.chunks_exact(row_bytes).take(h).enumerate() {
8785 let row_nonzero = if remaining_columns == 0 {
8786 row.chunks_exact(4).any(|sample| {
8787 u32::from_le_bytes([sample[0], sample[1], sample[2], sample[3]]) != 0
8788 })
8789 } else {
8790 let mut row_nonzero = false;
8791 if mode == "I" {
8792 for (x, sample) in row.chunks_exact(4).enumerate() {
8793 let value = i32::from_le_bytes([
8794 sample[0], sample[1], sample[2], sample[3],
8795 ]);
8796 if value != 0 {
8797 row_nonzero = true;
8798 if h_proj[x] == 0 {
8799 h_proj[x] = 1;
8800 remaining_columns -= 1;
8801 }
8802 if remaining_columns == 0 {
8803 break;
8804 }
8805 }
8806 }
8807 } else {
8808 for (x, sample) in row.chunks_exact(4).enumerate() {
8809 let value = u32::from_le_bytes([
8812 sample[0], sample[1], sample[2], sample[3],
8813 ]);
8814 if value != 0 {
8815 row_nonzero = true;
8816 if h_proj[x] == 0 {
8817 h_proj[x] = 1;
8818 remaining_columns -= 1;
8819 }
8820 if remaining_columns == 0 {
8821 break;
8822 }
8823 }
8824 }
8825 }
8826 row_nonzero
8827 };
8828 if row_nonzero {
8829 v_proj[y] = 1;
8830 }
8831 }
8832 }
8833 } else {
8834 let mut mark = |index: usize| {
8835 let x = index % w;
8836 let y = index / w;
8837 h_proj[x] = 1;
8838 v_proj[y] = 1;
8839 };
8840 match img {
8841 crate::raster::DynamicImage::ImageLuma8(image)
8842 if matches!(mode, "L" | "1" | "P") =>
8843 {
8844 for (index, pixel) in image.pixels().enumerate() {
8845 if pixel[0] != 0 {
8846 mark(index);
8847 }
8848 }
8849 }
8850 crate::raster::DynamicImage::ImageLumaA8(image) if matches!(mode, "LA" | "PA") => {
8851 for (index, pixel) in image.pixels().enumerate() {
8852 if pixel[0] != 0 || pixel[1] != 0 {
8853 mark(index);
8854 }
8855 }
8856 }
8857 crate::raster::DynamicImage::ImageRgb8(image)
8858 if matches!(mode, "RGB" | "HSV" | "YCbCr") =>
8859 {
8860 if w >= 64 {
8861 let row_bytes = w * 3;
8866 let mut covered_columns = 0usize;
8867 let mut all_columns_covered = false;
8868 for (y, row) in image.as_raw().chunks_exact(row_bytes).enumerate() {
8869 if all_columns_covered {
8870 v_proj[y] = u32::from(row.iter().any(|value| *value != 0));
8871 continue;
8872 }
8873 let mut row_nonzero = false;
8874 for (x, pixel) in row.chunks_exact(3).enumerate() {
8875 if pixel[0] == 0 && pixel[1] == 0 && pixel[2] == 0 {
8876 continue;
8877 }
8878 if h_proj[x] == 0 {
8879 h_proj[x] = 1;
8880 covered_columns += 1;
8881 }
8882 row_nonzero = true;
8883 if covered_columns == w {
8884 all_columns_covered = true;
8885 break;
8886 }
8887 }
8888 v_proj[y] = u32::from(row_nonzero);
8889 }
8890 } else {
8891 for (index, pixel) in image.pixels().enumerate() {
8894 if pixel.0.iter().any(|value| *value != 0) {
8895 mark(index);
8896 }
8897 }
8898 }
8899 }
8900 crate::raster::DynamicImage::ImageRgb8(image) if mode == "LAB" => {
8901 for (index, pixel) in image.pixels().enumerate() {
8906 if pixel[0] != 0 || pixel[1] != 128 || pixel[2] != 128 {
8907 mark(index);
8908 }
8909 }
8910 }
8911 crate::raster::DynamicImage::ImageRgba8(image)
8912 if matches!(mode, "RGBA" | "RGBa" | "RGBX") =>
8913 {
8914 for (index, pixel) in image.pixels().enumerate() {
8915 if pixel.0.iter().any(|value| *value != 0) {
8916 mark(index);
8917 }
8918 }
8919 }
8920 crate::raster::DynamicImage::ImageRgba8(image) if mode == "CMYK" => {
8921 (h_proj, v_proj) = Self::cmyk_projection(image);
8922 }
8923 _ => match mode {
8924 "L" | "1" | "P" => {
8925 for (index, pixel) in img.to_luma8().pixels().enumerate() {
8926 if pixel[0] != 0 {
8927 mark(index);
8928 }
8929 }
8930 }
8931 "LA" | "PA" => {
8932 for (index, pixel) in img.to_luma_alpha8().pixels().enumerate() {
8933 if pixel[0] != 0 || pixel[1] != 0 {
8934 mark(index);
8935 }
8936 }
8937 }
8938 "RGB" | "HSV" | "YCbCr" => {
8939 for (index, pixel) in img.to_rgb8().pixels().enumerate() {
8940 if pixel.0.iter().any(|value| *value != 0) {
8941 mark(index);
8942 }
8943 }
8944 }
8945 _ => {
8946 for (index, pixel) in img.to_rgba8().pixels().enumerate() {
8947 if pixel.0.iter().any(|value| *value != 0) {
8948 mark(index);
8949 }
8950 }
8951 }
8952 },
8953 }
8954 }
8955 Ok((h_proj, v_proj))
8956 }
8957
8958 pub fn tobitmap(&self) -> Result<Vec<u8>, PilError> {
8967 let mode = self.mode()?;
8968 if mode != "1" {
8969 return Err(PilError::ValueError("not a bitmap".to_owned()));
8970 }
8971 let img = self.materialized_shared()?;
8972 let gray = img.to_luma8();
8973 let (w, h) = (gray.width(), gray.height());
8974 let row_bytes = w.div_ceil(8) as usize;
8975 let mut bits = vec![0u8; row_bytes * h as usize];
8976 for y in 0..h {
8977 for x in 0..w {
8978 let v = gray.get_pixel(x, y)[0];
8979 let is_white = v != 0;
8982 if is_white {
8983 let byte_idx = (x / 8) as usize;
8985 let bit_idx = x % 8;
8986 bits[(y as usize) * row_bytes + byte_idx] |= 1u8 << bit_idx;
8987 }
8988 }
8989 }
8990 let mut xbm = String::new();
8992 xbm.push_str(&format!("#define image_width {}\n", w));
8993 xbm.push_str(&format!("#define image_height {}\n", h));
8994 xbm.push_str("static char image_bits[] = {\n");
8995 let hexes: Vec<String> = bits.iter().map(|b| format!("0x{:02x}", b)).collect();
8996 let total = hexes.len();
8997 for (i, chunk) in hexes.chunks(15).enumerate() {
8998 let start = i * 15;
8999 let end = (start + chunk.len()).min(total);
9000 let is_last = end >= total;
9001 if is_last {
9002 xbm.push_str(&chunk.join(","));
9004 } else {
9005 xbm.push_str(&chunk.join(","));
9007 xbm.push(',');
9008 }
9009 xbm.push('\n');
9010 }
9011 xbm.push_str("};");
9012 Ok(xbm.into_bytes())
9013 }
9014
9015 pub fn seek(&self, frame: u32) -> Result<(), PilError> {
9020 if frame != self.tell() {
9021 return Err(PilError::EOFError("no more images in file".to_owned()));
9022 }
9023 Ok(())
9024 }
9025
9026 pub fn tell(&self) -> u32 {
9031 0
9032 }
9033
9034 pub fn remap_palette(&self, dest_map: &[u8]) -> Result<Image, PilError> {
9045 self.remap_palette_with_source(dest_map, None)
9046 }
9047
9048 pub fn remap_palette_with_source(
9054 &self,
9055 dest_map: &[u8],
9056 source_palette: Option<&[u8]>,
9057 ) -> Result<Image, PilError> {
9058 let mode = self.mode()?;
9059 if !matches!(mode.as_str(), "L" | "P") {
9060 return Err(PilError::ValueError("illegal image mode".to_owned()));
9061 }
9062 if dest_map.len() > 256 {
9063 return Err(PilError::ValueError(
9064 "byte must be in range(0, 256)".to_owned(),
9065 ));
9066 }
9067
9068 let uses_attached_palette = source_palette.is_none() && mode == "P";
9069 let source_bands = if source_palette.is_some_and(|palette| palette.len() > 768) {
9072 4
9073 } else {
9074 3
9075 };
9076 let source_palette = source_palette.map_or_else(
9077 || {
9078 if mode == "P" {
9079 self.extract_palette().unwrap_or_default()
9080 } else {
9081 (0u8..=u8::MAX)
9082 .flat_map(|value| [value, value, value])
9083 .collect()
9084 }
9085 },
9086 <[u8]>::to_vec,
9087 );
9088 let mut remapped_palette = Vec::with_capacity(dest_map.len() * 3);
9089 let mut explicit_alpha = (source_bands == 4).then(|| Vec::with_capacity(dest_map.len()));
9090 for &old_index in dest_map {
9091 let start = usize::from(old_index) * source_bands;
9092 if let Some(color) = source_palette.get(start..start + source_bands) {
9093 remapped_palette.extend_from_slice(&color[..3]);
9097 if let Some(alpha) = &mut explicit_alpha {
9098 alpha.push(color[3]);
9099 }
9100 }
9101 }
9102
9103 let remapped_alpha = if source_bands == 4 {
9104 explicit_alpha
9105 } else if uses_attached_palette {
9106 self.palette_alpha().and_then(|alpha| {
9107 if alpha.is_empty() {
9108 return None;
9109 }
9110 Some(
9111 dest_map
9112 .iter()
9113 .map(|&index| alpha.get(usize::from(index)).copied().unwrap_or(255))
9114 .collect(),
9115 )
9116 })
9117 } else {
9118 None
9119 };
9120
9121 let mut result = Image::push_op(
9122 self,
9123 PipelineOp::RemapPalette {
9124 dest_map: dest_map.to_vec().into(),
9125 },
9126 );
9127 if let Image::Pipeline {
9128 explicit_mode,
9129 palette,
9130 palette_alpha,
9131 ..
9132 } = &mut result
9133 {
9134 *explicit_mode = Some("P".to_owned());
9135 *palette = Some(remapped_palette);
9136 *palette_alpha = remapped_alpha;
9137 }
9138 Ok(result)
9139 }
9140}
9141
9142fn image_from_materialized(
9143 image: Arc<DynamicImage>,
9144 source_format: Option<ImageFormat>,
9145 info: Option<ImageInfo>,
9146 exif: Option<Vec<u8>>,
9147) -> Result<Image, PilError> {
9148 let mode = info
9149 .as_ref()
9150 .map_or_else(|| image.color().into(), |info| info.mode);
9151 if mode == ImageMode::P8 {
9152 let palette = info
9153 .as_ref()
9154 .and_then(|info| info.palette.clone())
9155 .ok_or_else(|| {
9156 PilError::PaletteError("decoded P-mode image has no retained palette".to_owned())
9157 })?;
9158 return Ok(Image::Paletted(PalettedData {
9159 indices: image.as_ref().clone().to_luma8(),
9160 palette: padded_palette(&palette.rgb),
9161 palette_alpha: palette.alpha,
9162 source_format,
9163 info,
9164 exif: exif.clone(),
9165 materialized: materialization_cache(),
9166 }));
9167 }
9168 let explicit_mode = match mode {
9169 ImageMode::L1 | ImageMode::Cmyk8 | ImageMode::F32 | ImageMode::I32 => {
9170 Some(image_mode_name(mode).to_owned())
9171 }
9172 _ => None,
9173 };
9174 Ok(Image::Loaded(LoadedData {
9175 image,
9176 known_zero_fill: false,
9177 explicit_mode,
9178 decoded_mode: mode,
9179 palette: None,
9180 palette_alpha: None,
9181 source_format,
9182 info,
9183 exif,
9184 }))
9185}
9186
9187fn map_codec_error(error: image_slash_star::ImageError, source: &str) -> PilError {
9188 if matches!(error, image_slash_star::ImageError::UnknownFormat) {
9189 PilError::UnidentifiedImageError(source.to_owned())
9190 } else {
9191 PilError::ImageError(error)
9192 }
9193}
9194
9195fn map_deferred_decode_error(error: image_slash_star::ImageError) -> PilError {
9196 match error {
9197 image_slash_star::ImageError::Malformed { .. } => {
9202 PilError::IOError("cannot load this image".to_owned())
9203 }
9204 other => map_codec_error(other, "memory"),
9205 }
9206}
9207
9208fn decoded_to_dynamic(decoded: &Decoded<DecodedImage>) -> Result<DynamicImage, PilError> {
9209 let content = &decoded.content;
9210 match content.mode {
9211 ImageMode::P8 => crate::raster::GrayImage::from_raw(
9212 content.width,
9213 content.height,
9214 content.pixels.clone(),
9215 )
9216 .map(DynamicImage::ImageLuma8)
9217 .ok_or_else(|| PilError::DimensionError("invalid indexed buffer".to_owned())),
9218 ImageMode::L1 => {
9219 let row_bytes = content.width.div_ceil(8) as usize;
9220 let mut unpacked = Vec::with_capacity(content.width as usize * content.height as usize);
9221 for row in content.pixels.chunks_exact(row_bytes) {
9222 for x in 0..content.width as usize {
9223 let bit = (row[x / 8] >> (7 - (x % 8))) & 1;
9224 unpacked.push(if bit == 0 { 0 } else { 255 });
9225 }
9226 }
9227 crate::raster::GrayImage::from_raw(content.width, content.height, unpacked)
9228 .map(DynamicImage::ImageLuma8)
9229 .ok_or_else(|| PilError::DimensionError("invalid packed bilevel buffer".to_owned()))
9230 }
9231 ImageMode::Cmyk8 | ImageMode::F32 | ImageMode::I32 => crate::raster::RgbaImage::from_raw(
9232 content.width,
9233 content.height,
9234 content.pixels.clone(),
9235 )
9236 .map(DynamicImage::ImageRgba8)
9237 .ok_or_else(|| PilError::DimensionError("invalid four-byte buffer".to_owned())),
9238 mode => DynamicImage::from_decoded(content)
9239 .ok_or_else(|| PilError::ValueError(format!("unsupported decoded mode {mode:?}"))),
9240 }
9241}
9242
9243fn padded_palette(rgb: &[u8]) -> Vec<u8> {
9244 let mut palette = rgb.to_vec();
9245 palette.resize(768, 0);
9246 palette
9247}
9248
9249fn split_palette_data(data: &[u8], rawmode: &str) -> Result<(Vec<u8>, Vec<u8>), PilError> {
9250 match rawmode {
9251 "RGB" => {
9252 let complete = data.len() / 3 * 3;
9253 if complete > 768 {
9254 return Err(PilError::ValueError("invalid palette size".to_owned()));
9255 }
9256 Ok((data[..complete].to_vec(), Vec::new()))
9257 }
9258 "RGBA" => {
9259 let complete = data.len() / 4 * 4;
9260 if complete > 1024 {
9261 return Err(PilError::ValueError("invalid palette size".to_owned()));
9262 }
9263 let mut rgb = Vec::with_capacity(complete / 4 * 3);
9264 let mut alpha = Vec::with_capacity(complete / 4);
9265 for color in data[..complete].chunks_exact(4) {
9266 rgb.extend_from_slice(&color[..3]);
9267 alpha.push(color[3]);
9268 }
9269 Ok((rgb, alpha))
9270 }
9271 "LA" => {
9272 let complete = data.len() / 2 * 2;
9277 if complete > 512 {
9278 return Err(PilError::ValueError("invalid palette size".to_owned()));
9279 }
9280 let mut rgb = Vec::with_capacity(complete / 2 * 3);
9281 let mut alpha = Vec::with_capacity(complete / 2);
9282 for color in data[..complete].chunks_exact(2) {
9283 rgb.extend_from_slice(&[color[0], color[0], color[0]]);
9284 alpha.push(color[1]);
9285 }
9286 Ok((rgb, alpha))
9287 }
9288 _ => Err(PilError::ValueError("unrecognized raw mode".to_owned())),
9289 }
9290}
9291
9292pub(crate) fn expand_palette(
9293 indices: &crate::raster::GrayImage,
9294 palette: &[u8],
9295 palette_alpha: &[u8],
9296) -> DynamicImage {
9297 if palette_alpha.is_empty() {
9298 return DynamicImage::ImageRgb8(crate::raster::RgbImage::from_fn(
9299 indices.width(),
9300 indices.height(),
9301 |x, y| {
9302 let index = usize::from(indices.get_pixel(x, y)[0]);
9303 let base = index * 3;
9304 crate::raster::Rgb([
9305 palette.get(base).copied().unwrap_or(0),
9306 palette.get(base + 1).copied().unwrap_or(0),
9307 palette.get(base + 2).copied().unwrap_or(0),
9308 ])
9309 },
9310 ));
9311 }
9312 DynamicImage::ImageRgba8(crate::raster::RgbaImage::from_fn(
9313 indices.width(),
9314 indices.height(),
9315 |x, y| {
9316 let index = usize::from(indices.get_pixel(x, y)[0]);
9317 let base = index * 3;
9318 crate::raster::Rgba([
9319 palette.get(base).copied().unwrap_or(0),
9320 palette.get(base + 1).copied().unwrap_or(0),
9321 palette.get(base + 2).copied().unwrap_or(0),
9322 palette_alpha.get(index).copied().unwrap_or(255),
9323 ])
9324 },
9325 ))
9326}
9327
9328pub(crate) fn expand_palette_alpha(
9333 indices_alpha: &crate::raster::GrayAlphaImage,
9334 palette: &[u8],
9335) -> DynamicImage {
9336 let mut rgb_by_index = [[0u8; 3]; 256];
9337 for (index, rgb) in rgb_by_index.iter_mut().enumerate() {
9338 let base = index * 3;
9339 *rgb = [
9340 palette.get(base).copied().unwrap_or(0),
9341 palette.get(base + 1).copied().unwrap_or(0),
9342 palette.get(base + 2).copied().unwrap_or(0),
9343 ];
9344 }
9345
9346 let samples = indices_alpha.as_raw();
9347 if let Some(output_len) = samples.len().checked_mul(2) {
9348 let mut output = Vec::with_capacity(output_len);
9349 for sample in samples.chunks_exact(2) {
9350 let rgb = rgb_by_index[usize::from(sample[0])];
9351 output.extend_from_slice(&[rgb[0], rgb[1], rgb[2], sample[1]]);
9352 }
9353 if let Some(image) = crate::raster::RgbaImage::from_raw(
9354 indices_alpha.width(),
9355 indices_alpha.height(),
9356 output,
9357 ) {
9358 return DynamicImage::ImageRgba8(image);
9359 }
9360 }
9361
9362 DynamicImage::ImageRgba8(crate::raster::RgbaImage::from_fn(
9365 indices_alpha.width(),
9366 indices_alpha.height(),
9367 |x, y| {
9368 let pixel = indices_alpha.get_pixel(x, y);
9369 let rgb = rgb_by_index[usize::from(pixel[0])];
9370 crate::raster::Rgba([rgb[0], rgb[1], rgb[2], pixel[1]])
9371 },
9372 ))
9373}
9374
9375fn operational_palette(data: &PalettedData) -> Vec<u8> {
9378 let Some(source_palette) = data
9379 .info
9380 .as_ref()
9381 .and_then(|info| info.palette.as_ref())
9382 .map(|palette| &palette.rgb)
9383 else {
9384 return data.palette.clone();
9385 };
9386 if data.palette.starts_with(source_palette)
9387 && data.palette[source_palette.len()..]
9388 .iter()
9389 .all(|&component| component == 0)
9390 {
9391 source_palette.clone()
9392 } else {
9393 data.palette.clone()
9394 }
9395}
9396
9397const fn image_mode_name(mode: ImageMode) -> &'static str {
9398 match mode {
9399 ImageMode::L1 => "1",
9400 ImageMode::P8 => "P",
9401 ImageMode::L8 => "L",
9402 ImageMode::La8 | ImageMode::La16 => "LA",
9403 ImageMode::Rgb8 | ImageMode::Rgb16 | ImageMode::Rgb32F => "RGB",
9404 ImageMode::Rgba8 | ImageMode::Rgba16 | ImageMode::Rgba32F => "RGBA",
9405 ImageMode::Cmyk8 => "CMYK",
9406 ImageMode::L16 => "I;16",
9407 ImageMode::F32 => "F",
9408 ImageMode::I32 => "I",
9409 _ => "unknown",
9410 }
9411}
9412
9413pub fn preserve_mode(original: &DynamicImage, result: DynamicImage) -> DynamicImage {
9419 let orig_color = original.color();
9420 let res_color = result.color();
9421 if orig_color == res_color {
9422 return result;
9423 }
9424 match orig_color {
9425 crate::raster::ColorType::L8 => {
9426 let rgba = result.to_rgba8();
9429 let (w, h) = rgba.dimensions();
9430 let luma: Vec<u8> = rgba.pixels().map(|px| px[0]).collect();
9431 DynamicImage::ImageLuma8(
9432 crate::raster::GrayImage::from_raw(w, h, luma).unwrap_or_else(|| result.to_luma8()),
9433 )
9434 }
9435 crate::raster::ColorType::La8 => {
9436 let rgba = result.to_rgba8();
9438 let (w, h) = rgba.dimensions();
9439 let la: Vec<u8> = rgba.pixels().flat_map(|px| [px[0], px[3]]).collect();
9440 DynamicImage::ImageLumaA8(
9441 crate::raster::GrayAlphaImage::from_raw(w, h, la)
9442 .unwrap_or_else(|| result.to_luma_alpha8()),
9443 )
9444 }
9445 crate::raster::ColorType::Rgb8 => DynamicImage::ImageRgb8(result.to_rgb8()),
9446 crate::raster::ColorType::Rgba8 => DynamicImage::ImageRgba8(result.to_rgba8()),
9447 _ => result,
9448 }
9449}
9450pub fn stat_from_histogram(data: &[f64]) -> StatResult {
9456 let bands: Vec<Vec<f64>> = data
9457 .chunks(256)
9458 .map(|histogram| {
9459 let count: f64 = histogram.iter().sum();
9460 let sum: f64 = histogram
9461 .iter()
9462 .enumerate()
9463 .map(|(index, &frequency)| index as f64 * frequency)
9464 .sum();
9465 let sum2: f64 = histogram
9466 .iter()
9467 .enumerate()
9468 .map(|(index, &frequency)| {
9469 let value = index as f64;
9470 value * value * frequency
9471 })
9472 .sum();
9473 let mean = if count > 0.0 { sum / count } else { 0.0 };
9474 let rms = if count > 0.0 {
9475 (sum2 / count).sqrt()
9476 } else {
9477 0.0
9478 };
9479 let variance = if count > 0.0 {
9480 ((sum2 - (sum * sum) / count) / count).max(0.0)
9481 } else {
9482 0.0
9483 };
9484 let stddev = variance.sqrt();
9485
9486 let mut cumulative = 0.0;
9487 let half = (count / 2.0).floor();
9488 let mut median: f64 = 255.0;
9489 let mut min_bin: f64 = 255.0;
9490 let mut max_bin: f64 = 0.0;
9491 for (index, &frequency) in histogram.iter().enumerate() {
9492 cumulative += frequency;
9493 if cumulative > half && median == 255.0 {
9494 median = index as f64;
9495 }
9496 if frequency > 0.0 {
9497 min_bin = min_bin.min(index as f64);
9498 max_bin = max_bin.max(index as f64);
9499 }
9500 }
9501
9502 vec![
9503 count, sum, sum2, mean, median, rms, variance, stddev, min_bin, max_bin,
9504 ]
9505 })
9506 .collect();
9507 StatResult::from_bands(&bands)
9508}
9509
9510pub fn stat_from_list(data: &[f64]) -> (f64, f64, f64, f64, f64) {
9515 let count = data.len() as f64;
9516 let sum: f64 = data.iter().sum();
9517 let mean = if count > 0.0 { sum / count } else { 0.0 };
9518 let min_val = if count > 0.0 {
9519 data.iter().cloned().fold(f64::MAX, f64::min)
9520 } else {
9521 0.0
9522 };
9523 let max_val = if count > 0.0 {
9524 data.iter().cloned().fold(f64::NEG_INFINITY, f64::max)
9525 } else {
9526 0.0
9527 };
9528 (count, sum, mean, min_val, max_val)
9529}
9530
9531#[cfg(test)]
9532mod byte_export_tests {
9533 use super::{Image, PilError, PutDataValue, is_l16_mode, l16_uses_big_endian};
9534
9535 const MODES: &[(&str, usize)] = &[
9536 ("1", 1),
9537 ("L", 1),
9538 ("P", 1),
9539 ("LA", 2),
9540 ("PA", 2),
9541 ("RGB", 3),
9542 ("LAB", 3),
9543 ("RGBA", 4),
9544 ("RGBa", 4),
9545 ("RGBX", 4),
9546 ("CMYK", 4),
9547 ("HSV", 3),
9548 ("YCbCr", 3),
9549 ("I", 4),
9550 ("F", 4),
9551 ("I;16", 2),
9552 ("I;16L", 2),
9553 ("I;16B", 2),
9554 ("I;16N", 2),
9555 ];
9556
9557 #[test]
9558 fn native_default_exports_share_storage() -> Result<(), PilError> {
9559 for &(mode, channels) in MODES {
9560 if matches!(mode, "1" | "P")
9561 || (is_l16_mode(mode) && cfg!(target_endian = "big") != l16_uses_big_endian(mode))
9562 {
9563 continue;
9564 }
9565 for (width, height) in [(3, 2), (0, 3), (3, 0)] {
9566 let bytes: Vec<u8> = (0..channels * width as usize * height as usize)
9567 .map(|index| index.wrapping_mul(37).wrapping_add(11).to_le_bytes()[0])
9568 .collect();
9569 let image = Image::frombytes(mode, (width, height), &bytes)?;
9570 let storage = image.materialized_shared()?;
9571 let exported = image.tobytes_encoded_shared(mode, "raw", &[])?;
9572 assert_eq!(exported.as_ref(), bytes, "{mode} {width}x{height}");
9573 assert_eq!(
9574 exported.as_ref().as_ptr(),
9575 storage.as_bytes().as_ptr(),
9576 "native {mode} export should retain the materialized allocation"
9577 );
9578 }
9579 }
9580 Ok(())
9581 }
9582
9583 #[test]
9584 fn owned_frombytes_adopts_raw_raster_allocation() -> Result<(), PilError> {
9585 let bytes = vec![0x10, 0x20, 0x30, 0x40, 0x50, 0x60];
9586 let input_ptr = bytes.as_ptr();
9587 let image = Image::frombytes_owned("RGB", (2, 1), bytes)?;
9588 let storage = image.materialized_shared()?;
9589
9590 assert_eq!(storage.as_bytes().as_ptr(), input_ptr);
9591 assert_eq!(storage.as_bytes(), &[0x10, 0x20, 0x30, 0x40, 0x50, 0x60]);
9592 Ok(())
9593 }
9594
9595 #[test]
9596 fn shared_exports_preserve_encoder_layouts_and_errors() -> Result<(), PilError> {
9597 for &(source_mode, channels) in MODES {
9598 let bytes: Vec<u8> = (0..9 * 2 * channels)
9599 .map(|index| index.wrapping_mul(43).wrapping_add(17).to_le_bytes()[0])
9600 .collect();
9601 let image = Image::frombytes(source_mode, (9, 2), &bytes)?;
9602 for mode in [source_mode, "1", "RGB", "BGRA", "I;16L", "I;16B"] {
9603 for raw_mode in [
9604 None,
9605 Some(mode),
9606 Some("BGR"),
9607 Some("BGRA"),
9608 Some("RGBA"),
9609 Some("invalid"),
9610 ] {
9611 let args: Vec<String> = raw_mode.into_iter().map(str::to_owned).collect();
9612 for encoder in ["raw", "invalid"] {
9613 let existing = image
9614 .tobytes_encoded(mode, encoder, &args)
9615 .map_err(|error| format!("{error:?}"));
9616 let shared = image
9617 .tobytes_encoded_shared(mode, encoder, &args)
9618 .map(|bytes| bytes.as_ref().to_vec())
9619 .map_err(|error| format!("{error:?}"));
9620 assert_eq!(shared, existing, "{source_mode}: {mode}/{encoder}/{args:?}");
9621 }
9622 }
9623 }
9624 }
9625 Ok(())
9626 }
9627
9628 #[test]
9629 fn shared_scalar_exports_preserve_all_sample_bits() -> Result<(), PilError> {
9630 let words: [u32; 6] = [
9631 0x8000_0000,
9632 0x7fc0_1234,
9633 0x7f80_0001,
9634 0xff80_0000,
9635 0x8000_0001,
9636 0xffff_ffff,
9637 ];
9638 let bytes: Vec<u8> = words.into_iter().flat_map(u32::to_le_bytes).collect();
9639 for mode in ["I", "F"] {
9640 let image = Image::frombytes(mode, (3, 2), &bytes)?;
9641 let exported = image.tobytes_encoded_shared(mode, "raw", &[])?;
9642 assert_eq!(exported.as_ref(), bytes, "{mode}");
9643 }
9644 Ok(())
9645 }
9646
9647 #[test]
9648 fn exported_bytes_survive_image_mutation_and_drop() -> Result<(), PilError> {
9649 for mode in ["L", "P", "I;16N"] {
9650 let bytes = if mode == "I;16N" {
9651 vec![1, 2, 3, 4]
9652 } else {
9653 vec![1, 2]
9654 };
9655 let mut image = Image::frombytes(mode, (2, 1), &bytes)?;
9656 let exported = image.tobytes_encoded_shared(mode, "raw", &[])?;
9657 image.putdata_value_at(0, &PutDataValue::Number(77.0), 1.0, 0.0)?;
9658 assert_ne!(
9659 image.tobytes()?,
9660 bytes,
9661 "{mode} mutation must be observable"
9662 );
9663 drop(image);
9664 assert_eq!(
9665 exported.as_ref(),
9666 bytes,
9667 "{mode} export must stay immutable"
9668 );
9669 }
9670 Ok(())
9671 }
9672}
9673
9674#[cfg(test)]
9675mod putdata_shared_bytes_tests {
9676 use super::{Image, PilError};
9677 use crate::compute::Backend;
9678 use crate::pipeline::{PipelineOp, PixelMode};
9679 use bytes::Bytes;
9680
9681 #[test]
9682 fn native_l_putdata_keeps_the_shared_allocation_and_materializes_exactly()
9683 -> Result<(), PilError> {
9684 let payload = Bytes::from_static(&[13, 71, 209, 255]);
9685 let payload_ptr = payload.as_ptr();
9686 let mut image = Image::new(4, 1, "L", (0, 0, 0, 255))?;
9687
9688 assert!(image.putdata_shared_bytes_fast_path(payload, 4, 1.0, 0.0)?);
9689 let queued_ptr = match &image {
9690 Image::Pipeline { ops, .. } => match &ops.as_slice()[0] {
9691 PipelineOp::PutData {
9692 data,
9693 mode: PixelMode::L,
9694 } => data.as_ptr(),
9695 other => panic!("unexpected queued operation: {other:?}"),
9696 },
9697 other => panic!("putdata did not queue a pipeline: {other:?}"),
9698 };
9699 assert_eq!(queued_ptr, payload_ptr);
9700
9701 assert_eq!(
9702 image.use_backend(Backend::Cpu).tobytes()?,
9703 [13, 71, 209, 255]
9704 );
9705 Ok(())
9706 }
9707}
9708
9709#[cfg(test)]
9710mod getprojection_cmyk_tests {
9711 use super::{Image, PilError, PutDataValue};
9712
9713 #[test]
9714 fn cpu_known_zero_cmyk_projection_uses_sparse_writes() -> Result<(), PilError> {
9715 use crate::compute::Backend;
9716
9717 let mut image = Image::new(7, 3, "CMYK", (0, 0, 0, 0))?;
9718 image.putpixel(1, 0, 1, 0, 0, 0)?;
9719 image.putpixel(4, 1, 0, 1, 0, 0)?;
9720 image.putpixel(6, 2, 0, 0, 0, 1)?;
9721 assert!(matches!(
9722 &image,
9723 Image::Pipeline { source, .. }
9724 if matches!(source.as_ref(), Image::Loaded(data) if data.known_zero_fill)
9725 ));
9726 image = image.use_backend(Backend::Cpu);
9727
9728 assert_eq!(
9729 image.getprojection()?,
9730 (vec![0, 1, 0, 0, 1, 0, 1], vec![1, 1, 1])
9731 );
9732 Ok(())
9733 }
9734
9735 #[test]
9736 fn eager_pixel_data_mutation_invalidates_known_zero_source() -> Result<(), PilError> {
9737 use crate::compute::Backend;
9738
9739 let mut image = Image::new(4, 1, "CMYK", (0, 0, 0, 0))?;
9740 assert!(matches!(
9741 &image,
9742 Image::Loaded(data) if data.known_zero_fill
9743 ));
9744 image.putdata_value_at(1, &PutDataValue::Components(vec![1, 0, 0, 0]), 1.0, 0.0)?;
9745 assert!(matches!(
9746 &image,
9747 Image::Loaded(data) if !data.known_zero_fill
9748 ));
9749 image.putpixel(0, 0, 0, 0, 0, 0)?;
9750 image = image.use_backend(Backend::Cpu);
9751
9752 assert_eq!(image.getprojection()?, (vec![0, 1, 0, 0], vec![1]));
9753 Ok(())
9754 }
9755
9756 #[test]
9757 fn packed_cmyk_projection_covers_grouped_pixels_and_row_tails() -> Result<(), PilError> {
9758 let mut image = Image::new(7, 3, "CMYK", (0, 0, 0, 0))?;
9759 image.putpixel(1, 0, 1, 0, 0, 0)?;
9760 image.putpixel(4, 1, 0, 1, 0, 0)?;
9761 image.putpixel(6, 2, 0, 0, 1, 0)?;
9762 image.putpixel(2, 2, 0, 0, 0, 1)?;
9763
9764 assert_eq!(
9765 image.getprojection()?,
9766 (vec![0, 1, 1, 0, 1, 0, 1], vec![1, 1, 1])
9767 );
9768 Ok(())
9769 }
9770
9771 #[test]
9772 fn packed_cmyk_projection_preserves_empty_width_rows() -> Result<(), PilError> {
9773 let image = Image::new(0, 3, "CMYK", (0, 0, 0, 0))?;
9774 assert_eq!(image.getprojection()?, (vec![], vec![0, 0, 0]));
9775 Ok(())
9776 }
9777
9778 #[test]
9779 fn pending_cmyk_projection_applies_overwrites_without_changing_image() -> Result<(), PilError> {
9780 let mut image = Image::new(7, 3, "CMYK", (1, 0, 0, 0))?;
9781 for x in 0..7 {
9782 image.putpixel(x, 2, 0, 0, 0, 0)?;
9783 }
9784 for y in 0..2 {
9785 image.putpixel(4, y, 0, 0, 0, 0)?;
9786 }
9787 image.putpixel(3, 0, 0, 0, 0, 0)?;
9788 image.putpixel(3, 0, 1, 0, 0, 0)?;
9789
9790 assert_eq!(
9791 image.getprojection()?,
9792 (vec![1, 1, 1, 1, 0, 1, 1], vec![1, 1, 0])
9793 );
9794
9795 let mut expected = Vec::with_capacity(7 * 3 * 4);
9796 for y in 0..3 {
9797 for x in 0..7 {
9798 expected.extend_from_slice(if y == 2 || x == 4 {
9799 &[0, 0, 0, 0]
9800 } else {
9801 &[1, 0, 0, 0]
9802 });
9803 }
9804 }
9805 assert_eq!(image.tobytes()?, expected);
9806 Ok(())
9807 }
9808
9809 #[test]
9810 fn simd_pending_cmyk_projection_fuses_writes_and_reports_vector_execution()
9811 -> Result<(), PilError> {
9812 use crate::compute::Backend;
9813
9814 let mut image = Image::new(65, 3, "CMYK", (0, 0, 0, 0))?;
9815 image.putpixel(1, 0, 1, 0, 0, 0)?;
9816 image.putpixel(1, 0, 0, 0, 0, 0)?;
9817 image.putpixel(64, 1, 0, 1, 0, 0)?;
9818 image.putpixel(3, 2, 0, 0, 0, 1)?;
9819 let image = image.use_backend(Backend::Simd);
9820
9821 let previous = Backend::set_pipeline_telemetry_enabled(true);
9822 let projection = image.getprojection()?;
9823 let receipt = Backend::take_pipeline_telemetry();
9824 let operation_receipts = Backend::take_pipeline_operation_telemetry();
9825 Backend::set_pipeline_telemetry_enabled(previous);
9826
9827 let mut expected_horizontal = vec![0; 65];
9828 expected_horizontal[3] = 1;
9829 expected_horizontal[64] = 1;
9830 assert_eq!(projection, (expected_horizontal, vec![0, 1, 1]));
9831 let receipt = receipt.expect("SIMD terminal receipt");
9832 assert_eq!(receipt.1, Backend::Simd);
9833 assert_eq!(receipt.2, 4);
9834 assert_eq!(receipt.7, None);
9835 assert_eq!(operation_receipts.len(), 4);
9836 assert!(operation_receipts[0].vector_block_count > 0);
9837 Ok(())
9838 }
9839
9840 #[test]
9841 fn simd_known_zero_cmyk_projection_vectorizes_positive_writes_and_axis_tails()
9842 -> Result<(), PilError> {
9843 use crate::compute::Backend;
9844
9845 let mut image = Image::new(65, 3, "CMYK", (0, 0, 0, 0))?;
9846 image.putpixel(1, 0, 1, 0, 0, 0)?;
9847 image.putpixel(1, 0, 0, 1, 0, 0)?;
9848 image.putpixel(64, 2, 0, 0, 0, 1)?;
9849 let image = image.use_backend(Backend::Simd);
9850
9851 let previous = Backend::set_pipeline_telemetry_enabled(true);
9852 let projection = image.getprojection()?;
9853 let receipt = Backend::take_pipeline_telemetry();
9854 let operation_receipts = Backend::take_pipeline_operation_telemetry();
9855 Backend::set_pipeline_telemetry_enabled(previous);
9856
9857 let mut expected_horizontal = vec![0; 65];
9858 expected_horizontal[1] = 1;
9859 expected_horizontal[64] = 1;
9860 let mut expected_vertical = vec![0; 3];
9861 expected_vertical[0] = 1;
9862 expected_vertical[2] = 1;
9863 assert_eq!(projection, (expected_horizontal, expected_vertical));
9864 let receipt = receipt.expect("SIMD terminal receipt");
9865 assert_eq!(receipt.1, Backend::Simd);
9866 assert_eq!(receipt.2, 3);
9867 assert_eq!(receipt.7, None);
9868 assert_eq!(operation_receipts.len(), 3);
9869 assert_eq!(operation_receipts[0].vector_block_count, 16);
9870 Ok(())
9871 }
9872
9873 #[test]
9874 fn simd_known_zero_cmyk_projection_scans_when_write_limit_is_exceeded() -> Result<(), PilError>
9875 {
9876 use crate::compute::Backend;
9877
9878 let mut image = Image::new(9, 1, "CMYK", (0, 0, 0, 0))?;
9879 for x in 0..9 {
9880 image.putpixel(x, 0, 0, 0, 1, 0)?;
9881 }
9882 let image = image.use_backend(Backend::Simd);
9883
9884 let previous = Backend::set_pipeline_telemetry_enabled(true);
9885 let projection = image.getprojection()?;
9886 let receipt = Backend::take_pipeline_telemetry();
9887 let operation_receipts = Backend::take_pipeline_operation_telemetry();
9888 Backend::set_pipeline_telemetry_enabled(previous);
9889
9890 assert_eq!(projection, (vec![1; 9], vec![1]));
9891 let receipt = receipt.expect("SIMD terminal receipt");
9892 assert_eq!(receipt.1, Backend::Simd);
9893 assert_eq!(receipt.2, 9);
9894 assert_eq!(receipt.7, None);
9895 assert_eq!(operation_receipts[0].vector_block_count, 2);
9896 Ok(())
9897 }
9898
9899 #[cfg(feature = "gpu")]
9900 #[test]
9901 fn gpu_pending_cmyk_projection_applies_zero_overwrites_across_wide_row_boundaries()
9902 -> Result<(), PilError> {
9903 use crate::compute::Backend;
9904
9905 let source = crate::raster::DynamicImage::ImageRgba8(crate::raster::RgbaImage::from_pixel(
9906 515,
9907 19,
9908 crate::raster::Rgba([0; 4]),
9909 ));
9910 let ops = [
9911 crate::pipeline::PipelineOp::PutPixel {
9912 x: 255,
9913 y: 16,
9914 color: (1, 0, 0, 0),
9915 palette_index: false,
9916 },
9917 crate::pipeline::PipelineOp::PutPixel {
9918 x: 255,
9919 y: 16,
9920 color: (0, 0, 0, 0),
9921 palette_index: false,
9922 },
9923 crate::pipeline::PipelineOp::PutPixel {
9924 x: 0,
9925 y: 0,
9926 color: (0, 0, 1, 0),
9927 palette_index: false,
9928 },
9929 crate::pipeline::PipelineOp::PutPixel {
9930 x: 0,
9931 y: 0,
9932 color: (0, 0, 0, 0),
9933 palette_index: false,
9934 },
9935 crate::pipeline::PipelineOp::PutPixel {
9936 x: 257,
9937 y: 7,
9938 color: (0, 1, 0, 0),
9939 palette_index: false,
9940 },
9941 crate::pipeline::PipelineOp::PutPixel {
9942 x: 514,
9943 y: 18,
9944 color: (0, 0, 0, 1),
9945 palette_index: false,
9946 },
9947 ];
9948 if !crate::compute::gpu_cmyk_projection_terminal_supported(&source, &ops) {
9949 return Ok(());
9950 }
9951
9952 let mut image = Image::new(515, 19, "CMYK", (0, 0, 0, 0))?;
9953 image.putpixel(255, 16, 1, 0, 0, 0)?;
9954 image.putpixel(255, 16, 0, 0, 0, 0)?;
9955 image.putpixel(0, 0, 0, 0, 1, 0)?;
9956 image.putpixel(0, 0, 0, 0, 0, 0)?;
9957 image.putpixel(257, 7, 0, 1, 0, 0)?;
9958 image.putpixel(514, 18, 0, 0, 0, 1)?;
9959 image = image.use_backend(Backend::Gpu);
9960
9961 let previous = Backend::set_pipeline_telemetry_enabled(true);
9962 let result = image.getprojection();
9963 let receipt = Backend::take_pipeline_telemetry();
9964 Backend::set_pipeline_telemetry_enabled(previous);
9965
9966 let (horizontal, vertical) = result?;
9967 let mut expected_horizontal = vec![0; 515];
9968 expected_horizontal[257] = 1;
9969 expected_horizontal[514] = 1;
9970 let mut expected_vertical = vec![0; 19];
9971 expected_vertical[7] = 1;
9972 expected_vertical[18] = 1;
9973 assert_eq!(
9974 (horizontal, vertical),
9975 (expected_horizontal, expected_vertical)
9976 );
9977
9978 let receipt = receipt.expect("GPU projection terminal receipt");
9979 assert_eq!(receipt.0, Some(Backend::Gpu));
9980 assert_eq!(receipt.1, Backend::Gpu);
9981 assert_eq!(receipt.2, ops.len());
9982 assert_eq!(receipt.6, Some(1));
9983 assert_eq!(receipt.7, None);
9984 let resources = receipt.8.expect("GPU projection resources");
9985 assert_eq!(resources.upload_bytes, 0);
9986 assert_eq!(resources.readback_bytes, 72);
9987 assert_eq!(resources.full_frame_copy_count, 0);
9988 Ok(())
9989 }
9990
9991 #[cfg(feature = "gpu")]
9992 #[test]
9993 fn gpu_pending_cmyk_projection_applies_overwrites_to_nonzero_source() -> Result<(), PilError> {
9994 use crate::compute::Backend;
9995
9996 let (width, height) = (515, 19);
9997 let mut bytes = vec![0; width as usize * height as usize * 4];
9998 let source_offset = (3 * width as usize + 100) * 4;
9999 bytes[source_offset] = 1;
10000 let source = crate::raster::DynamicImage::ImageRgba8(
10001 crate::raster::RgbaImage::from_raw(width, height, bytes.clone())
10002 .expect("source carrier dimensions"),
10003 );
10004 let ops = [
10005 crate::pipeline::PipelineOp::PutPixel {
10006 x: 100,
10007 y: 3,
10008 color: (0, 0, 0, 0),
10009 palette_index: false,
10010 },
10011 crate::pipeline::PipelineOp::PutPixel {
10012 x: 257,
10013 y: 7,
10014 color: (0, 1, 0, 0),
10015 palette_index: false,
10016 },
10017 crate::pipeline::PipelineOp::PutPixel {
10018 x: 514,
10019 y: 18,
10020 color: (0, 0, 0, 1),
10021 palette_index: false,
10022 },
10023 ];
10024 if !crate::compute::gpu_cmyk_projection_terminal_supported(&source, &ops) {
10025 return Ok(());
10026 }
10027
10028 let mut image = Image::frombytes("CMYK", (width, height), &bytes)?;
10029 image.putpixel(100, 3, 0, 0, 0, 0)?;
10030 image.putpixel(257, 7, 0, 1, 0, 0)?;
10031 image.putpixel(514, 18, 0, 0, 0, 1)?;
10032 image = image.use_backend(Backend::Gpu);
10033
10034 let previous = Backend::set_pipeline_telemetry_enabled(true);
10035 let result = image.getprojection();
10036 let receipt = Backend::take_pipeline_telemetry();
10037 Backend::set_pipeline_telemetry_enabled(previous);
10038
10039 let (horizontal, vertical) = result?;
10040 let mut expected_horizontal = vec![0; width as usize];
10041 expected_horizontal[257] = 1;
10042 expected_horizontal[514] = 1;
10043 let mut expected_vertical = vec![0; height as usize];
10044 expected_vertical[7] = 1;
10045 expected_vertical[18] = 1;
10046 assert_eq!(
10047 (horizontal, vertical),
10048 (expected_horizontal, expected_vertical)
10049 );
10050
10051 let receipt = receipt.expect("GPU projection terminal receipt");
10052 assert_eq!(receipt.0, Some(Backend::Gpu));
10053 assert_eq!(receipt.1, Backend::Gpu);
10054 assert_eq!(receipt.2, ops.len());
10055 assert_eq!(receipt.6, Some(1));
10056 assert_eq!(receipt.7, None);
10057 Ok(())
10058 }
10059}
10060
10061#[cfg(test)]
10062mod getprojection_rgb_pipeline_tests {
10063 use super::{Image, PilError};
10064
10065 #[test]
10066 fn cpu_zero_rgb_source_preserves_sparse_overwrite_order() -> Result<(), PilError> {
10067 use crate::compute::Backend;
10068
10069 let mut image = Image::new(17, 4, "RGB", (0, 0, 0, 255))?;
10070 image.putpixel(0, 0, 1, 0, 0, 0)?;
10071 image.putpixel(16, 3, 0, 1, 0, 0)?;
10072 image.putpixel(0, 0, 0, 0, 0, 255)?;
10073 image = image.use_backend(Backend::Cpu);
10074
10075 let previous = Backend::set_pipeline_telemetry_enabled(true);
10076 let projection = image.getprojection()?;
10077 let receipt = Backend::take_pipeline_telemetry();
10078 Backend::set_pipeline_telemetry_enabled(previous);
10079
10080 let mut expected_horizontal = vec![0; 17];
10081 expected_horizontal[16] = 1;
10082 assert_eq!((expected_horizontal, vec![0, 0, 0, 1]), projection);
10083 let receipt = receipt.expect("CPU sparse RGB projection terminal receipt");
10084 assert_eq!(receipt.0, Some(Backend::Cpu));
10085 assert_eq!(receipt.1, Backend::Cpu);
10086 assert_eq!(receipt.2, 3);
10087 assert_eq!(receipt.7, None);
10088 assert_eq!(
10089 receipt
10090 .8
10091 .expect("CPU terminal resource receipt")
10092 .fused_operation_count,
10093 3
10094 );
10095 Ok(())
10096 }
10097
10098 #[test]
10099 fn cpu_pending_rgb_projection_applies_overwrites_and_ignores_alpha() -> Result<(), PilError> {
10100 use crate::compute::Backend;
10101
10102 let mut image = Image::new(7, 4, "RGB", (1, 0, 0, 255))?;
10103 for x in 0..7 {
10104 image.putpixel(x, 3, 0, 0, 0, 255)?;
10105 }
10106 for y in 0..3 {
10107 image.putpixel(4, y, 0, 0, 0, 255)?;
10108 }
10109 image.putpixel(3, 0, 0, 0, 0, 255)?;
10110 image.putpixel(3, 0, 0, 1, 0, 0)?;
10111 image.putpixel(6, 3, 0, 0, 0, 255)?;
10112 image = image.use_backend(Backend::Cpu);
10113
10114 assert_eq!(
10115 image.getprojection()?,
10116 (vec![1, 1, 1, 1, 0, 1, 1], vec![1, 1, 1, 0])
10117 );
10118 Ok(())
10119 }
10120
10121 #[test]
10122 fn simd_pending_rgb_projection_executes_vector_blocks() -> Result<(), PilError> {
10123 use crate::compute::Backend;
10124
10125 let mut image = Image::new(17, 4, "RGB", (0, 0, 0, 255))?;
10126 image.putpixel(0, 0, 1, 0, 0, 0)?;
10127 image.putpixel(16, 3, 0, 1, 0, 0)?;
10128 image.putpixel(4, 2, 0, 0, 0, 255)?;
10129 image = image.use_backend(Backend::Simd);
10130
10131 let previous = Backend::set_pipeline_telemetry_enabled(true);
10132 let projection = image.getprojection()?;
10133 let receipt = Backend::take_pipeline_telemetry();
10134 let operation_receipts = Backend::take_pipeline_operation_telemetry();
10135 Backend::set_pipeline_telemetry_enabled(previous);
10136
10137 let mut expected_horizontal = vec![0; 17];
10138 expected_horizontal[0] = 1;
10139 expected_horizontal[16] = 1;
10140 assert_eq!(projection, (expected_horizontal, vec![1, 0, 0, 1]));
10141 let receipt = receipt.expect("SIMD RGB projection terminal receipt");
10142 assert_eq!(receipt.1, Backend::Simd);
10143 assert_eq!(receipt.2, 3);
10144 assert_eq!(receipt.7, None);
10145 assert_eq!(operation_receipts.len(), 3);
10146 assert!(operation_receipts[0].vector_block_count > 0);
10147 Ok(())
10148 }
10149
10150 #[cfg(feature = "gpu")]
10151 #[test]
10152 fn gpu_pending_rgb_projection_executes_terminal_and_ignores_alpha() -> Result<(), PilError> {
10153 use crate::compute::Backend;
10154
10155 let source = crate::raster::DynamicImage::ImageRgb8(crate::raster::RgbImage::from_pixel(
10156 17,
10157 4,
10158 crate::raster::Rgb([0; 3]),
10159 ));
10160 let ops = [
10161 crate::pipeline::PipelineOp::PutPixel {
10162 x: 0,
10163 y: 0,
10164 color: (1, 0, 0, 0),
10165 palette_index: false,
10166 },
10167 crate::pipeline::PipelineOp::PutPixel {
10168 x: 16,
10169 y: 3,
10170 color: (0, 1, 0, 0),
10171 palette_index: false,
10172 },
10173 crate::pipeline::PipelineOp::PutPixel {
10174 x: 4,
10175 y: 2,
10176 color: (0, 0, 0, 255),
10177 palette_index: false,
10178 },
10179 ];
10180 if !crate::compute::gpu_rgb_projection_terminal_supported(&source, &ops) {
10181 return Ok(());
10182 }
10183
10184 let mut image = Image::new(17, 4, "RGB", (0, 0, 0, 255))?;
10185 image.putpixel(0, 0, 1, 0, 0, 0)?;
10186 image.putpixel(16, 3, 0, 1, 0, 0)?;
10187 image.putpixel(4, 2, 0, 0, 0, 255)?;
10188 image = image.use_backend(Backend::Gpu);
10189
10190 let previous = Backend::set_pipeline_telemetry_enabled(true);
10191 let result = image.getprojection();
10192 let receipt = Backend::take_pipeline_telemetry();
10193 Backend::set_pipeline_telemetry_enabled(previous);
10194
10195 let (horizontal, vertical) = result?;
10196 let mut expected_horizontal = vec![0; 17];
10197 expected_horizontal[0] = 1;
10198 expected_horizontal[16] = 1;
10199 assert_eq!(
10200 (horizontal, vertical),
10201 (expected_horizontal, vec![1, 0, 0, 1])
10202 );
10203 let receipt = receipt.expect("GPU RGB projection terminal receipt");
10204 assert_eq!(receipt.0, Some(Backend::Gpu));
10205 assert_eq!(receipt.1, Backend::Gpu);
10206 assert_eq!(receipt.2, ops.len());
10207 assert_eq!(receipt.6, Some(1));
10208 assert_eq!(receipt.7, None);
10209 Ok(())
10210 }
10211}
10212
10213#[cfg(test)]
10214mod compatibility_info_tests {
10215 use super::{Image, ImageInfoValue, PilError};
10216
10217 #[test]
10218 fn crop_after_pipeline_preserves_jpeg_info() -> Result<(), PilError> {
10219 let image = Image::open_bytes(
10220 include_bytes!("../tests/fixtures/assets/image/rgb-small.jpg").to_vec(),
10221 )?;
10222 let expected = image.compatibility_info();
10223 assert!(expected.iter().any(|(key, _)| key == "jfif"));
10224 let inverted = crate::ops::imageops::invert(&image)?;
10225 let cropped = inverted.crop(Some((0, 0, 2, 2)))?;
10226 assert_eq!(cropped.compatibility_info(), expected);
10227 assert!(cropped.source_format().is_none());
10228 Ok(())
10229 }
10230
10231 #[test]
10232 fn webp_timing_defaults_appear_only_after_load() -> Result<(), PilError> {
10233 let mut image = Image::open_bytes(
10234 include_bytes!("../tests/fixtures/assets/image/rgb-small.webp").to_vec(),
10235 )?;
10236 let expected = [
10237 ("timestamp".to_owned(), ImageInfoValue::Integer(0)),
10238 ("duration".to_owned(), ImageInfoValue::Integer(0)),
10239 ];
10240
10241 assert!(!image.is_materialized());
10242 let lazy_info = image.compatibility_info();
10243 assert!(
10244 lazy_info
10245 .iter()
10246 .all(|(key, _)| key != "timestamp" && key != "duration")
10247 );
10248
10249 image.load()?;
10250 let loaded_info = image.compatibility_info();
10251 assert!(expected.iter().all(|field| loaded_info.contains(field)));
10252 Ok(())
10253 }
10254}
10255
10256#[cfg(test)]
10257#[path = "image_getchannel_receipt_tests.rs"]
10258mod getchannel_receipt_tests;