Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified crates/tok-pdf/assets/icc/b2a.bin
Binary file not shown.
Binary file added crates/tok-pdf/assets/icc/gamt.bin
Binary file not shown.
51 changes: 44 additions & 7 deletions crates/tok-pdf/assets/icc/gen_icc_luts.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

A2B_GRID = 9
B2A_GRID = 9
GAMT_GRID = 17

# D50 reference white
XN, YN, ZN = 0.9642, 1.0, 0.8249
Expand Down Expand Up @@ -72,12 +73,20 @@ def cmyk_to_rgb(c, m, y, k):


def rgb_to_cmyk(r, g, b):
"""Maximum-GCR separation: the black channel carries the whole grey component.

Neutrals therefore land on K only, and the three coloured inks together never
exceed 200%, so the total ink stays below 300% without any further limiting.
The model above is multiplicative, so this separation is colorimetrically exact.
"""
r, g, b = (min(max(v, 0.0), 1.0) for v in (r, g, b))
k = 1 - max(r, g, b)
if k >= 1 - 1e-9:
top = max(r, g, b)
# Near-black (including values pushed slightly off-neutral by the 16-bit Lab encoding)
# would otherwise blow tiny colour differences up into full-strength inks.
if top <= 1e-3:
return 0.0, 0.0, 0.0, 1.0
d = 1 - k
return (1 - r - k) / d, (1 - g - k) / d, (1 - b - k) / d, k
k = 1 - top
return (top - r) / top, (top - g) / top, (top - b) / top, k


def u16(v):
Expand Down Expand Up @@ -133,20 +142,48 @@ def build_a2b():
def build_b2a():
clut = []
n = B2A_GRID - 1
# The input tables are the identity over 0..65535, so grid node i sits at the 16-bit
# input value i / n * 65535 on every channel (L, a and b alike).
for li in range(B2A_GRID):
for ai in range(B2A_GRID):
for bi in range(B2A_GRID):
l = dec_l(li / n * 65280)
a = dec_ab(ai / n * 65280)
b = dec_ab(bi / n * 65280)
l = dec_l(li / n * 65535)
a = dec_ab(ai / n * 65535)
b = dec_ab(bi / n * 65535)
r, g, bl = xyz_d50_to_rgb(*lab_to_xyz(l, a, b))
c, m, y, k = rgb_to_cmyk(r, g, bl)
clut += [u16(c * 65535), u16(m * 65535), u16(y * 65535), u16(k * 65535)]
return lut16(3, 4, B2A_GRID, clut)


def build_gamt():
"""Gamut tag (Lab -> 1 channel): 0 inside the model's gamut, rising with the overshoot outside.

The model reaches every sRGB colour and nothing beyond it, so "outside" means a linear
sRGB component below 0 or above 1.
"""
clut = []
n = GAMT_GRID - 1
for li in range(GAMT_GRID):
for ai in range(GAMT_GRID):
for bi in range(GAMT_GRID):
l = dec_l(li / n * 65535)
a = dec_ab(ai / n * 65535)
b = dec_ab(bi / n * 65535)
x, y, z = lab_to_xyz(l, a, b)
rl = 3.1338561 * x - 1.6168667 * y - 0.4906146 * z
gl = -0.9787684 * x + 1.9161415 * y + 0.0334540 * z
bl = 0.0719453 * x - 0.2289914 * y + 1.4052427 * z
over = max(0.0, max(rl, gl, bl) - 1.0, -min(rl, gl, bl))
if over < 1e-4:
over = 0.0
clut.append(u16(min(over * 4.0, 1.0) * 65535))
return lut16(3, 1, GAMT_GRID, clut)


if __name__ == "__main__":
out_dir = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
out_dir.mkdir(parents=True, exist_ok=True)
(out_dir / "a2b.bin").write_bytes(build_a2b())
(out_dir / "b2a.bin").write_bytes(build_b2a())
(out_dir / "gamt.bin").write_bytes(build_gamt())
65 changes: 59 additions & 6 deletions crates/tok-pdf/src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,10 @@ impl IccProfileId {
}
}

/// Official PDF/X `OutputConditionIdentifier` registered at `http://www.color.org`.
/// Identifier of the registered press condition this profile approximates.
///
/// Informational (CLI output, UI): the PDF itself declares a custom output condition,
/// because the embedded profile is a generic approximation and not that characterisation.
pub fn output_condition_identifier(&self) -> &'static str {
match self {
Self::Fogra39 => "FOGRA39",
Expand All @@ -149,7 +152,8 @@ impl IccProfileId {
}
}

/// Registry URL for PDF/X OutputIntent.
/// Registry that lists the condition named by `output_condition_identifier`.
/// Not written to the PDF, which declares a custom (unregistered) output condition.
pub fn registry_name(&self) -> &'static str {
"http://www.color.org"
}
Expand Down Expand Up @@ -273,6 +277,8 @@ impl ColorManagementEngine {
// CMYK -> Lab and Lab -> CMYK `lut16Type` tag data.
const A2B_LUT: &[u8] = include_bytes!("../assets/icc/a2b.bin");
const B2A_LUT: &[u8] = include_bytes!("../assets/icc/b2a.bin");
// Lab -> gamut distance (0 inside the gamut); ICC v2 requires it for LUT-based output.
const GAMT: &[u8] = include_bytes!("../assets/icc/gamt.bin");

let desc_str = format!("TypesetOK approximation of {}", profile.info());
let cprt_str = "Copyright TypesetOK Pre-Press Color Engine (ISO 15076-1)";
Expand Down Expand Up @@ -305,10 +311,10 @@ impl ColorManagementEngine {
wtpt_tag.extend_from_slice(&0x0000_D32Du32.to_be_bytes()); // 0.8249 in s15Fixed16

// Distinct data blocks, stored in this order. Every block starts on a 4-byte boundary.
let blocks: [&[u8]; 5] = [&desc_tag, &cprt_tag, &wtpt_tag, A2B_LUT, B2A_LUT];
let blocks: [&[u8]; 6] = [&desc_tag, &cprt_tag, &wtpt_tag, A2B_LUT, B2A_LUT, GAMT];
// Tag table: signature and the block it points at. The three rendering intents of each
// transform share one block.
let tags: [(&[u8; 4], usize); 9] = [
let tags: [(&[u8; 4], usize); 10] = [
(b"desc", 0),
(b"cprt", 1),
(b"wtpt", 2),
Expand All @@ -318,12 +324,13 @@ impl ColorManagementEngine {
(b"B2A0", 4),
(b"B2A1", 4),
(b"B2A2", 4),
(b"gamt", 5),
];

let header_size = 128u32;
let tag_count = tags.len() as u32;
let tag_table_size = 4 + tag_count * 12;
let mut offsets = [0u32; 5];
let mut offsets = [0u32; 6];
let mut cursor = header_size + tag_table_size;
for (offset, block) in offsets.iter_mut().zip(blocks.iter()) {
*offset = cursor;
Expand Down Expand Up @@ -421,6 +428,51 @@ mod tests {
);
}

/// Regression: the Lab -> CMYK table used to put 100% cyan and 64% magenta under pure black
/// (about 364% total ink) and tinted every dark neutral with coloured inks.
#[test]
fn icc_b2a_table_keeps_neutrals_on_black_and_within_ink_limit() {
let icc = ColorManagementEngine::generate_icc_profile_bytes(IccProfileId::Fogra39);
let be32 = |at: usize| u32::from_be_bytes(icc[at..at + 4].try_into().unwrap());
let tag_count = be32(128) as usize;
let b2a_offset = (0..tag_count)
.map(|i| 132 + i * 12)
.find(|&entry| icc[entry..entry + 4] == *b"B2A0")
.map(|entry| be32(entry + 4) as usize)
.expect("B2A0 tag");
assert_eq!(&icc[b2a_offset..b2a_offset + 4], b"mft2");
assert_eq!(icc[b2a_offset + 8], 3, "B2A0 has 3 input channels (Lab)");
assert_eq!(icc[b2a_offset + 9], 4, "B2A0 has 4 output channels (CMYK)");
let grid = icc[b2a_offset + 10] as usize;
// 52-byte header, then three input tables of two 16-bit entries, then the grid.
let clut = b2a_offset + 52 + 3 * 2 * 2;
let node = |l: usize, a: usize, b: usize| -> [f32; 4] {
let at = clut + ((l * grid + a) * grid + b) * 4 * 2;
let mut ink = [0.0f32; 4];
for (i, value) in ink.iter_mut().enumerate() {
let hi = icc[at + i * 2];
let lo = icc[at + i * 2 + 1];
*value = f32::from(u16::from_be_bytes([hi, lo])) / 65535.0;
}
ink
};
let neutral = grid / 2;
for l in 0..grid {
let [c, m, y, _] = node(l, neutral, neutral);
assert!(
c < 0.01 && m < 0.01 && y < 0.01,
"neutral node {l} must use the black channel only, got c={c} m={m} y={y}"
);
for a in 0..grid {
for b in 0..grid {
let total: f32 = node(l, a, b).iter().sum();
assert!(total <= 3.0 + 1e-3, "node ({l},{a},{b}) has {total} ink");
}
}
}
assert_eq!(node(0, neutral, neutral)[3], 1.0, "L=0 is pure 100% K");
}

#[test]
fn color_management_engine_enforces_tac_and_preserves_pure_black() {
// Pure RGB black -> pure 100% K (0, 0, 0, 1)
Expand Down Expand Up @@ -459,7 +511,7 @@ mod tests {
let be32 = |at: usize| u32::from_be_bytes(icc_bytes[at..at + 4].try_into().unwrap());
assert_eq!(be32(0) as usize, icc_bytes.len(), "profile size field");
let tag_count = be32(128) as usize;
assert_eq!(tag_count, 9);
assert_eq!(tag_count, 10);
let mut signatures = Vec::new();
for i in 0..tag_count {
let entry = 132 + i * 12;
Expand All @@ -478,5 +530,6 @@ mod tests {
}
assert!(signatures.iter().any(|s| s == b"A2B0"));
assert!(signatures.iter().any(|s| s == b"B2A0"));
assert!(signatures.iter().any(|s| s == b"gamt"));
}
}
Loading
Loading