From 721d7bf4d846e88218f03074a90b92ecbc7b8b9f Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:21:12 +0100 Subject: [PATCH] refactor(eps): read CCITTFaxDecode through craft-stream-codecs EPS fax images decode with craft_stream_codecs::decode_ccitt_raw instead of hayro-ccitt directly. With EndOfBlock the rows end at the end-of-block code whatever Rows says (rows 0), as before. Needs craft-libs#1772 (rows on bytes exactly as EncodedByteAlign says). --- Cargo.lock | 30 ++++--- crates/eps/Cargo.toml | 2 +- crates/eps/src/import/data.rs | 1 - crates/eps/src/import/data/filters.rs | 111 +++++++------------------- crates/eps/src/import/tests_images.rs | 1 + 5 files changed, 47 insertions(+), 98 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6d44918061..0656ddf111 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -232,7 +232,7 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.52.0", + "windows-sys 0.59.0", "wl-clipboard-rs", "x11rb", ] @@ -1206,11 +1206,10 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d6cd7836d364177661b0ae17f48a0805e83a5f32#d6cd7836d364177661b0ae17f48a0805e83a5f32" dependencies = [ "fax", "hayro-ccitt", - "hayro-jbig2", + "hayro-jbig2 0.3.0", "thiserror 2.0.21", ] @@ -1813,7 +1812,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -2463,6 +2462,13 @@ dependencies = [ "yoke", ] +[[package]] +name = "hayro-jbig2" +version = "0.3.0" +dependencies = [ + "hayro-ccitt", +] + [[package]] name = "hayro-jbig2" version = "0.3.0" @@ -2493,7 +2499,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=d6cd7836d364177661b0ae dependencies = [ "flate2", "hayro-ccitt", - "hayro-jbig2", + "hayro-jbig2 0.3.0 (git+https://github.com/storytold/craft-libs?rev=d6cd7836d364177661b0ae17f48a0805e83a5f32)", "hayro-jpeg2000", "memchr", "rustc-hash 2.1.3", @@ -4103,7 +4109,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -4625,7 +4631,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -5000,7 +5006,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -5059,7 +5065,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -5924,7 +5930,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix 1.1.6", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -6777,10 +6783,10 @@ dependencies = [ "craft-eps", "craft-image-codecs", "craft-pdf", + "craft-stream-codecs", "encoding_rs", "fax", "flate2", - "hayro-ccitt", "image", "kurbo 0.13.1", "memchr", @@ -7791,7 +7797,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] diff --git a/crates/eps/Cargo.toml b/crates/eps/Cargo.toml index 8d20f83f47..9efae37385 100644 --- a/crates/eps/Cargo.toml +++ b/crates/eps/Cargo.toml @@ -34,7 +34,7 @@ craft-image-codecs = { workspace = true } flate2 = { workspace = true } ruzstd = { workspace = true } # Images read through `CCITTFaxDecode`. -hayro-ccitt = { workspace = true } +craft-stream-codecs = { workspace = true } # Live effects' params, as the art styles that name them give them. serde_json = { workspace = true } # Substring search for PostScript `search`. diff --git a/crates/eps/src/import/data.rs b/crates/eps/src/import/data.rs index 53848af89d..ade850a21e 100644 --- a/crates/eps/src/import/data.rs +++ b/crates/eps/src/import/data.rs @@ -5,7 +5,6 @@ use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; -use hayro_ccitt::{DecodeSettings, Decoder, DecoderContext, EncodingMode}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::cmyk::{Inks, jpeg_components}; use vectorcraft_doc::{ImageBlob, ImageObject, Node, NodeId, NodeKind, OpacityMask}; diff --git a/crates/eps/src/import/data/filters.rs b/crates/eps/src/import/data/filters.rs index 79dce67ea0..a3ad50039e 100644 --- a/crates/eps/src/import/data/filters.rs +++ b/crates/eps/src/import/data/filters.rs @@ -1,8 +1,6 @@ use super::ops::MAX_DATA; -use super::{ - DecodeSettings, Decoder, DecoderContext, DictRef, EncodingMode, ImageBlob, Key, Obj, PsError, Rc, RefCell, Res, find, hex_decode, - jpeg_components, ps, ps_err, -}; +use super::{DictRef, ImageBlob, Key, Obj, PsError, Rc, RefCell, Res, find, hex_decode, jpeg_components, ps, ps_err}; +use craft_stream_codecs::CcittParams; /// A file object: the program itself, or data a filter decoded. #[derive(Debug)] @@ -163,36 +161,29 @@ fn dct(raw: &[u8]) -> Res<(Vec, usize, u8)> { /// `Rows`; without it they end after `Rows` rows, or at the end of the data when `Rows` is 0. /// Damaged data ends the rows: those decoded before it are kept, and damage in the first row is an /// `ioerror`. Rows that would take more than `MAX_DATA` bytes are refused. -fn fax(raw: &[u8], settings: DecodeSettings) -> Res<(Vec, usize)> { +fn fax(raw: &[u8], settings: CcittParams) -> Res<(Vec, usize)> { let row = (settings.columns as usize).div_ceil(8).max(1); let most = u32::try_from(MAX_DATA / row).unwrap_or(u32::MAX); - if !settings.end_of_block && settings.rows > most { + if !settings.end_of_block && settings.rows > i64::from(most) { return Err(PsError::Limit("decoded data is too large")); } // Without a row count that ends the data, a row past `most` shows that the data is too large. - let rows = if settings.end_of_block || settings.rows == 0 { most.saturating_add(1) } else { settings.rows }; + let rows = if settings.end_of_block || settings.rows == 0 { most.saturating_add(1) } else { settings.rows as u32 }; + // With `EndOfBlock` the rows end at the end-of-block code, whatever `Rows` says. + let params = if settings.end_of_block { CcittParams { rows: 0, ..settings } } else { settings }; // The decoder reads the RTC of Group 3 two-dimensional data as rows: it gets the data before it. - let rtc = match settings.encoding { - EncodingMode::Group3_2D { .. } if settings.end_of_block => rtc(raw), - _ => None, - }; + let rtc = if settings.k > 0 && settings.end_of_block { rtc(raw) } else { None }; let data = rtc.and_then(|(cut, _)| raw.get(..cut)).unwrap_or(raw); - let mut out = FaxRows::default(); - let read = hayro_ccitt::decode(data, &mut out, &mut DecoderContext::new(DecodeSettings { rows, ..settings })); - if out.rows > most { + let out = craft_stream_codecs::decode_ccitt_raw(data, ¶ms, rows).map_err(|_| PsError::Limit("decoded data is too large"))?; + if out.rows_decoded > most { return Err(PsError::Limit("decoded data is too large")); } - let used = match read { - Ok(used) => used, - Err(_) if out.rows > 0 => { - out.data.truncate(out.rows as usize * row); - // The whole rows decoded again, for how many bytes they took. - let used = hayro_ccitt::decode(data, &mut Dropped, &mut DecoderContext::new(DecodeSettings { rows: out.rows, ..settings })); - used.unwrap_or(data.len()) - } - Err(_) => return io("CCITTFaxDecode"), - }; - Ok((out.data, rtc.map_or(used, |(_, end)| end))) + // Damaged data ends the rows: those decoded before it are kept, and damage in the first row + // is an `ioerror`. + if out.error.is_some() && out.rows_decoded == 0 { + return io("CCITTFaxDecode"); + } + Ok((out.data, rtc.map_or(out.bytes_consumed, |(_, end)| end))) } /// The RTC that ends Group 3 two-dimensional data (six EOLs, each followed by a 1 tag bit, ITU-T @@ -225,50 +216,6 @@ fn rtc(raw: &[u8]) -> Option<(usize, usize)> { None } -/// Rows of 1-bit samples from a CCITT decoder, each padded to a whole byte: 1 is white, or black -/// with `BlackIs1`. -#[derive(Default)] -struct FaxRows { - data: Vec, - /// Samples in the row being decoded. - x: u32, - /// Whole rows decoded. - rows: u32, -} - -impl Decoder for FaxRows { - fn push_pixel(&mut self, white: bool) { - if self.x.is_multiple_of(8) { - self.data.push(0); - } - if white && let Some(b) = self.data.last_mut() { - *b |= 0x80 >> (self.x % 8); - } - self.x = self.x.saturating_add(1); - } - - fn push_pixel_chunk(&mut self, white: bool, chunk_count: u32) { - self.data.extend(std::iter::repeat_n(if white { 0xff } else { 0 }, chunk_count as usize)); - self.x = self.x.saturating_add(chunk_count.saturating_mul(8)); - } - - fn next_line(&mut self) { - self.x = 0; - self.rows = self.rows.saturating_add(1); - } -} - -/// A CCITT decoder that drops what it decodes. -struct Dropped; - -impl Decoder for Dropped { - fn push_pixel(&mut self, _: bool) {} - - fn push_pixel_chunk(&mut self, _: bool, _: u32) {} - - fn next_line(&mut self) {} -} - /// A decoding filter and its parameters. #[derive(Clone, Debug)] pub(crate) struct Filter { @@ -278,7 +225,7 @@ pub(crate) struct Filter { /// `FlateDecode`'s and `LZWDecode`'s `Predictor`: what it undoes. pub(super) predictor: Option, /// `CCITTFaxDecode`'s parameters. - pub(super) fax: Option, + pub(super) fax: Option, } /// A `Predictor` (2: TIFF, 10–15: PNG) with its `Colors`, `BitsPerComponent` and `Columns`. @@ -407,7 +354,7 @@ fn paeth(a: u8, b: u8, c: u8) -> u8 { /// §7.4.6): `K` (below 0 Group 4, 0 Group 3 one-dimensional, above 0 Group 3 mixed), `Columns`, /// `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`, with their defaults where /// `d` leaves them out. `Columns` outside 1 to 65,535 and `Rows` below 0 are a `rangecheck`. -pub(super) fn fax_settings(d: Option<&DictRef>) -> Res { +pub(super) fn fax_settings(d: Option<&DictRef>) -> Res { let get = |k: &str| d.and_then(|d| d.borrow().get(&Key::name(k)).cloned()); let num = |k: &str, default: f64| get(k).and_then(|o| o.as_num()).unwrap_or(default); let flag = |k: &str, default: bool| match get(k) { @@ -418,21 +365,17 @@ pub(super) fn fax_settings(d: Option<&DictRef>) -> Res { if !k.is_finite() || !(1.0..=65_535.0).contains(&columns) || !(0.0..=f64::from(u32::MAX)).contains(&rows) { return ps_err("rangecheck", "CCITTFaxDecode"); } - let encoding = if k < 0.0 { - EncodingMode::Group4 - } else if k == 0.0 { - EncodingMode::Group3_1D - } else { - EncodingMode::Group3_2D { k: k.min(f64::from(u32::MAX)) as u32 } - }; - Ok(DecodeSettings { - columns: columns as u32, - rows: rows as u32, + // Group 4 below 0, one-dimensional Group 3 at 0, mixed Group 3 above (the row's tag bit says + // how it is coded, so any positive `K` reads the same); `as` saturates. + let k = if k < 0.0 { -1 } else if k == 0.0 { 0 } else { (k as i64).max(1) }; + Ok(CcittParams { + k, + columns: columns as i64, + rows: rows as i64, end_of_block: flag("EndOfBlock", true), end_of_line: flag("EndOfLine", false), - rows_are_byte_aligned: flag("EncodedByteAlign", false), - encoding, - invert_black: flag("BlackIs1", false), + encoded_byte_align: flag("EncodedByteAlign", false), + black_is_1: flag("BlackIs1", false), }) } diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 91ed520d73..6c21c1b7b2 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -359,6 +359,7 @@ fn ccitt_fax_data_in_the_program_ends_at_its_end_of_block() { for (k, eol, aligned, params) in [ (-1, false, false, "/K -1 /Columns 70"), (0, true, false, "/Columns 70 /EndOfLine true"), + (0, true, true, "/Columns 70 /EndOfLine true /EncodedByteAlign true"), (2, true, false, "/K 2 /Columns 70 /Rows 7 /EndOfLine true"), (3, true, true, "/K 3 /Columns 70 /EndOfLine true /EncodedByteAlign true"), ] {