PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Posterize: 16-bit documents bin the 16-bit sample, as Photoshop does (#5267)
Timothy Daly8504dc615e85
diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rsindex 3c40d7c59..adf07006f 100644--- a/crates/compose/src/adjust.rs+++ b/crates/compose/src/adjust.rs@@ -87,7 +87,7 @@ pub fn apply_depth(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, depth[v; 3]})}- Adjustment::Posterize { levels } => map_rgb(buf, |c| c.map(|v| posterize(v, *levels))),+ Adjustment::Posterize { levels } => map_rgb(buf, |c| c.map(|v| posterize_in(v, *levels, depth))),Adjustment::BrightnessContrast { brightness, contrast, legacy: true } => {// Legacy: contrast scales around 128/255, with brightness added before it when// contrast is raised and after it when contrast is lowered. Measured on Photoshop@@ -313,7 +313,7 @@ pub fn stored_channels(adj: &Adjustment, mode: ColorMode, depth: Option<SampleTy*v = if i > 0 { mirror } else { 1.0 } - v.clamp(0.0, 1.0);}}- Adjustment::Posterize { levels } => ch.iter_mut().for_each(|v| *v = posterize(*v, *levels)),+ Adjustment::Posterize { levels } => ch.iter_mut().for_each(|v| *v = posterize_in(*v, *levels, depth)),Adjustment::Threshold { level } => {// On the 8-bit grid, like the RGB threshold.let t = (level * 255.0).round();@@ -866,6 +866,23 @@ pub fn posterize(v: f32, levels: u32) -> f32 {(bin * 255.0 / (n - 1.0)).floor() / 255.0}+/// [`posterize`] in a document of `depth` (`None`: unknown, treated as 8-bit). At 16 bits+/// Photoshop bins the 16-bit sample (`⌊v · n / 32768⌋`) and lands on 8-bit levels through a+/// 16-bit step: `⌊b · 32768 / (n - 1)⌋`, converted with `⌊(o · 255 + 16384) / 32768⌋`, so+/// 127.5 comes out as 128 but 42.5 as 42 (8 bits floor them all). Exact on every sample of+/// psd-tools posterize_16bits_rgb.psd and posterize_16bits_grayscale.psd (levels 2 to 21),+/// which the 8-bit rule missed by up to half the range.+pub fn posterize_in(v: f32, levels: u32, depth: Option<SampleType>) -> f32 {+ if depth != Some(SampleType::U16) {+ return posterize(v, levels);+ }+ let n = f64::from(levels.clamp(2, 255));+ let x = (f64::from(v.clamp(0.0, 1.0)) * 32768.0).round();+ let bin = (x * n / 32768.0).floor().min(n - 1.0);+ let step = (bin * 32768.0 / (n - 1.0)).floor();+ (((step * 255.0 + 16384.0) / 32768.0).floor() / 255.0) as f32+}+pub fn levels(ch: &LevelsChannel, v: f32) -> f32 {levels_q(ch, v, None)}@@ -1207,6 +1224,21 @@ mod tone_tests {}}+ /// 16-bit sample → Photoshop's 8-bit level, from psd-tools posterize_16bits_rgb.psd: bins+ /// split on the 16-bit sample (10794 and 10923 straddle a third of 32768), and the middle of 3+ /// levels is 128 where 8 bits give 127, while 21 levels keep 25 for 25.5.+ #[test]+ fn sixteen_bit_posterize_matches_photoshop() {+ let points: [(u32, u16, u8); 9] =+ [(3, 10794, 0), (3, 10923, 128), (3, 21845, 128), (3, 21974, 255), (13, 2504, 0), (13, 2542, 21), (13, 7453, 42), (13, 7582, 64), (21, 3341, 25)];+ for (levels, x, want) in points {+ let got = posterize_in(f32::from(x) / 32768.0, levels, Some(SampleType::U16));+ assert!((got * 255.0 - f32::from(want)).abs() < 1e-3, "{levels} levels at {x}: {} vs Photoshop {want}", got * 255.0);+ }+ // 8 bits keep their rule.+ assert_eq!(posterize_in(128.0 / 255.0, 3, Some(SampleType::U8)), posterize(128.0 / 255.0, 3));+ }+#[test]fn color_lookup_with_an_overflowing_stored_size_is_the_identity() {// A stored document's size is untrusted: (2²²)³ × 3 overflows, which once wrapped pastdiff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rsindex 90f90eaec..df6c01850 100644--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@ -2530,9 +2530,9 @@ fn lab_documents_invert_and_posterize_l_a_and_b() {let rgb_inv = photocraft_color::convert::srgb_to_lab(MUTED.map(|v| 1.0 - v));assert!((rgb_inv[0] - inv[0]).abs() > 2.0, "{depth:?}: {rgb_inv:?} vs {inv:?}");// Posterize, three levels: the same steps on L, a and b (here all land on the middle- // step: L ≈ 50 and a, b ≈ -1, a neutral grey).+ // step: L ≈ 50 and a, b ≈ -1 (0 at 16 bits, whose middle level is 128), a neutral grey).let post = lab_doc_adjusted(MUTED, Adjustment::Posterize { levels: 3 }, depth);- let n = [lab[0] / 100.0, (lab[1] + 128.0) / 255.0, (lab[2] + 128.0) / 255.0].map(|v| adjust::posterize(v, 3));+ let n = [lab[0] / 100.0, (lab[1] + 128.0) / 255.0, (lab[2] + 128.0) / 255.0].map(|v| adjust::posterize_in(v, 3, Some(depth)));let want = [n[0] * 100.0, n[1] * 255.0 - 128.0, n[2] * 255.0 - 128.0];assert!(want[0] > 45.0 && want[1].abs() < 2.0 && want[2].abs() < 2.0, "{want:?}");near3(post, want, 1.0, &format!("{depth:?} posterize"));diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgslindex 03a869003..cbec75da7 100644--- a/crates/gpu/src/compose.wgsl+++ b/crates/gpu/src/compose.wgsl@@ -473,6 +473,17 @@ fn posterize(v: f32, n: f32) -> f32 {return floor(bin * 255.0 / (n - 1.0)) / 255.0;}+// compose::adjust::posterize_in at 16 bits: bins of the 16-bit sample, landing on 8-bit levels+// through a 16-bit step. Every product and sum here is a whole number below 2^24, exact in f32;+// 16-bit layers reach the GPU as half floats, though, so a sample within their precision of a+// bin's edge can land in the neighbouring bin (the CPU, which exports, is exact).+fn posterize16(v: f32, n: f32) -> f32 {+ let x = floor(clamp(v, 0.0, 1.0) * 32768.0 + 0.5);+ let bin = min(floor(x * n / 32768.0), n - 1.0);+ let step = floor(bin * 32768.0 / (n - 1.0));+ return floor((step * 255.0 + 16384.0) / 32768.0) / 255.0;+}+// Document pixel being adjusted (for ordered dither).var<private> adj_px: vec2<i32>;@@ -615,7 +626,10 @@ fn adjust(c: vec3<f32>) -> vec3<f32> {case 2: { // Threshold (p0.x = 8-bit level)return vec3(select(0.0, 1.0, round_half_up(gray(c) * 255.0) >= p0.x));}- case 3: { return vec3(posterize(c.r, p0.x), posterize(c.g, p0.x), posterize(c.b, p0.x)); }+ case 3: { // Posterize (p0.x levels; p0.y = 1: 16-bit)+ if p0.y > 0.5 { return vec3(posterize16(c.r, p0.x), posterize16(c.g, p0.x), posterize16(c.b, p0.x)); }+ return vec3(posterize(c.r, p0.x), posterize(c.g, p0.x), posterize(c.b, p0.x));+ }case 4: { return clamp((c + p0.x - p0.z) * p0.y + p0.z + p0.w, vec3(0.0), vec3(1.0)); } // B/C legacy: brightness before (p0.x) or after (p0.w) contrast around compose::adjust::LEGACY_PIVOT (p0.z)case 5: { // B/C modernlet b = p0.x; let ct = p0.y;diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rsindex 48abbc093..d94d2c1de 100644--- a/crates/gpu/src/plan.rs+++ b/crates/gpu/src/plan.rs@@ -1597,7 +1597,9 @@ pub fn adjustment_program(adj: &Adjustment, transfer: Transfer, depth: photocraf(2, p, None)}Adjustment::Posterize { levels } => {+ // The levels, and the 16-bit rule (compose::adjust::posterize_in).p[0][0] = (*levels).clamp(2, 255) as f32;+ p[0][1] = if depth == photocraft_color::SampleType::U16 { 1.0 } else { 0.0 };(3, p, None)}Adjustment::BrightnessContrast { brightness, contrast, legacy: true } => {diff --git a/crates/io/tests/corpus.rs b/crates/io/tests/corpus.rsindex 0689c03ea..1b4cadb4f 100644--- a/crates/io/tests/corpus.rs+++ b/crates/io/tests/corpus.rs@@ -152,7 +152,7 @@ const MIXED: Source = Source { label: "io corpus", dir: "corpus/psd", group_dept/// The full psd-tools test set (309 files at the pinned commit; see `xtask/psd-tools-corpus.sha256`):/// 226 vs the merged image + 10 vs the thumbnail (Advanced Blending knockouts: +7).-const PSD_TOOLS: Source = Source { label: "psd-tools corpus", dir: "corpus/psd-tools", group_depth: 0, pass_floor: 236, roundtrip_floor: 308 };+const PSD_TOOLS: Source = Source { label: "psd-tools corpus", dir: "corpus/psd-tools", group_depth: 0, pass_floor: 241, roundtrip_floor: 308 };/// Our Photoshop-authored oracles (256 files; https://github.com/storytold/photocraft-corpus),/// grouped by feature (`smart-filters`, `effects`, `text`, `adjustments/<mode><bits>`).diff --git a/docs/file-format-parity.md b/docs/file-format-parity.mdindex 5229842b6..6793091b8 100644--- a/docs/file-format-parity.md+++ b/docs/file-format-parity.md@@ -1,6 +1,6 @@# File-format parity-> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-13 · **Change:** minor (Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026+> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-13 · **Change:** minor (16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity andtests. Photoshop's list comes from its `Info.plist` `CFBundleDocumentTypes`, the PiPL read/write@@ -142,6 +142,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings.| Date | Change | Summary ||---|---|---|+| 2026-10-13 | minor | 16-bit Posterize bins the 16-bit sample and lands on 8-bit levels through a 16-bit step, as Photoshop does (RGB, Grayscale and the CMYK/Lab channel path): psd-tools posterize_16bits_rgb and posterize_16bits_grayscale pass; psd-tools floor → 241 of 309 (main 239) || 2026-10-13 | minor | Gradient Map adjustment layers are driven by the W3C luminosity (0.3, 0.59, 0.11), not the Rec. 601 grey: rgb8 and rgb16 gradient-map.psd pass; Photoshop-oracle floor 145 → 147 of 258 || 2026-10-13 | minor | PSD: a "Saving Merged Transparency" global block (`Mtrn`, `Mt16`, `Mt32`; Photoshop's 32-bit documents keep a positive layer count) marks the merged image's first extra channel as its transparency: opening such a file no longer adds a "Transparency" alpha channel, and the oracle compares psd-tools transparentbg.psd's alpha (83.7 % → 0.9 % of pixels off; its shape edges remain) || 2026-10-13 | minor | Palette PNGs open in Indexed Color mode (#4804) |diff --git a/docs/gaps.md b/docs/gaps.mdindex b932848af..70925deb8 100644--- a/docs/gaps.md+++ b/docs/gaps.md@@ -1,6 +1,6 @@# Where PhotoCraft falls short of Photoshop-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impacton the way to beta. This is the work list agents pick from: take the highest-ranked entry that@@ -262,6 +262,7 @@ what an agent can't finish alone.| Date | Change | Summary ||---|---|---|+| 2026-10-13 | minor | G1: 16-bit Posterize bins the 16-bit sample, as Photoshop does (exact on two oracles); psd-tools floor → 241 of 309 || 2026-10-13 | minor | G1: Gradient Map driven by the W3C luminosity (0.3, 0.59, 0.11), as Photoshop is; rgb8/rgb16 gradient-map pass; Photoshop-oracle floor 145 → 147 of 258 || 2026-10-13 | minor | G6: stale "missing tool" list corrected against `main` — Color Replacement (`paint.colorReplacement`), Red Eye (`paint.redEye`) and Add/Delete Anchor Point (P flyout, #4144) are live tools, so the toolbox is 67 of 68 and Art History Brush is the only one missing; no percentage or estimate changed || 2026-10-13 | minor | G4: Hue Jitter amount-track appearance (#3825, partial); no readiness percentage or estimate changed |diff --git a/docs/scorecard.md b/docs/scorecard.mdindex b97b68ac9..409a8760e 100644--- a/docs/scorecard.md+++ b/docs/scorecard.md@@ -7,7 +7,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js| Area | Done | Partial | Missing | Key numbers ||---|---:|---:|---:|---|| [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) |-| [File compatibility](#file-compatibility) | 7 | 13 | 7 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 147/256, round trip ≥ 258/256 |+| [File compatibility](#file-compatibility) | 7 | 13 | 7 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 241/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 147/256, round trip ≥ 258/256 || [Tools](#tools) | 29 | 13 | 1 | || [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 159 (target 0) || [Type](#type) | 4 | 3 | 2 | |@@ -93,7 +93,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t| Corpus | Directory | Files | Oracle pass floor | Round-trip floor ||---|---|---:|---:|---:|| io corpus | `corpus/psd` | 170 | 146 | 169 |-| psd-tools corpus | `corpus/psd-tools` | 309 | 236 | 308 |+| psd-tools corpus | `corpus/psd-tools` | 309 | 241 | 308 || photoshop oracles | `corpus/photoshop` | 256 | 147 | 258 || Id | Target | Status | Issue | Note |