diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_image.rs b/crates/texrra-tex-core/src/execution/engine/pdf_image.rs index 2c3fab2..c82e59b 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_image.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_image.rs @@ -74,9 +74,12 @@ impl Executor { } else { PageSelection::Number(1) }; - if self.keyword("colorspace", files)? { - return self.fail("native PDF image colorspace requires PDF object support"); - } + let color_space = if self.keyword("colorspace", files)? { + let number = self.integer(files)?; + (number != 0).then_some(number) + } else { + None + }; let mut page_box = 0; for (keyword, kind) in [ ("mediabox", PageBox::Media), @@ -125,9 +128,9 @@ impl Executor { |header| (header.major, i32::from(header.minor)), ); let decoded = if png { - PdfImage::read_png(source, resolution) + PdfImage::read_png(source, resolution, color_space) } else { - PdfImage::read_jpeg(source, resolution, version) + PdfImage::read_jpeg(source, resolution, version, color_space) }; let (image, warning) = decoded.map_err(|error| self.error(error, token.span))?; if let Some(warning) = warning { diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index b573d2a..47135ac 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -2397,7 +2397,9 @@ fn write_pdf( } else { resources }; - let remapped = resources.map(|resources| resources.append(&mut objects, diagnostics)); + let remapped = resources + .map(|resources| resources.append(&mut objects, diagnostics)) + .transpose()?; if let Some(resources) = &remapped { for (font, entries) in &resources.fonts { if !entries.is_empty() { @@ -2417,8 +2419,26 @@ fn write_pdf( .first() .and_then(|page| page.pdf.as_ref()) .map_or((1, 4), |pdf| (pdf.file.major, i32::from(pdf.file.minor))); + let mut unwritten_color_spaces = BTreeMap::new(); let form_ids: BTreeMap<_, _> = images.into_iter().map(|(id, image, attributes, compression)| { - (id, image.append_to(&mut objects, attributes, compression, pdf_version, &type1_references)) + let color_space = image.color_space.map(|number| { + let Ok(reference) = u32::try_from(number) else { + return i64::from(number); + }; + if let Some(mapped) = remapped.as_ref().and_then(|r| r.object_numbers.get(&reference)) { + return i64::from(*mapped); + } + // A colorspace number is a reference only. Keep an unwritten target + // free rather than materializing it or colliding with a device object. + *unwritten_color_spaces.entry(reference).or_insert_with(|| { + objects.push(Vec::new()); + objects.len() as i64 + }) + }); + let object = image.append_to( + &mut objects, attributes, compression, pdf_version, &type1_references, color_space, + ); + (id, object) }).collect(); let mut png_group = None; for (page_index, list) in pages.iter().enumerate() { diff --git a/crates/texrra-tex-core/src/pdf_device/page_resources.rs b/crates/texrra-tex-core/src/pdf_device/page_resources.rs index 8060a84..37c27f9 100644 --- a/crates/texrra-tex-core/src/pdf_device/page_resources.rs +++ b/crates/texrra-tex-core/src/pdf_device/page_resources.rs @@ -428,6 +428,7 @@ pub(crate) struct ResourceOutput { page_references: BTreeMap, link_references: BTreeMap>, structure_references: BTreeSet, + image_color_space_objects: BTreeSet, page_entries: Vec, font_opacities: Vec>, page_attributes: Vec, @@ -447,6 +448,7 @@ pub(crate) struct RemappedResources { pub page_objects: BTreeMap, pub link_objects: BTreeMap<(usize, usize), usize>, pub structure_objects: BTreeMap, + pub object_numbers: BTreeMap, pub annotations: Vec>>>, pub catalog: Option>, pub info: Option>, @@ -463,6 +465,7 @@ impl ResourceOutput { ) -> Result { let empty = PdfObjects::default(); let objects = objects.unwrap_or(&empty); + let mut image_color_spaces = BTreeSet::new(); let (page_entries, font_opacities): (Vec<_>, Vec<_>) = pages .iter() .map(|page| { @@ -472,16 +475,24 @@ impl ResourceOutput { "additional PDF resources overlap generated Font or XObject entries".into(), ); } - let alphas = page - .items - .iter() - .filter_map(|item| match item { - crate::render::DisplayItem::OpenTypeColor(Some([_, _, _, alpha])) => { - Some(*alpha) + use crate::render::DisplayItem; + let mut alphas = BTreeSet::new(); + for item in &page.items { + let image = match item { + DisplayItem::OpenTypeColor(Some([_, _, _, alpha])) => { + alphas.insert(*alpha); + continue; } - _ => None, - }) - .collect(); + DisplayItem::PdfImage { image, .. } => image, + DisplayItem::PdfImageObject(object) => &object.image, + _ => continue, + }; + if let Some(number) = image.image.color_space + && let Ok(number) = u32::try_from(number) + { + image_color_spaces.insert(number); + } + } let names = add_font_opacities(&mut entries, alphas, objects)?; Ok((entries, names)) }) @@ -572,11 +583,22 @@ impl ResourceOutput { references(&value, &mut pending)?; values.insert(number, value); } + // An image reference does not schedule an object for writing. Keep + // full numeric precision in the written color space and its graph. + let mut image_color_space_objects = BTreeSet::new(); + while let Some(number) = image_color_spaces.pop_first() { + if let Some(value) = values.get(&number) + && image_color_space_objects.insert(number) + { + references(value, &mut image_color_spaces)?; + } + } Ok(Self { values, page_references: objects.page_references.clone(), link_references, structure_references, + image_color_space_objects, page_entries, font_opacities, page_attributes, @@ -592,7 +614,7 @@ impl ResourceOutput { self, output: &mut Vec>, diagnostics: &mut Vec, - ) -> RemappedResources { + ) -> Result { let mut ids = BTreeMap::new(); let mut page_objects = BTreeMap::new(); for (page, number) in self.page_references { @@ -625,9 +647,14 @@ impl ResourceOutput { .enumerate() .map(|(i, number)| (number, (output.len() + i + 1) as u32)), ); - for (_, mut object) in self.values { + for (number, mut object) in self.values { remap(&mut object, &ids); - output.push(encode_value(object).expect("valid PDF object in memory")); + let body = if self.image_color_space_objects.contains(&number) { + super::xdv_object::encode_device_value(object) + } else { + encode_value(object) + }; + output.push(body?); } let structure_objects = self .structure_references @@ -659,7 +686,7 @@ impl ResourceOutput { bytes[2..bytes.len() - 2].to_vec() }; let encode = |dictionary| encode_dictionary(dictionary, false); - RemappedResources { + Ok(RemappedResources { pages: self .page_entries .into_iter() @@ -680,7 +707,8 @@ impl ResourceOutput { .collect(), catalog: self.catalog.map(&encode), info: self.info.map(encode), - } + object_numbers: ids, + }) } } diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_object.rs b/crates/texrra-tex-core/src/pdf_device/xdv_object.rs index f646a61..7e8db00 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_object.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_object.rs @@ -314,7 +314,7 @@ pub(super) fn encode_device_value(object: Object) -> Result, String> { fn append(bytes: &mut Vec, object: Object) -> Result<(), String> { match object { Object::Real(value) if value.is_finite() => write!(bytes, "{value}").unwrap(), - Object::Real(_) => return Err("non-finite number in XDV PDF object".into()), + Object::Real(_) => return Err("non-finite number in PDF object".into()), Object::Array(values) => { bytes.push(b'['); for value in values { @@ -333,6 +333,12 @@ pub(super) fn encode_device_value(object: Object) -> Result, String> { } bytes.extend_from_slice(b">>"); } + Object::Stream(stream) => { + append(bytes, Object::Dictionary(stream.dict))?; + bytes.extend_from_slice(b"\nstream\n"); + bytes.extend_from_slice(&stream.content); + bytes.extend_from_slice(b"\nendstream"); + } _ => bytes.extend(encode_value(object)?), } Ok(()) diff --git a/crates/texrra-tex-core/src/pdf_image.rs b/crates/texrra-tex-core/src/pdf_image.rs index e177e24..5c596b6 100644 --- a/crates/texrra-tex-core/src/pdf_image.rs +++ b/crates/texrra-tex-core/src/pdf_image.rs @@ -47,6 +47,8 @@ pub struct PdfImage { pub natural: [i64; 2], extent: [u64; 2], objects: Vec>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) color_space: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] imported_fonts: Vec, } @@ -336,6 +338,7 @@ enum Part { Bmp(png::SampledImage), XdvCmykDecode, MappedType1(Arc), + ImageColorSpace, } pub(crate) enum RasterProcSet { @@ -362,6 +365,7 @@ impl PdfImage { resource: LoadedResource, fallback_resolution: i32, pdf_version: (i32, i32), + color_space: Option, ) -> Result<(Self, Option<&'static str>), String> { let header = jpeg::read(&resource.data).map_err(|error| { format!( @@ -390,7 +394,10 @@ impl PdfImage { let denominator = 100 * i64::from(density[axis]); (numerator + denominator / 2) / denominator }); - Ok((Self::jpeg_xobject(resource, header, natural, [1.0; 2], false), warning)) + Ok(( + Self::jpeg_xobject(resource, header, natural, [1.0; 2], false, color_space), + warning, + )) } fn jpeg_xobject( @@ -399,6 +406,7 @@ impl PdfImage { natural: [i64; 2], extent: [f64; 2], xdv: bool, + color_space: Option, ) -> Self { let [width, height] = header.size; let color = match header.components { @@ -413,14 +421,17 @@ impl PdfImage { let mut parts = vec![Part::Bytes( format!("/Type /XObject /Subtype /Image /Width {width} /Height {height}").into_bytes(), )]; - if let Some((_, intent)) = profile { + if color_space.is_some() { + parts.push(Part::Bytes(b" /ColorSpace ".to_vec())); + parts.push(Part::ImageColorSpace); + } else if let Some((_, intent)) = profile { parts.push(Part::Bytes(format!(" /Intent /{intent} /ColorSpace [/ICCBased ").into_bytes())); parts.push(Part::Ref(1)); parts.push(Part::Bytes(b"]".to_vec())); } else { parts.push(Part::Bytes(format!(" /ColorSpace {color}").into_bytes())); } - if header.components == 4 { + if header.components == 4 && color_space.is_none() { if xdv && header.adobe { parts.push(Part::XdvCmykDecode); } else if !xdv { @@ -454,6 +465,7 @@ impl PdfImage { natural, extent: extent.map(f64::to_bits), objects, + color_space, imported_fonts: Vec::new(), } } @@ -475,7 +487,7 @@ impl PdfImage { if resource.data.starts_with(jpeg::SIGNATURE) { let header = jpeg::read(&resource.data).map_err(invalid)?; let bp = extent(header.size.map(u32::from), header.xdv_density)?; - return Ok(Self::jpeg_xobject(resource, header, natural(bp), bp, true)); + return Ok(Self::jpeg_xobject(resource, header, natural(bp), bp, true, None)); } let (part, bp) = if Self::is_png(&resource) { let (image, physical) = png::decode(&resource.data).map_err(|error| invalid(&error))?; @@ -500,6 +512,7 @@ impl PdfImage { natural: natural(bp), extent: bp.map(f64::to_bits), objects: vec![vec![part]], + color_space: None, imported_fonts: Vec::new(), }) } @@ -511,8 +524,9 @@ impl PdfImage { pub(crate) fn read_png( resource: LoadedResource, fallback_resolution: i32, + color_space: Option, ) -> Result<(Self, Option<&'static str>), String> { - png::read(resource, fallback_resolution) + png::read(resource, fallback_resolution, color_space) } pub(crate) fn raster_frame(&self) -> Option<([i64; 2], u8)> { @@ -723,6 +737,7 @@ impl PdfImage { natural, extent: [width.to_bits(), height.to_bits()], objects: graph.bodies, + color_space: None, imported_fonts, }, [left, bottom], @@ -740,9 +755,10 @@ impl PdfImage { compression: u8, pdf_version: (i32, i32), fonts: &crate::pdf::type1_fonts::References<'_>, + color_space: Option, ) -> usize { if let Some(samples) = self.sampled_image() { - return samples.append(pdf, attributes, compression, pdf_version); + return samples.append(pdf, attributes, compression, pdf_version, color_space); } let base = pdf.len() + 1; pdf.extend(self.objects.iter().enumerate().map(|(index, parts)| { @@ -758,6 +774,10 @@ impl PdfImage { match part { Part::Bytes(bytes) | Part::Jpeg { bytes, .. } => body.extend_from_slice(bytes), Part::Ref(id) => write!(body, "{} 0 R", base + id).unwrap(), + Part::ImageColorSpace => { + let id = color_space.expect("mapped image color space"); + write!(body, "{id} 0 R").unwrap(); + } Part::MappedType1(font) => { let reference = &fonts[&font.mapped.key()]; body.extend_from_slice(b" /BaseFont "); diff --git a/crates/texrra-tex-core/src/pdf_image/png.rs b/crates/texrra-tex-core/src/pdf_image/png.rs index ccbd7e1..06a2320 100644 --- a/crates/texrra-tex-core/src/pdf_image/png.rs +++ b/crates/texrra-tex-core/src/pdf_image/png.rs @@ -106,6 +106,7 @@ pub(super) fn decode(bytes: &[u8]) -> Result<(SampledImage, Option, ) -> Result<(PdfImage, Option<&'static str>), String> { let (image, physical) = decode(&resource.data).map_err(|error| { format!( @@ -140,6 +141,7 @@ pub(super) fn read( natural, extent: [1.0_f64.to_bits(); 2], objects: vec![vec![Part::Png(image)]], + color_space, imported_fonts: Vec::new(), }, warning, @@ -180,13 +182,15 @@ impl SampledImage { attributes: &[u8], compression: u8, pdf_version: (i32, i32), + color_space: Option, ) -> usize { let id = pdf.len() + 1; let [width, height] = self.size; - let mut color = match &self.color { - ColorSpace::Gray => "/DeviceGray".to_owned(), - ColorSpace::Rgb => "/DeviceRGB".to_owned(), - ColorSpace::Indexed(table) => { + let mut color = match (color_space, &self.color) { + (Some(id), _) => format!("{id} 0 R"), + (None, ColorSpace::Gray) => "/DeviceGray".to_owned(), + (None, ColorSpace::Rgb) => "/DeviceRGB".to_owned(), + (None, ColorSpace::Indexed(table)) => { let mut color = format!("[/Indexed /DeviceRGB {} <", table.len() / 3 - 1); for byte in table { write!(color, "{byte:02X}").expect("writing to a string"); diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 93835b9..b924afb 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -2175,6 +2175,32 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。 全量编译一致。incremental-receipt.json 的 SHA-256 为 bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。 +### pdfTeX 光栅图像的颜色空间对象 + +`\pdfximage colorspace` 扫描带符号的 TeX 整数。PNG 和 JPEG 在实际写出时 +引用同一作业的 PDF 对象,原样 PDF 页面导入忽略这个选项。零值保留自动 +选择,CMYK JPEG 的缺省 Decode 反转也仅在自动选择时写入。没有写出的 +正数目标在输出保留空闲引用,图像引用本身不会提前写出对象。对象编号在 +导出时映射,支持延迟写出及出页后补写。 +[参考 PNG 写出](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/writepng.c#L572-L611) · [参考 JPEG 写出](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/writejpg.c#L371-L405) + +25 个定向用例覆盖实际颜色空间对象、文件对象、未写出目标、透明遮罩、 +灰度与 CMYK JPEG、Indexed 和 ICC。原有通用写出器曾把 CalGray 白点 +0.9505、1.089 舍入到 0.95、1.09。现在沿实际对象引用图保存数值精度, +包括间接字典、ICC 流字典的 1.0123 和原始 ICC 字节。十个结果的 +144 DPI 光栅逐像素一致,含原样 Elsevier CAS 的 5333 × 3000 JPEG。 +三页 XDV 数字选页与前版 PDF 逐字节一致。 + +同一会话替换外部颜色对象、移除后恢复。两轮成功修订各复用 108 步,只 +替换第二页,PDF、SVG、来源映射与 aux 等于独立全量。缺失对象时保留 +已有产物。修改入口前缀和删除资源的修订也保留产物,此修订走会话内的 +暂存重编路径。已保留此前独立全量作业写出 aux 的观察。 + +三页探针在第三页另放一张图片。改变第二页的颜色对象后,第三页本次及 +前版的 SVG 字节相同,现有交付仍重新发送第二、三页。回执保留了该额外 +工作和与独立全量的一致性,用于后续精确页失效。回执 +`target/p3-pdf-image-colorspace/receipt.json` 的 SHA-256 为 `3ea8083760d7a26bdc4d453cd39e0ad339f0a4c0f9069abcf318911bdd4b07cf`。 + ### pdfTeX 页框设置与继承裁边 `\pdfximage` 支持 `\pdfpagebox` 的默认选择、显式页框、 diff --git a/docs/PUBLISHER_TEMPLATE_MATRIX.md b/docs/PUBLISHER_TEMPLATE_MATRIX.md index 1c398fc..1eded59 100644 --- a/docs/PUBLISHER_TEMPLATE_MATRIX.md +++ b/docs/PUBLISHER_TEMPLATE_MATRIX.md @@ -995,6 +995,14 @@ LaTeX 的 aux 与冻结参考逐字节相同,引用已收敛。三页的 635 词保持顺序和词框,144 DPI 灰度图逐像素一致。 [阶段记录](P2_M1_PROGRESS.md#pdftex-导入版本检查与设备初始化时机) +### Elsevier CAS 双栏原样 JPEG 的颜色空间对照 + +从既有原样归档取未修改的 `figs/cas-munnar-2024.jpg`,冻结输入指纹。 +以同样的 PDF 颜色空间对象单独比较该插图。两端保留同一份 5333 × 3000 +JPEG 的压缩字节与解码设置,生成页的 144 DPI 灰度图相同。 +此前整篇双栏复验与同版统一矩阵的记录分别保留。 +[阶段记录](P2_M1_PROGRESS.md#pdftex-光栅图像的颜色空间对象) + ### Elsevier CAS 双栏导入页框复验 原样 30 项交付沿用冻结的 schema51、真实字体映射及参考。三轮