PhotoCraft: An open-source, photo editor written by scratch in pure Rust
PNG: keep a stereo file's sTER pairing on save (#6063) (#6285)
mroxso640873de7ba8
diff --git a/crates/codecs/src/codecs/png.rs b/crates/codecs/src/codecs/png.rsindex 7c1a633d1..ede70d296 100644--- a/crates/codecs/src/codecs/png.rs+++ b/crates/codecs/src/codecs/png.rs@@ -7,7 +7,7 @@ use crate::Format;use crate::error::CodecError;use crate::fidelity::Plan;use crate::image::{ChannelLayout, DecodeWarning, Image, Metadata, SampleType};-use crate::options::{EncodeOptions, Limits, PngCompression, alloc_zeroed};+use crate::options::{EncodeOptions, Limits, PngCompression, PngStereo, alloc_zeroed};const F: Format = Format::Png;pub(crate) const XMP_KEYWORD: &str = "XML:com.adobe.xmp";@@ -127,6 +127,38 @@ pub fn palette(bytes: &[u8]) -> Result<Option<PngPalette>, CodecError> {Ok(Some(PngPalette { colors, transparent }))}+/// The stereo pairing a PNG declares in its `sTER` chunk (PNG Extensions 1.4.0, §3.6), read+/// from the headers without decoding pixels. `None` when the file has no CRC-valid `sTER` with a+/// defined mode byte. The first valid chunk wins, as a later one would contradict it.+pub fn stereo(bytes: &[u8]) -> Option<PngStereo> {+ let mut rest = bytes.get(8..)?;+ while let Some((length, tail)) = rest.split_first_chunk::<4>() {+ let Some((kind, tail)) = tail.split_first_chunk::<4>() else { break };+ let length = u32::from_be_bytes(*length);+ if length > i32::MAX as u32 {+ break;+ }+ let Ok(length) = usize::try_from(length) else { break };+ let Some(data) = tail.get(..length) else { break };+ let Some((checksum, next)) = tail.get(length..).and_then(|t| t.split_first_chunk::<4>()) else { break };+ rest = next;+ if kind == b"IEND" {+ break;+ }+ if kind != b"sTER" || data.len() != 1 {+ continue;+ }+ let mut crc = flate2::Crc::new();+ crc.update(kind);+ crc.update(data);+ if crc.sum() != u32::from_be_bytes(*checksum) {+ continue;+ }+ return PngStereo::from_mode(data[0]);+ }+ None+}+fn map_png_err(e: png::DecodingError) -> CodecError {match e {png::DecodingError::LimitsExceeded => CodecError::LimitExceeded("PNG decoder memory limit".into()),@@ -346,6 +378,10 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Ve}}let mut writer = encoder.write_header().map_err(|e| CodecError::encode(F, e))?;+ if let Some(stereo) = opts.png_stereo {+ // Ancillary chunk before IDAT, as the spec recommends for `sTER`.+ writer.write_chunk(png::chunk::ChunkType(*b"sTER"), &[stereo.mode()]).map_err(|e| CodecError::encode(F, e))?;+ }if opts.png_interlaced {let bpp = img.layout().channels() * img.sample_type().bytes();let idat = adam7_idat(&data, w as usize, h as usize, bpp, opts.png_compression)?;@@ -574,6 +610,7 @@ pub fn encode_indexed(palette: &[[u8; 3]],transparent: Option<u8>,dpi: Option<(f32, f32)>,+ stereo: Option<PngStereo>,) -> Result<Vec<u8>, CodecError> {if width == 0 || height == 0 || indices.len() != width as usize * height as usize {return Err(CodecError::InvalidImage("index data does not match the size".into()));@@ -603,12 +640,95 @@ pub fn encode_indexed({let encoder = png::Encoder::with_info(&mut out, info).map_err(|e| CodecError::encode(F, e))?;let mut writer = encoder.write_header().map_err(|e| CodecError::encode(F, e))?;+ if let Some(stereo) = stereo {+ writer.write_chunk(png::chunk::ChunkType(*b"sTER"), &[stereo.mode()]).map_err(|e| CodecError::encode(F, e))?;+ }writer.write_image_data(indices).map_err(|e| CodecError::encode(F, e))?;writer.finish().map_err(|e| CodecError::encode(F, e))?;}Ok(out)}+#[cfg(test)]+mod stereo_tests {+ use super::*;++ /// One CRC-valid chunk as it appears in a file.+ fn chunk(kind: &[u8; 4], data: &[u8]) -> Vec<u8> {+ let mut out = Vec::new();+ out.extend_from_slice(&(data.len() as u32).to_be_bytes());+ out.extend_from_slice(kind);+ out.extend_from_slice(data);+ let mut crc = flate2::Crc::new();+ crc.update(kind);+ crc.update(data);+ out.extend_from_slice(&crc.sum().to_be_bytes());+ out+ }++ fn png_with(stereo: &[u8]) -> Vec<u8> {+ let mut out = b"\x89PNG\r\n\x1a\n".to_vec();+ out.extend_from_slice(&chunk(b"IHDR", &[0, 0, 0, 2, 0, 0, 0, 1, 8, 2, 0, 0, 0]));+ if !stereo.is_empty() {+ out.extend_from_slice(&chunk(b"sTER", stereo));+ }+ out.extend_from_slice(&chunk(b"IDAT", &[0x78, 0x01, 0x01, 0x00, 0xff, 0xff, 0, 3, 1, 0, 0]));+ out.extend_from_slice(&chunk(b"IEND", &[]));+ out+ }++ #[test]+ fn reads_both_defined_views() {+ assert_eq!(stereo(&png_with(&[0])), Some(PngStereo::Horizontal));+ assert_eq!(stereo(&png_with(&[1])), Some(PngStereo::Vertical));+ assert_eq!(stereo(&png_with(&[])), None);+ // Reserved and unknown mode bytes are not a pairing we can keep.+ assert_eq!(stereo(&png_with(&[2])), None);+ assert_eq!(stereo(&png_with(&[255])), None);+ // A two-byte payload is not sTER data.+ assert_eq!(stereo(&png_with(&[0, 0])), None);+ assert_eq!(stereo(b"not a png"), None);+ }++ #[test]+ fn a_broken_crc_is_not_a_stereo_mark() {+ let mut bytes = png_with(&[0]);+ let kind = bytes.windows(4).position(|w| w == b"sTER").unwrap();+ // The CRC trails the type and the one-byte payload of the chunk.+ bytes[kind + 8] ^= 0xff;+ assert_eq!(stereo(&bytes), None);+ }++ #[test]+ fn encode_writes_the_chunk_before_idat_and_it_reads_back() {+ let img = Image::from_raw(2, 1, ChannelLayout::Rgb, SampleType::U8, vec![9; 6]).unwrap();+ for view in [PngStereo::Horizontal, PngStereo::Vertical] {+ let opts = EncodeOptions { png_stereo: Some(view), ..Default::default() };+ let bytes = crate::encode(&img, Format::Png, &opts).unwrap();+ assert_eq!(stereo(&bytes), Some(view));+ let back = decode(&bytes, &Limits::default()).unwrap();+ assert_eq!(back.data(), img.data());+ let ter = bytes.windows(4).position(|w| w == b"sTER").unwrap();+ let idat = bytes.windows(4).position(|w| w == b"IDAT").unwrap();+ assert!(ter < idat, "sTER before IDAT");+ }+ let plain = crate::encode(&img, Format::Png, &EncodeOptions::default()).unwrap();+ assert_eq!(stereo(&plain), None);+ }++ #[test]+ fn interlaced_and_indexed_encoders_keep_the_mark() {+ let img = Image::from_raw(2, 2, ChannelLayout::Rgb, SampleType::U8, vec![9; 12]).unwrap();+ let opts = EncodeOptions { png_stereo: Some(PngStereo::Vertical), png_interlaced: true, ..Default::default() };+ let bytes = crate::encode(&img, Format::Png, &opts).unwrap();+ assert_eq!(stereo(&bytes), Some(PngStereo::Vertical));+ let pal = [[255, 0, 0], [0, 0, 255]];+ let bytes = encode_indexed(2, 1, &[0, 1], &pal, None, None, Some(PngStereo::Horizontal)).unwrap();+ assert_eq!(stereo(&bytes), Some(PngStereo::Horizontal));+ assert_eq!(palette(&bytes).unwrap().map(|p| p.colors), Some(pal.to_vec()));+ }+}+#[cfg(test)]mod indexed_tests {use super::*;@@ -617,14 +737,14 @@ mod indexed_tests {fn png8_roundtrips_through_the_decoder() {let pal = [[255, 0, 0], [0, 0, 255], [0, 0, 0]];let idx = [0u8, 1, 2, 1, 0, 2];- let bytes = encode_indexed(3, 2, &idx, &pal, Some(2), None).unwrap();+ let bytes = encode_indexed(3, 2, &idx, &pal, Some(2), None, None).unwrap();let img = decode(&bytes, &Limits::default()).unwrap();assert_eq!(img.dimensions(), (3, 2));let px = img.convert(ChannelLayout::Rgba, SampleType::U8);assert_eq!(&px.data()[..8], &[255, 0, 0, 255, 0, 0, 255, 255]);assert_eq!(px.data()[11], 0, "transparent entry");- assert!(encode_indexed(3, 2, &[9; 6], &pal, None, None).is_err());- assert!(encode_indexed(3, 3, &idx, &pal, None, None).is_err());+ assert!(encode_indexed(3, 2, &[9; 6], &pal, None, None, None).is_err());+ assert!(encode_indexed(3, 3, &idx, &pal, None, None, None).is_err());}fn png(color: png::ColorType, trns: Option<&[u8]>) -> Vec<u8> {@@ -643,7 +763,7 @@ mod indexed_tests {#[test]fn palette_reads_the_table_and_its_one_transparent_entry() {- let bytes = encode_indexed(2, 1, &[0, 1], &[[1, 2, 3], [4, 5, 6]], Some(1), None).unwrap();+ let bytes = encode_indexed(2, 1, &[0, 1], &[[1, 2, 3], [4, 5, 6]], Some(1), None, None).unwrap();let colors = vec![[1, 2, 3], [4, 5, 6]];assert_eq!(palette(&bytes).unwrap(), Some(PngPalette { colors: colors.clone(), transparent: Some(1) }));assert_eq!(palette(&png(png::ColorType::Indexed, None)).unwrap(), Some(PngPalette { colors, transparent: None }));diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rsindex 86611599d..67369d026 100644--- a/crates/codecs/src/lib.rs+++ b/crates/codecs/src/lib.rs@@ -28,7 +28,7 @@ pub mod web;pub use crate::codecs::exr_cryptomatte::{cryptomatte_id, cryptomatte_key, cryptomatte_preview_color};pub use crate::codecs::gif_frames::{AnimationFrame, MAX_GIF_FRAMES};-pub use crate::codecs::png::{PngPalette, encode_indexed as encode_png_indexed, palette as png_palette};+pub use crate::codecs::png::{PngPalette, encode_indexed as encode_png_indexed, palette as png_palette, stereo as png_stereo};pub use crate::codecs::tiff::{PhotoshopTags as TiffPhotoshopTags, photoshop_tags as tiff_photoshop_tags, writes_little_endian as tiff_writes_little_endian};pub use crate::codecs::tiff_ifd::{TiffInfo, TiffPage, TiffPageKind};pub use crate::error::CodecError;@@ -38,7 +38,7 @@ pub use crate::format::{ASYMMETRIC_EXCEPTIONS, Format, FormatCaps, caps, detect,pub use crate::image::{ChannelLayout, CryptomatteBuffer, CryptomatteLayer, DecodeWarning, DeepChannel, DeepImage, ExrChannelInfo, ExrPartInfo, Image, Metadata, SampleType,};-pub use crate::options::{DecodeOptions, DpxBits, EncodeOptions, ExrCompression, Limits, PngCompression, TiffCompression};+pub use crate::options::{DecodeOptions, DpxBits, EncodeOptions, ExrCompression, Limits, PngCompression, PngStereo, TiffCompression};pub use crate::orientation::{exif_orientation, upright_exif, upright_xmp};pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_resolution, xmp_resolution};pub use crate::source_settings::{WebpEncoding, jpeg_quality, webp_encoding};diff --git a/crates/codecs/src/options.rs b/crates/codecs/src/options.rsindex eee5b38c0..e6ca3cb94 100644--- a/crates/codecs/src/options.rs+++ b/crates/codecs/src/options.rs@@ -100,6 +100,34 @@ pub enum PngCompression {Best,}+/// How a PNG's `sTER` chunk pairs its two views (PNG Extensions 1.4.0, §3.6).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PngStereo {+ /// Left and right views side by side, left first.+ Horizontal,+ /// Left and right views stacked, left on top.+ Vertical,+}++impl PngStereo {+ /// The view for an `sTER` mode byte; reserved and unknown values are `None`.+ pub fn from_mode(mode: u8) -> Option<Self> {+ match mode {+ 0 => Some(Self::Horizontal),+ 1 => Some(Self::Vertical),+ _ => None,+ }+ }++ /// The `sTER` mode byte.+ pub fn mode(self) -> u8 {+ match self {+ Self::Horizontal => 0,+ Self::Vertical => 1,+ }+ }+}+/// TIFF strip compression. The default is none, as in Photoshop: uncompressed strips are the/// only kind every TIFF reader opens (Deflate and the predictor are not baseline TIFF, #4484).#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]@@ -164,6 +192,9 @@ pub struct EncodeOptions {pub png_compression: PngCompression,/// Write Adam7-interlaced PNG.pub png_interlaced: bool,+ /// Write an `sTER` chunk marking the image as a stereo pair (PNG Extensions 1.4.0, §3.6),+ /// so a stereo PNG keeps its mark when saved again (#6063).+ pub png_stereo: Option<PngStereo>,/// WebP: lossless (VP8L, via `image-webp`) or lossy (our VP8 encoder, see/// `codecs::vp8`) with [`Self::webp_quality`].pub webp_lossless: bool,@@ -189,6 +220,7 @@ impl Default for EncodeOptions {jpeg_chroma_subsampling: true,png_compression: PngCompression::Default,png_interlaced: false,+ png_stereo: None,webp_lossless: true,webp_quality: 80,tiff_compression: TiffCompression::None,diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rsindex a1214e793..268b0b6b4 100644--- a/crates/doc/src/lib.rs+++ b/crates/doc/src/lib.rs@@ -912,8 +912,8 @@ pub struct Document {pub variables: Variables,/// Window › Timeline (None until a video timeline is created).pub timeline: Option<Timeline>,- /// How the document's lossy file was encoded (its JPEG quality, WebP lossy or lossless), so- /// a save writes it back the same way rather than at fixed defaults.+ /// How the document's lossy file was encoded (its JPEG quality, WebP lossy or lossless,+ /// PNG stereo pairing), so a save writes it back the same way rather than at fixed defaults.pub file_encoding: FileEncoding,}@@ -932,6 +932,10 @@ pub struct FileEncoding {/// Lossy WebP quality.#[serde(skip_serializing_if = "Option::is_none")]pub webp_quality: Option<u8>,+ /// PNG stereo pairing (the `sTER` chunk's mode byte, PNG Extensions 1.4.0 §3.6): `Some(0)`+ /// side by side, `Some(1)` stacked, so saving a stereo PNG keeps the mark (#6063).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub png_stereo: Option<u8>,}impl FileEncoding {diff --git a/crates/engine/src/web_cmds.rs b/crates/engine/src/web_cmds.rsindex 29237fd5a..755ba0732 100644--- a/crates/engine/src/web_cmds.rs+++ b/crates/engine/src/web_cmds.rs@@ -586,7 +586,7 @@ pub fn optimize(let bytes = if st.format == WebFormat::Gif {photocraft_codecs::web::encode_gif_indexed(ww, hh, &idx, &pal, tt, st.interlaced).map_err(e)?} else {- photocraft_codecs::encode_png_indexed(ww, hh, &idx, &pal, tt, None).map_err(e)?+ photocraft_codecs::encode_png_indexed(ww, hh, &idx, &pal, tt, None, None).map_err(e)?};if preview {indices = idx;diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rsindex 773e69272..76f53d970 100644--- a/crates/io/src/flat.rs+++ b/crates/io/src/flat.rs@@ -67,8 +67,9 @@ pub fn import_gif_frames(name: &str, bytes: &[u8], each: &mut dyn FnMut(Document}/// The lossy settings `bytes` were encoded with, for File › Save to keep: a JPEG's quality-/// (estimated from its quantisation tables) and a WebP's lossless or lossy encoding with its-/// quality. A lossy WebP whose quality can't be read gets [`DEFAULT_LOSSY_WEBP_QUALITY`].+/// (estimated from its quantisation tables), a WebP's lossless or lossy encoding with its+/// quality, and a PNG's `sTER` stereo pairing. A lossy WebP whose quality can't be read gets+/// [`DEFAULT_LOSSY_WEBP_QUALITY`].pub fn file_encoding(bytes: &[u8]) -> photocraft_doc::FileEncoding {file_encoding_as(codecs::detect(bytes), bytes)}@@ -78,6 +79,7 @@ fn file_encoding_as(format: Option<Format>, bytes: &[u8]) -> photocraft_doc::Fillet mut e = photocraft_doc::FileEncoding::default();match format {Some(Format::Jpeg) => e.jpeg_quality = codecs::jpeg_quality(bytes),+ Some(Format::Png) => e.png_stereo = codecs::png_stereo(bytes).map(codecs::PngStereo::mode),Some(Format::WebP) => match codecs::webp_encoding(bytes) {Some(codecs::WebpEncoding::Lossless) => e.webp_lossless = Some(true),Some(codecs::WebpEncoding::Lossy { quality }) => {@@ -95,8 +97,8 @@ fn file_encoding_as(format: Option<Format>, bytes: &[u8]) -> photocraft_doc::Filpub const DEFAULT_LOSSY_WEBP_QUALITY: u8 = 75;/// Applies the settings `doc`'s file was encoded with (see [`file_encoding`]) to `opts`: what a-/// save that chose no quality writes, so a JPEG keeps its quality and a WebP stays lossy or-/// lossless.+/// save that chose no quality writes, so a JPEG keeps its quality, a WebP stays lossy or lossless,+/// and a stereo PNG keeps its `sTER` pairing (#6063).pub fn apply_file_encoding(doc: &Document, opts: &mut codecs::EncodeOptions) {let e = &doc.file_encoding;if let Some(q) = e.jpeg_quality {@@ -108,6 +110,7 @@ pub fn apply_file_encoding(doc: &Document, opts: &mut codecs::EncodeOptions) {if let Some(q) = e.webp_quality {opts.webp_quality = q.min(100);}+ opts.png_stereo = e.png_stereo.and_then(codecs::PngStereo::from_mode);}/// Photoshop opens a 32-bit Targa as an opaque Background plus an "Alpha 1" channel holding the@@ -835,7 +838,7 @@ fn export_mode_specific(doc: &Document, format: Format, opts: &ExportOptions) ->})?;// Same rule as the ordinary PNG encoder: the resolution goes into `pHYs` with the metadata.let dpi = opts.encode.embed_metadata.then_some((doc.resolution_dpi, doc.resolution_dpi));- let bytes = codecs::encode_png_indexed(doc.size.width, doc.size.height, &idx, &table.colors, table.transparent, dpi)?;+ let bytes = codecs::encode_png_indexed(doc.size.width, doc.size.height, &idx, &table.colors, table.transparent, dpi, opts.encode.png_stereo)?;let mut warnings = vec![format!("written as an 8-bit palette PNG ({} colours)", table.colors.len())];if opts.encode.embed_metadata && opts.xmp == XmpEmbed::All && !doc.metadata.text.is_empty() {warnings.push("text metadata is not supported by the palette PNG exporter; it will be dropped".into());diff --git a/crates/io/tests/flat.rs b/crates/io/tests/flat.rsindex edaff2ec8..e591fbd5c 100644--- a/crates/io/tests/flat.rs+++ b/crates/io/tests/flat.rs@@ -105,7 +105,7 @@ fn indexed_bmp_opens_with_its_color_table() {#[test]fn indexed_png_opens_with_its_color_table() {let pal = [[10, 20, 30], [200, 100, 50], [7, 8, 9], [0, 255, 0]];- let png = photocraft_codecs::encode_png_indexed(2, 2, &[1, 0, 2, 1], &pal, Some(2), None).unwrap();+ let png = photocraft_codecs::encode_png_indexed(2, 2, &[1, 0, 2, 1], &pal, Some(2), None, None).unwrap();let doc = import("indexed.png", &png).unwrap().document;assert_eq!(doc.mode, ColorMode::Indexed);assert_eq!(doc.depth, SampleType::U8);@@ -396,8 +396,8 @@ fn transparent_flat_images_open_as_layer_0() {("ga.png", enc(ChannelLayout::GrayA, CS::U8, Format::Png), true),("a.tif", enc(ChannelLayout::Rgba, CS::U8, Format::Tiff), true),("ga.tif", enc(ChannelLayout::GrayA, CS::U16, Format::Tiff), true),- ("pal.png", photocraft_codecs::encode_png_indexed(w, h, &[0, 1].repeat(n / 2), &[[255, 0, 0], [0, 0, 255]], Some(0), None).unwrap(), true),- ("pal_opaque.png", photocraft_codecs::encode_png_indexed(w, h, &[0, 1].repeat(n / 2), &[[255, 0, 0], [0, 0, 255]], None, None).unwrap(), false),+ ("pal.png", photocraft_codecs::encode_png_indexed(w, h, &[0, 1].repeat(n / 2), &[[255, 0, 0], [0, 0, 255]], Some(0), None, None).unwrap(), true),+ ("pal_opaque.png", photocraft_codecs::encode_png_indexed(w, h, &[0, 1].repeat(n / 2), &[[255, 0, 0], [0, 0, 255]], None, None, None).unwrap(), false),("rgb.png", enc(ChannelLayout::Rgb, CS::U8, Format::Png), false),("g.png", enc(ChannelLayout::Gray, CS::U16, Format::Png), false),("rgb.tif", enc(ChannelLayout::Rgb, CS::U8, Format::Tiff), false),@@ -1114,3 +1114,22 @@ fn a_lab_document_with_one_layer_is_not_reported_as_flattened() {let r = export(&two, "tif", &ExportOptions::default()).unwrap();assert!(r.warnings.iter().any(|w| w.contains("2 layer(s) flattened")), "{:?}", r.warnings);}++#[test]+fn a_stereo_png_keeps_its_stereo_mark_on_save() {+ use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, PngStereo, SampleType as CS};+ let img = Image::from_raw(4, 2, ChannelLayout::Rgb, CS::U8, vec![40u8; 24]).unwrap();+ for view in [PngStereo::Horizontal, PngStereo::Vertical] {+ let bytes = photocraft_codecs::encode(&img, Format::Png, &EncodeOptions { png_stereo: Some(view), ..Default::default() }).unwrap();+ let doc = import("stereo.png", &bytes).unwrap().document;+ assert_eq!(doc.file_encoding.png_stereo, Some(view.mode()));+ // What File > Save does: reuse the settings the file was opened with (#6063).+ let mut opts = ExportOptions::default();+ apply_file_encoding(&doc, &mut opts.encode);+ let r = export(&doc, "png", &opts).unwrap();+ assert_eq!(photocraft_codecs::png_stereo(&r.bytes), Some(view), "{view:?}");+ }+ // An ordinary PNG gains no mark.+ let plain = export(&single(ColorMode::Rgb, SampleType::U8, false), "png", &ExportOptions::default()).unwrap();+ assert_eq!(photocraft_codecs::png_stereo(&plain.bytes), None);+}diff --git a/crates/io/tests/modes.rs b/crates/io/tests/modes.rsindex c16676621..6760c7afe 100644--- a/crates/io/tests/modes.rs+++ b/crates/io/tests/modes.rs@@ -31,7 +31,7 @@ fn indexed_png_keeps_duplicate_palette_colors_opaque() {// choose the first red entry for both pixels, making the opaque one disappear on save.let palette = [[255, 0, 0], [0, 255, 0], [255, 0, 0], [0, 0, 255]];for transparent in [0, 2] {- let png = photocraft_codecs::encode_png_indexed(4, 1, &[0, 1, 2, 3], &palette, Some(transparent), None).unwrap();+ let png = photocraft_codecs::encode_png_indexed(4, 1, &[0, 1, 2, 3], &palette, Some(transparent), None, None).unwrap();let d = photocraft_io::import("in.png", &png).unwrap().document;assert_eq!(d.mode, ColorMode::Indexed);let before = d.color_table.clone();@@ -102,7 +102,7 @@ fn indexed_png_keeps_the_last_palette_index() {palette[0] = [255, 0, 0];palette[255] = [255, 0, 0];for transparent in [0, 255] {- let png = photocraft_codecs::encode_png_indexed(2, 1, &[0, 255], &palette, Some(transparent), None).unwrap();+ let png = photocraft_codecs::encode_png_indexed(2, 1, &[0, 255], &palette, Some(transparent), None, None).unwrap();let d = photocraft_io::import("in.png", &png).unwrap().document;let r = photocraft_io::export(&d, "out.png", &Default::default()).unwrap();assert_eq!(photocraft_codecs::png_palette(&r.bytes).unwrap(), photocraft_codecs::png_palette(&png).unwrap());@@ -112,7 +112,7 @@ fn indexed_png_keeps_the_last_palette_index() {#[test]fn indexed_png_keeps_a_single_transparent_entry() {- let png = photocraft_codecs::encode_png_indexed(2, 1, &[0, 0], &[[255, 0, 0]], Some(0), None).unwrap();+ let png = photocraft_codecs::encode_png_indexed(2, 1, &[0, 0], &[[255, 0, 0]], Some(0), None, None).unwrap();let d = photocraft_io::import("in.png", &png).unwrap().document;let r = photocraft_io::export(&d, "out.png", &Default::default()).unwrap();assert_eq!(photocraft_codecs::png_palette(&r.bytes).unwrap(), photocraft_codecs::png_palette(&png).unwrap());diff --git a/docs/file-format-parity.md b/docs/file-format-parity.mdindex ba7462370..a2a21c9c3 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 (earlier: PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 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 2026+> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-15 · **Change:** minor (PNG `sTER` stereo pairing kept on save, #6063; earlier: PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 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@@ -26,7 +26,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity.| Cloud PSD (.psdc) | R/W | no | no | Out of scope (Adobe cloud) || TIFF | R/W | yes | yes | 8/16/32f, Gray/RGB/CMYK, BigTIFF, every IFD, banded parallel decode; layered TIFF both byte orders (FILE-215-7: extra alpha channels not written) || JPEG | R/W | yes | yes | 8-bit Gray/RGB/CMYK, ICC/EXIF/XMP; Save keeps the opened file's quality (estimated from its quantisation tables, #2399); no JPEG Options dialog (quality 0–12, baseline/progressive) (FILE-215-19) |-| PNG | R/W | yes | yes | 8/16-bit, ICC/text; APNG first frame only; alpha channels on open (#2225); palette PNGs open in Indexed Color mode with their transparent entry (#4804) |+| PNG | R/W | yes | yes | 8/16-bit, ICC/text; APNG first frame only; alpha channels on open (#2225); palette PNGs open in Indexed Color mode with their transparent entry (#4804); Save keeps a stereo PNG's `sTER` pairing (#6063) || GIF | R/W | yes | yes | File › Open keeps the first frame; New Video Layer from File and Video Frames to Layers take every frame, with the timeline rate from the delays (#572). Per-frame delays and keeping the frames in `.pcraft` are not done || BMP | R/W | yes | yes | 8-bit; palette BMPs open in Indexed Color mode || WebP | R/W | yes | yes | Lossless and our own lossy VP8 encoder; ICC/EXIF/XMP; Save keeps an opened file lossy (at its quality) or lossless (#2399) |@@ -142,6 +142,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings.| Date | Change | Summary ||---|---|---|+| 2026-10-15 | minor | PNG: a stereo PNG's `sTER` pairing (PNG Extensions 1.4.0 §3.6) is read on open and written back on save, so the file still says it is a stereo pair (#6063) || 2026-10-14 | minor | PSD smart filter masks: Photoshop stores a smart object's filtered pixels without its filter mask and mixes the unfiltered ones (`FEid`) back in; import now mixes them and export writes them that way, so sf-filter-mask-hard, -gradient and sf-stack-blend-and-mask pass; Photoshop-oracle floor 185 → 188 of 258 || 2026-10-13 | minor | Lossy DNG (compression 34892) decodes: 8-bit baseline JPEG tiles and strips, CFA and LinearRaw, partial edge tiles; the stored values take the normal levels and LinearizationTable (FILE-215-11, lossy DNG part) || 2026-10-14 | minor | Corpus floors raised to the measured results of the CMYK, Lab, 32-bit, Levels, Threshold, Posterize, feather and pass-through fixes landed together: Photoshop-authored 165 → 185 of 258, io 146 → 148 of 170, psd-tools 242 → 249 of 309 |