From 15d07a47aef700cd5f80843756ffe885ed80ec2e Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:31:41 +0000 Subject: [PATCH 1/3] PDF/X-4: keep placed RGB images ICCBased when embedded ICC is dropped by PDF 1.6 (#3341) --- crates/pdf/src/export/images.rs | 114 ++++++++++++++++++++++++----- crates/pdf/src/lib.rs | 4 +- crates/pdf/src/pdfx/tests.rs | 124 +++++++++++++++++++++++++++++++- 3 files changed, 221 insertions(+), 21 deletions(-) diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 1c10452dd..2908fff57 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -58,6 +58,34 @@ pub(super) fn is_grey_icc(icc: &[u8]) -> bool { icc.get(16..20) == Some(b"GRAY".as_slice()) } +/// Whether an ICC profile describes CMYK. +fn is_cmyk_icc(icc: &[u8]) -> bool { + icc.get(16..20) == Some(b"CMYK".as_slice()) +} + +/// Whether krilla embeds `icc` as `/ICCBased` in a PDF 1.6 (PDF/X-4) file. +/// +/// krilla's `PdfVersion::Pdf16::supports_icc` checks `major <= 4 && minor <= 1`, so ICC v2.2–2.4 +/// and v4.2+ profiles (such as LittleCMS/Pillow sRGB v4.4 or sRGB2014 v2.4) are dropped to +/// `/DeviceRGB` if passed through unchanged. +fn pdf16_accepts_icc(icc: &[u8]) -> bool { + icc.get(8).is_some_and(|&major| major <= 4) && icc.get(9).is_some_and(|&minor| (minor >> 4) <= 1) +} + +/// Whether krilla embeds `icc` as an RGB `/ICCBased` space in PDF 1.6. +fn pdf16_accepts_rgb_icc(icc: &[u8]) -> bool { + is_rgb_icc(icc) && pdf16_accepts_icc(icc) +} + +/// Whether `icc` is a readable RGB profile whose colours differ from sRGB (e.g. Display P3 or +/// Adobe RGB), so tagging raw pixels with `SRGB_ICC` without converting them would shift colour. +fn needs_srgb_conversion(icc: &[u8]) -> bool { + is_rgb_icc(icc) + && icc.len() <= designcraft_images::colour::MAX_ICC_BYTES + && craft_cms::Profile::parse(icc) + .is_ok_and(|p| p.color_space == craft_cms::ColorSpace::Rgb && !p.same_colors(craft_cms::Builtin::Srgb.profile())) +} + /// Whether `data` decodes to grey (with or without alpha), read from its header. pub(super) fn is_grey(data: &[u8]) -> bool { craft_image_codecs::inspect_raster(data).ok().flatten().is_some_and(|info| { @@ -68,25 +96,47 @@ pub(super) fn is_grey(data: &[u8]) -> bool { }) } -/// A JPEG, passed through. With `tag_rgb`, a JPEG keeps its own profile, and one without gets -/// sRGB. krilla uses a profile only when its channels match the JPEG's, so a grey or CMYK JPEG -/// without a profile stays DeviceGray or DeviceCMYK. +/// A JPEG, passed through. With `tag_rgb`, a JPEG keeps its own profile when PDF 1.6 accepts it +/// and its colour space matches the JPEG's channels; an RGB JPEG whose profile PDF 1.6 drops is +/// tagged with sRGB (after converting pixels to sRGB if the profile isn't sRGB), and an untagged +/// RGB JPEG gets sRGB. Grey and CMYK JPEGs without an accepted matching profile stay DeviceGray +/// or DeviceCMYK. pub(super) fn jpeg(data: krilla::Data, icc: impl FnOnce() -> Option>, mode: RasterMode) -> Option { if !mode.tag_rgb { return Image::from_jpeg(data, mode.interpolate).ok(); } - let icc: krilla::Data = match icc() { - Some(own) => own.into(), - None => SRGB_ICC.into(), - }; - Image::from_jpeg_with_icc(data, Some(icc), mode.interpolate).ok() + let color = craft_image_codecs::inspect_raster(data.as_ref()).ok().flatten().map(|info| info.color_type); + let own = icc(); + let keep_own = own.as_deref().is_some_and(|p| { + pdf16_accepts_icc(p) + && match color { + Some(craft_image_codecs::RasterColorType::Gray | craft_image_codecs::RasterColorType::Bitmap) => is_grey_icc(p), + Some(craft_image_codecs::RasterColorType::Cmyk) => is_cmyk_icc(p), + _ => is_rgb_icc(p), + } + }); + if keep_own { + return Image::from_jpeg_with_icc(data, own.map(Into::into), mode.interpolate).ok(); + } + let is_rgb = !matches!( + color, + Some(craft_image_codecs::RasterColorType::Gray | craft_image_codecs::RasterColorType::Bitmap | craft_image_codecs::RasterColorType::Cmyk) + ); + if is_rgb + && own.as_deref().is_some_and(needs_srgb_conversion) + && let Some(rgba) = designcraft_images::decode_rgba(data.as_ref()) + { + return SrgbImage::new(rgba).and_then(|img| Image::from_custom(img, mode.interpolate).ok()); + } + Image::from_jpeg_with_icc(data, Some(SRGB_ICC.into()), mode.interpolate).ok() } -/// Whether krilla would write this PNG, GIF or WebP as untagged RGB: not grey, and no profile of -/// its own. The header inspection doesn't read WebP, which has no grey form, so a file it can't -/// read counts as colour. +/// Whether krilla would write this PNG, GIF or WebP as untagged RGB in PDF 1.6: not grey, and +/// either no profile of its own or one krilla drops (wrong colour space or ICC version past 4.1). +/// The header inspection doesn't read WebP, which has no grey form, so a file it can't read counts +/// as colour. fn untagged_rgb(data: &[u8]) -> bool { - !is_grey(data) && embedded_icc(data).is_none() + !is_grey(data) && !embedded_icc(data).is_some_and(|p| pdf16_accepts_rgb_icc(&p)) } pub(super) fn lossless(data: &Arc>, fmt: Option, mode: RasterMode) -> Option { @@ -165,7 +215,8 @@ thread_local! { } /// Opaque raster → JPEG (quality 90). `None` when the image has transparency, is too large or -/// can't be decoded. With `tag_rgb`, the JPEG keeps the source's RGB profile, or gets sRGB. +/// can't be decoded. With `tag_rgb`, the JPEG keeps the source's profile when PDF 1.6 accepts it, +/// or converts/tags to sRGB. pub(super) fn recompress(data: &[u8], mode: RasterMode) -> Option { if designcraft_images::too_large_to_decode(data) { return None; @@ -181,14 +232,43 @@ pub(super) fn recompress(data: &[u8], mode: RasterMode) -> Option { } // A grey image stays a grey JPEG (#1426). let grey = img.layout().is_gray(); - let jpeg_image = if grey { - img.convert(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) + let icc = img.icc.as_deref(); + let (jpeg_image, out_icc) = if grey { + ( + img.convert(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8), + mode.tag_rgb.then(|| icc.filter(|p| is_grey_icc(p) && pdf16_accepts_icc(p)).map(<[u8]>::to_vec)).flatten(), + ) + } else if mode.tag_rgb && icc.is_some_and(|p| !pdf16_accepts_rgb_icc(p) && needs_srgb_conversion(p)) { + let converted = image::RgbaImage::from_raw(img.width(), img.height(), rgba).and_then(|rgba_img| { + designcraft_images::colour::to_display_rgba( + designcraft_images::colour::Pixels::Rgb(rgba_img), + icc, + &designcraft_images::colour::DisplayColour::active(), + ) + })?; + let pixels = usize::try_from(converted.width()).ok()?.checked_mul(usize::try_from(converted.height()).ok()?)?; + let mut rgb = Vec::with_capacity(pixels.checked_mul(3)?); + for p in converted.pixels() { + rgb.extend_from_slice(&p.0[..3]); + } + let converted_img = craft_image_codecs::Image::from_raw( + converted.width(), + converted.height(), + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U8, + rgb, + ) + .ok()?; + (converted_img, None) } else { - img.convert(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) + ( + img.convert(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8), + mode.tag_rgb.then(|| icc.filter(|p| is_rgb_icc(p) && pdf16_accepts_icc(p)).map(<[u8]>::to_vec)).flatten(), + ) }; let options = craft_image_codecs::EncodeOptions { jpeg_quality: 90, ..Default::default() }; let buf = craft_image_codecs::encode(&jpeg_image, craft_image_codecs::Format::Jpeg, &options).ok()?; - jpeg(buf.into(), || embedded_icc(data).filter(|p| if grey { is_grey_icc(p) } else { is_rgb_icc(p) }), mode) + jpeg(buf.into(), || out_icc, mode) } #[cfg(test)] diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 5b9603d38..26da905e9 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -21,8 +21,8 @@ //! Appearance of Black says so) as `/op` and `/OP` with `/OPM 1`; left out of PDF/A. //! - **Images:** clipped to their frame; JPEG data is passed through, PNG/GIF/WebP are embedded //! losslessly (or re-encoded as JPEG with [`PdfOptions::compress_images`]). PDF/X-4 and PDF/A -//! images are written without interpolation. In PDF/X-4 an RGB image without a profile of its own -//! carries sRGB (`assets/icc/sRGB-v2-magic.icc`). +//! images are written without interpolation. In PDF/X-4 an RGB image without a PDF 1.6-compatible +//! profile of its own carries sRGB (`assets/icc/sRGB-v2-magic.icc`). //! - **Text as real text:** the composed glyph runs are emitted with embedded, subsetted fonts and a //! Unicode mapping taken from the story text (ligatures, page numbers and inserted hyphens get the //! right characters), so text is selectable and searchable. diff --git a/crates/pdf/src/pdfx/tests.rs b/crates/pdf/src/pdfx/tests.rs index 6fc7fb90d..2a3fb0e82 100644 --- a/crates/pdf/src/pdfx/tests.rs +++ b/crates/pdf/src/pdfx/tests.rs @@ -407,9 +407,129 @@ fn own_profiles_and_grey_stay() { let mut d = Document::new(&NewDocument::default()); place(&mut d, "grey.png", png(true, None), (4.0, 2.0), (72.0, 72.0)); place(&mut d, "tagged.png", png(false, Some(rgb_icc())), (4.0, 2.0), (72.0, 172.0)); + place(&mut d, "tagged.jpg", encode_with_icc(craft_image_codecs::Format::Jpeg, false, [0, 128, 255, 255], rgb_icc()), (4.0, 2.0), (72.0, 272.0)); let r = x4(&d); - assert_eq!(image_spaces(&r.bytes), ["DeviceGray", "[ICCBased"]); - assert_eq!(image_profiles(&r.bytes), [rgb_icc()]); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert_eq!(image_spaces(&r.bytes), ["DeviceGray", "[ICCBased", "[ICCBased"]); + assert_eq!(image_profiles(&r.bytes), [rgb_icc(), rgb_icc()]); +} + +/// Encode a 4 × 2 RGB or RGBA image with `icc` embedded in `format`. +fn encode_with_icc(format: craft_image_codecs::Format, rgba: bool, color: [u8; 4], icc: Vec) -> Vec { + let (layout, pixels) = if rgba { + (craft_image_codecs::ChannelLayout::Rgba, color.repeat(8)) + } else { + (craft_image_codecs::ChannelLayout::Rgb, [color[0], color[1], color[2]].repeat(8)) + }; + let img = craft_image_codecs::Image::from_raw(4, 2, layout, craft_image_codecs::SampleType::U8, pixels).unwrap().with_icc(Some(icc)); + let opts = craft_image_codecs::EncodeOptions { embed_icc: true, ..Default::default() }; + craft_image_codecs::encode(&img, format, &opts).unwrap() +} + +/// Placed RGB/RGBA images with an embedded sRGB profile whose ICC version PDF 1.6 / krilla drops +/// (v2.4, v4.2, v4.3, v4.4) or a mismatched profile must still be written as `/ICCBased` in +/// PDF/X-4 rather than falling back to `/DeviceRGB` (#3341). +#[test] +fn embedded_srgb_icc_past_pdf16_stays_iccbased_in_pdfx4() { + let srgb_v44 = { + let mut p = craft_cms::Builtin::Srgb.profile().clone().with_encoded_bytes().to_bytes().to_vec(); + p[8] = 4; + p[9] = 0x40; + p + }; + let srgb_v24 = { + let mut p = crate::export::SRGB_ICC.to_vec(); + p[8] = 2; + p[9] = 0x40; + p + }; + let mut wrong_space = rgb_icc(); + wrong_space[16..20].copy_from_slice(b"GRAY"); + + let mut d = Document::new(&NewDocument::default()); + let cases = [ + ("srgb-v44.jpg", encode_with_icc(craft_image_codecs::Format::Jpeg, false, [200, 40, 20, 255], srgb_v44.clone())), + ("srgb-v24.jpg", encode_with_icc(craft_image_codecs::Format::Jpeg, false, [20, 200, 40, 255], srgb_v24.clone())), + ("srgb-v44.png", encode_with_icc(craft_image_codecs::Format::Png, false, [40, 20, 200, 255], srgb_v44.clone())), + ("srgb-v44-alpha.png", encode_with_icc(craft_image_codecs::Format::Png, true, [200, 180, 20, 128], srgb_v44.clone())), + ("srgb-v44.webp", encode_with_icc(craft_image_codecs::Format::WebP, false, [20, 180, 200, 255], srgb_v44)), + ("wrong-icc.jpg", encode_with_icc(craft_image_codecs::Format::Jpeg, false, [180, 20, 180, 255], wrong_space.clone())), + ("wrong-icc.png", encode_with_icc(craft_image_codecs::Format::Png, false, [120, 90, 60, 255], wrong_space)), + ]; + for (i, (name, data)) in cases.into_iter().enumerate() { + place(&mut d, name, data, (4.0, 2.0), (72.0, 72.0 + 40.0 * i as f64)); + } + + for compress_images in [false, true] { + let opts = PdfOptions { standard: Standard::PdfX4, compress_images, ..Default::default() }; + let r = export_pdf_with_report(&d, &Cache::new(), &opts).unwrap(); + assert!(r.warnings.is_empty(), "compress_images {compress_images}: {:?}", r.warnings); + assert!(check_pdfx4(&r.bytes).is_empty(), "compress_images {compress_images}: {:?}", check_pdfx4(&r.bytes)); + // 7 colour images (all ICCBased) + 1 DeviceGray SMask for the RGBA PNG. + let mut expected = vec!["DeviceGray".to_string()]; + expected.extend(std::iter::repeat_n("[ICCBased".to_string(), 7)); + expected.sort(); + assert_eq!(image_spaces(&r.bytes), expected, "compress_images {compress_images}"); + let profiles = image_profiles(&r.bytes); + assert_eq!(profiles.len(), 7, "compress_images {compress_images}"); + assert!(profiles.iter().all(|p| p == crate::export::SRGB_ICC), "fallback profile is sRGB v2.1"); + } + + // sRGB v4.4 JPEG keeps DCTDecode passthrough without re-encoding. + let mut single = Document::new(&NewDocument::default()); + let jpg = encode_with_icc(craft_image_codecs::Format::Jpeg, false, [200, 40, 20, 255], srgb_v24); + place(&mut single, "srgb-v24.jpg", jpg, (4.0, 2.0), (72.0, 72.0)); + let r = x4(&single); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert!(String::from_utf8_lossy(&r.bytes).contains("/DCTDecode"), "sRGB JPEG keeps DCTDecode passthrough"); +} + +/// A wide-gamut RGB image whose embedded ICC version PDF 1.6 / krilla drops (e.g. Display P3 v4.3) +/// is converted to sRGB pixels before being tagged with sRGB v2.1, so colours are not shifted. +#[test] +fn embedded_wide_gamut_icc_past_pdf16_converts_to_srgb_in_pdfx4() { + let p3 = craft_cms::Builtin::DisplayP3.profile().clone().with_encoded_bytes().to_bytes().to_vec(); + let src_color = [60, 200, 60, 255]; + let p3_png = encode_with_icc(craft_image_codecs::Format::Png, false, src_color, p3.clone()); + let p3_jpg = encode_with_icc(craft_image_codecs::Format::Jpeg, false, src_color, p3); + let expected_srgb = designcraft_images::decode_rgba(&p3_png).unwrap().get_pixel(0, 0).0; + // Sanity: Display P3 green shifts noticeably when converted to sRGB. + assert!(expected_srgb[0].abs_diff(src_color[0]) > 10 || expected_srgb[1].abs_diff(src_color[1]) > 5); + + for (name, bytes) in [("p3.png", p3_png), ("p3.jpg", p3_jpg)] { + let mut d = Document::new(&NewDocument::default()); + place(&mut d, name, bytes, (4.0, 2.0), (72.0, 72.0)); + for compress_images in [false, true] { + let opts = PdfOptions { standard: Standard::PdfX4, compress_images, ..Default::default() }; + let r = export_pdf_with_report(&d, &Cache::new(), &opts).unwrap(); + assert!(r.warnings.is_empty(), "{name} compress={compress_images}: {:?}", r.warnings); + assert_eq!(image_spaces(&r.bytes), ["[ICCBased"], "{name} compress={compress_images}"); + assert_eq!(image_profiles(&r.bytes), [crate::export::SRGB_ICC], "{name} compress={compress_images}"); + // Decode the written image stream (either raw RGB8 or JPEG) and verify sRGB conversion. + let pdf = craft_pdf::syntax::Pdf::new(r.bytes).unwrap(); + let stream = pdf + .objects() + .into_iter() + .filter_map(|o| o.into_stream()) + .find(|s| s.dict().get::(b"Subtype").is_some_and(|n| n.as_str() == "Image")) + .unwrap(); + let px = if stream.dict().get::(b"Filter").is_some_and(|f| f.as_str() == "DCTDecode") { + let raw_jpg = stream.raw_data(); + let dec = craft_image_codecs::decode(&raw_jpg).unwrap().to_rgba8(); + [dec[0], dec[1], dec[2]] + } else { + let raw = stream.decoded().unwrap(); + [raw[0], raw[1], raw[2]] + }; + for ch in 0..3 { + assert!( + px[ch].abs_diff(expected_srgb[ch]) <= 4, + "{name} compress={compress_images} channel {ch}: got {px:?}, expected ~{:?} (unconverted {src_color:?})", + &expected_srgb[..3] + ); + } + } + } } /// Every image constructor asked for interpolation, which PDF/X-4 and PDF/A forbid: PDF/A From d3915f2c375440eeb2a0bbadfdc3314f29b292b8 Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:46:46 +0000 Subject: [PATCH 2/3] PDF/X-4: fail instead of tagging unconverted wide-gamut JPEG as sRGB --- crates/pdf/src/export/images.rs | 35 +++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 2908fff57..3e070cb82 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -122,10 +122,8 @@ pub(super) fn jpeg(data: krilla::Data, icc: impl FnOnce() -> Option>, mo color, Some(craft_image_codecs::RasterColorType::Gray | craft_image_codecs::RasterColorType::Bitmap | craft_image_codecs::RasterColorType::Cmyk) ); - if is_rgb - && own.as_deref().is_some_and(needs_srgb_conversion) - && let Some(rgba) = designcraft_images::decode_rgba(data.as_ref()) - { + if is_rgb && own.as_deref().is_some_and(needs_srgb_conversion) { + let rgba = designcraft_images::decode_rgba(data.as_ref())?; return SrgbImage::new(rgba).and_then(|img| Image::from_custom(img, mode.interpolate).ok()); } Image::from_jpeg_with_icc(data, Some(SRGB_ICC.into()), mode.interpolate).ok() @@ -643,4 +641,33 @@ mod recompress_tests { assert!(recompress(&crate::tests::blank_png(9), mode).is_some()); assert_eq!(decodes(), start + 1); } + + /// A wide-gamut RGB JPEG whose embedded profile PDF 1.6 drops cannot be silently tagged as + /// sRGB when `decode_rgba` fails; an sRGB-equivalent JPEG still passes through without decoding. + #[test] + fn wide_gamut_jpeg_conversion_failure_does_not_fall_back_to_srgb_passthrough() { + let img = craft_image_codecs::Image::from_raw( + 4, + 2, + craft_image_codecs::ChannelLayout::Rgb, + craft_image_codecs::SampleType::U8, + [60, 200, 60].repeat(8), + ) + .unwrap(); + let mut bad_scan = craft_image_codecs::encode(&img, craft_image_codecs::Format::Jpeg, &Default::default()).unwrap(); + // Truncate right after the SOS header so header-only parsers succeed while full decode fails. + let sos = bad_scan.windows(2).position(|w| w == [0xFF, 0xDA]).unwrap(); + let sos_len = usize::from(u16::from_be_bytes([bad_scan[sos + 2], bad_scan[sos + 3]])); + bad_scan.truncate(sos + 2 + sos_len); + assert!(designcraft_images::decode_rgba(&bad_scan).is_none()); + + let mode = RasterMode { interpolate: false, tag_rgb: true }; + let p3 = craft_cms::Builtin::DisplayP3.profile().clone().with_encoded_bytes().to_bytes().to_vec(); + assert!(jpeg(bad_scan.clone().into(), || Some(p3), mode).is_none()); + + let mut srgb_v44 = craft_cms::Builtin::Srgb.profile().clone().with_encoded_bytes().to_bytes().to_vec(); + srgb_v44[8] = 4; + srgb_v44[9] = 0x40; + assert!(jpeg(bad_scan.into(), || Some(srgb_v44), mode).is_some()); + } } From 3c88fd88b5b340d64d7cb4ec0ce51498f7716337 Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:05:37 +0000 Subject: [PATCH 3/3] PDF/X-4: require successful RGB-to-sRGB transform before tagging as sRGB --- crates/images/src/colour.rs | 23 +++++++++++---- crates/images/src/lib.rs | 13 +++++++++ crates/pdf/src/export/images.rs | 50 ++++++++++++++++----------------- crates/pdf/src/pdfx/tests.rs | 32 +++++++++++++++++++++ 4 files changed, 88 insertions(+), 30 deletions(-) diff --git a/crates/images/src/colour.rs b/crates/images/src/colour.rs index dcbdeee8a..264a4c1f9 100644 --- a/crates/images/src/colour.rs +++ b/crates/images/src/colour.rs @@ -68,7 +68,7 @@ pub fn to_display_rgba(px: Pixels, embedded_icc: Option<&[u8]>, display: &Displa if let Some(x) = own(ColorSpace::Rgb) && !keeps_rgb(&x) { - in_place(&mut img, &x); + let _ = in_place(&mut img, &x); } Some(img) } @@ -76,7 +76,7 @@ pub fn to_display_rgba(px: Pixels, embedded_icc: Option<&[u8]>, display: &Displa if let Some(x) = own(ColorSpace::Gray) && !keeps_gray(&x) { - in_place(&mut img, &x); + let _ = in_place(&mut img, &x); } Some(img) } @@ -87,6 +87,18 @@ pub fn to_display_rgba(px: Pixels, embedded_icc: Option<&[u8]>, display: &Displa } } +/// Convert straight RGBA8 pixels from `embedded_icc` into sRGB, returning `None` if the profile +/// cannot be parsed as RGB, yields no usable RGB → sRGB transform, or fails during pixel +/// conversion. Unlike [`to_display_rgba`], never falls back to unconverted pixels. +pub fn convert_rgb_to_srgb(mut img: RgbaImage, embedded_icc: &[u8], display: &DisplayColour) -> Option { + let profile = parse(embedded_icc, ColorSpace::Rgb)?; + let x = to_srgb(&profile, display.options)?; + if !keeps_rgb(&x) && !in_place(&mut img, &x) { + return None; + } + Some(img) +} + fn parse(icc: &[u8], pixels: ColorSpace) -> Option { if icc.len() > MAX_ICC_BYTES { log::warn!("embedded ICC profile of {} bytes is too large: ignored", icc.len()); @@ -149,16 +161,17 @@ fn keeps_gray(x: &Transform) -> bool { } /// Convert RGBA pixels whose first channels (RGB, or grey for a grey transform) hold the source -/// values; alpha is kept. -fn in_place(img: &mut RgbaImage, x: &Transform) { +/// values; alpha is kept. Returns `false` if any chunk fails to convert. +fn in_place(img: &mut RgbaImage, x: &Transform) -> bool { let mut src = Vec::with_capacity(CHUNK * 4); for chunk in img.chunks_mut(CHUNK * 4) { src.clear(); src.extend_from_slice(chunk); if !convert(x, &src, 4, chunk, 4) { - return; + return false; } } + true } /// CMYK inks → RGBA through `x`, or the profile-free formula without one. diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index c58061d91..c22283862 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -413,6 +413,19 @@ pub fn decode_rgba(bytes: &[u8]) -> Option { to_display_rgba(px, Some(icc), &DisplayColour::active()) } +/// Straight RGBA8 of an RGB raster decoded under the normal RGBA budget and strictly converted +/// from `icc` to sRGB. Returns `None` if decoding fails, the image exceeds the decode budget, or +/// `icc` yields no usable RGB → sRGB conversion (unlike [`decode_rgba`], never falls back to +/// unconverted RGB). +pub fn decode_rgb_to_srgb(bytes: &[u8], icc: &[u8]) -> Option { + if too_large_to_decode(bytes) { + return None; + } + let decoded = craft_image_codecs::decode_with(bytes, &decode_options()).ok()?; + let rgba = image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8())?; + colour::convert_rgb_to_srgb(rgba, icc, &colour::DisplayColour::active()) +} + /// About how many bytes a pixel [`decode_rgba`] of `bytes` holds at once, with a premultiplied /// copy of its result. A decode holds the samples as decoded beside the 8-bit RGBA (or, for /// CMYK, the 8-bit CMYKA copy and its ink and alpha planes) they are converted to, or two copies diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 3e070cb82..e2af3884e 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -122,33 +122,31 @@ pub(super) fn jpeg(data: krilla::Data, icc: impl FnOnce() -> Option>, mo color, Some(craft_image_codecs::RasterColorType::Gray | craft_image_codecs::RasterColorType::Bitmap | craft_image_codecs::RasterColorType::Cmyk) ); - if is_rgb && own.as_deref().is_some_and(needs_srgb_conversion) { - let rgba = designcraft_images::decode_rgba(data.as_ref())?; + if is_rgb && let Some(p) = own.as_deref().filter(|p| needs_srgb_conversion(p)) { + let rgba = designcraft_images::decode_rgb_to_srgb(data.as_ref(), p)?; return SrgbImage::new(rgba).and_then(|img| Image::from_custom(img, mode.interpolate).ok()); } Image::from_jpeg_with_icc(data, Some(SRGB_ICC.into()), mode.interpolate).ok() } -/// Whether krilla would write this PNG, GIF or WebP as untagged RGB in PDF 1.6: not grey, and -/// either no profile of its own or one krilla drops (wrong colour space or ICC version past 4.1). -/// The header inspection doesn't read WebP, which has no grey form, so a file it can't read counts -/// as colour. -fn untagged_rgb(data: &[u8]) -> bool { - !is_grey(data) && !embedded_icc(data).is_some_and(|p| pdf16_accepts_rgb_icc(&p)) -} - pub(super) fn lossless(data: &Arc>, fmt: Option, mode: RasterMode) -> Option { + if designcraft_images::too_large_to_decode(data) { + return None; + } + let i = mode.interpolate; + let direct_format = matches!(fmt, Some(craft_image_codecs::Format::Png | craft_image_codecs::Format::Gif | craft_image_codecs::Format::WebP)); + let own_icc = if mode.tag_rgb { embedded_icc(data) } else { None }; + let will_tag_srgb = mode.tag_rgb && !is_grey(data) && !(direct_format && own_icc.as_deref().is_some_and(pdf16_accepts_rgb_icc)); // krilla reads PNG, GIF and WebP lazily: a damaged file is accepted here and fails the whole // export when the PDF is written. Decoding it first means it is skipped, like any other // image that can't be decoded. - let rgba = designcraft_images::decode_rgba(data)?; - let i = mode.interpolate; + let rgba = if will_tag_srgb && let Some(icc) = own_icc.as_deref().filter(|p| needs_srgb_conversion(p)) { + designcraft_images::decode_rgb_to_srgb(data, icc)? + } else { + designcraft_images::decode_rgba(data)? + }; let direct = match fmt { - Some(craft_image_codecs::Format::Png | craft_image_codecs::Format::Gif | craft_image_codecs::Format::WebP) - if mode.tag_rgb && untagged_rgb(data) => - { - None - } + Some(craft_image_codecs::Format::Png | craft_image_codecs::Format::Gif | craft_image_codecs::Format::WebP) if will_tag_srgb => None, Some(craft_image_codecs::Format::Png) => Image::from_png(data.clone().into(), i).ok(), Some(craft_image_codecs::Format::Gif) => Image::from_gif(data.clone().into(), i).ok(), Some(craft_image_codecs::Format::WebP) => Image::from_webp(data.clone().into(), i).ok(), @@ -161,6 +159,11 @@ pub(super) fn lossless(data: &Arc>, fmt: Option Option { img.convert(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8), mode.tag_rgb.then(|| icc.filter(|p| is_grey_icc(p) && pdf16_accepts_icc(p)).map(<[u8]>::to_vec)).flatten(), ) - } else if mode.tag_rgb && icc.is_some_and(|p| !pdf16_accepts_rgb_icc(p) && needs_srgb_conversion(p)) { - let converted = image::RgbaImage::from_raw(img.width(), img.height(), rgba).and_then(|rgba_img| { - designcraft_images::colour::to_display_rgba( - designcraft_images::colour::Pixels::Rgb(rgba_img), - icc, - &designcraft_images::colour::DisplayColour::active(), - ) - })?; + } else if mode.tag_rgb + && let Some(icc) = icc.filter(|p| !pdf16_accepts_rgb_icc(p) && needs_srgb_conversion(p)) + { + let rgba_img = image::RgbaImage::from_raw(img.width(), img.height(), rgba)?; + let converted = designcraft_images::colour::convert_rgb_to_srgb(rgba_img, icc, &designcraft_images::colour::DisplayColour::active())?; let pixels = usize::try_from(converted.width()).ok()?.checked_mul(usize::try_from(converted.height()).ok()?)?; let mut rgb = Vec::with_capacity(pixels.checked_mul(3)?); for p in converted.pixels() { diff --git a/crates/pdf/src/pdfx/tests.rs b/crates/pdf/src/pdfx/tests.rs index 2a3fb0e82..14246a479 100644 --- a/crates/pdf/src/pdfx/tests.rs +++ b/crates/pdf/src/pdfx/tests.rs @@ -532,6 +532,38 @@ fn embedded_wide_gamut_icc_past_pdf16_converts_to_srgb_in_pdfx4() { } } +/// An RGB profile that parses as RGB but lacks a usable source transform (no matrix/TRC or AToB +/// tags) keeps display preview's best-effort fallback, but PDF/X-4 export must not tag its +/// unconverted samples as sRGB on JPEG, lossless PNG, or recompressed PNG. +#[test] +fn embedded_unconvertible_rgb_icc_is_not_tagged_as_srgb_in_pdfx4() { + let mut unconvertible_v43 = rgb_icc(); + unconvertible_v43[8] = 4; + unconvertible_v43[9] = 0x30; + let parsed = craft_cms::Profile::parse(&unconvertible_v43).unwrap(); + assert_eq!(parsed.color_space, craft_cms::ColorSpace::Rgb); + assert!(parsed.device_to_pcs(craft_cms::Intent::RelativeColorimetric).is_err()); + + let src_color = [60, 200, 60, 255]; + let jpg = encode_with_icc(craft_image_codecs::Format::Jpeg, false, src_color, unconvertible_v43.clone()); + let png_bytes = encode_with_icc(craft_image_codecs::Format::Png, false, src_color, unconvertible_v43); + // Display preview retains best-effort fallback when conversion is unavailable. + assert_eq!(designcraft_images::decode_rgba(&png_bytes).unwrap().get_pixel(0, 0).0, src_color); + assert!(designcraft_images::decode_rgba(&jpg).is_some()); + + for (name, bytes) in [("no-lut.jpg", jpg), ("no-lut.png", png_bytes)] { + let mut d = Document::new(&NewDocument::default()); + place(&mut d, name, bytes, (4.0, 2.0), (72.0, 72.0)); + for compress_images in [false, true] { + let opts = PdfOptions { standard: Standard::PdfX4, compress_images, ..Default::default() }; + let r = export_pdf_with_report(&d, &Cache::new(), &opts).unwrap(); + assert!(image_spaces(&r.bytes).is_empty(), "{name} compress={compress_images}: unconverted image was emitted"); + assert!(r.warnings.iter().any(|w| w.contains(name)), "{name} compress={compress_images}: expected skip warning, got {:?}", r.warnings); + assert!(check_pdfx4(&r.bytes).is_empty(), "{name} compress={compress_images}: {:?}", check_pdfx4(&r.bytes)); + } + } +} + /// Every image constructor asked for interpolation, which PDF/X-4 and PDF/A forbid: PDF/A /// exports with a placed image failed (#71). Plain exports keep it. #[test]