From a8ed8ca7749643887394363789b269ea47f78a07 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Sat, 31 Oct 2026 09:45:18 +0000 Subject: [PATCH 01/78] fix(effects): parse_cube rejects a hostile LUT_3D_SIZE before cubing it --- crates/effects/src/utility.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/effects/src/utility.rs b/crates/effects/src/utility.rs index e41b42e99..17f0a243b 100644 --- a/crates/effects/src/utility.rs +++ b/crates/effects/src/utility.rs @@ -202,9 +202,12 @@ pub fn parse_cube(text: &str) -> Option { _ => rows.push(three(&mut it)?), } } + if lut.n3 > 256 { + return None; + } let need1 = lut.n1; let need3 = lut.n3 * lut.n3 * lut.n3; - if (lut.n1 == 0 && lut.n3 == 0) || lut.n1 == 1 || lut.n3 == 1 || rows.len() != need1 + need3 || lut.n3 > 256 { + if (lut.n1 == 0 && lut.n3 == 0) || lut.n1 == 1 || lut.n3 == 1 || Some(rows.len()) != need1.checked_add(need3) { return None; } lut.d1 = rows[..need1].to_vec(); @@ -464,6 +467,10 @@ mod tests { fn bad_cube_is_passthrough() { assert!(parse_cube("LUT_3D_SIZE 2\n0 0 0\n1 1 1\n").is_none()); assert!(parse_cube("LUT_3D_SIZE 2\n0 0 zz\n").is_none()); + // A hostile size must be rejected, not overflow `n3^3` or `n1 + n3^3`. + assert!(parse_cube("LUT_3D_SIZE 4294967296\n0 0 0\n").is_none()); + assert!(parse_cube(&format!("LUT_3D_SIZE {}\n0 0 0\n", usize::MAX)).is_none()); + assert!(parse_cube(&format!("LUT_1D_SIZE {}\nLUT_3D_SIZE 2\n0 0 0\n", usize::MAX)).is_none()); let img = test_img(); let out = run("ec.utility.applylut", &[("lut", Value::Str("LUT_3D_SIZE 3\n0 0 0\n".into()))], img.clone()); assert_eq!(out.img, img); From bad3e7c2320d5f8aa8608d3dc725ed301b3ed366 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Sat, 31 Oct 2026 09:45:18 +0000 Subject: [PATCH 02/78] fix(effects): parse_cube rejects a hostile LUT_3D_SIZE before cubing it Co-Authored-By: Claude Sonnet 5.5 --- crates/effects/src/utility.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/effects/src/utility.rs b/crates/effects/src/utility.rs index e87c6d3ff..b38ded8db 100644 --- a/crates/effects/src/utility.rs +++ b/crates/effects/src/utility.rs @@ -215,9 +215,12 @@ pub fn parse_cube(text: &str) -> Option { _ => rows.push(three(&mut it)?), } } + if lut.n3 > 256 { + return None; + } let need1 = lut.n1; let need3 = lut.n3 * lut.n3 * lut.n3; - if (lut.n1 == 0 && lut.n3 == 0) || lut.n1 == 1 || lut.n3 == 1 || rows.len() != need1 + need3 || lut.n3 > 256 { + if (lut.n1 == 0 && lut.n3 == 0) || lut.n1 == 1 || lut.n3 == 1 || Some(rows.len()) != need1.checked_add(need3) { return None; } lut.d1 = rows[..need1].to_vec(); @@ -477,6 +480,10 @@ mod tests { fn bad_cube_is_passthrough() { assert!(parse_cube("LUT_3D_SIZE 2\n0 0 0\n1 1 1\n").is_none()); assert!(parse_cube("LUT_3D_SIZE 2\n0 0 zz\n").is_none()); + // A hostile size must be rejected, not overflow `n3^3` or `n1 + n3^3`. + assert!(parse_cube("LUT_3D_SIZE 4294967296\n0 0 0\n").is_none()); + assert!(parse_cube(&format!("LUT_3D_SIZE {}\n0 0 0\n", usize::MAX)).is_none()); + assert!(parse_cube(&format!("LUT_1D_SIZE {}\nLUT_3D_SIZE 2\n0 0 0\n", usize::MAX)).is_none()); let img = test_img(); let out = run("ec.utility.applylut", &[("lut", Value::Str("LUT_3D_SIZE 3\n0 0 0\n".into()))], img.clone()); assert_eq!(out.img, img); From 9dfc1fb1f76bd4617dc5c3b870abad6a28b8a8d6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:29:18 -0500 Subject: [PATCH 03/78] media: delegate WAV marker formats to shared audio metadata --- Cargo.lock | 21 ++- crates/media/Cargo.toml | 1 + crates/media/src/wav_markers.rs | 279 ++++---------------------------- 3 files changed, 49 insertions(+), 252 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7af09affa..dbe3ea876 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1103,6 +1103,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-audio" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8cfbbc7597221c64f9360657e9acb11a7c79e79b#8cfbbc7597221c64f9360657e9acb11a7c79e79b" +dependencies = [ + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8cfbbc7597221c64f9360657e9acb11a7c79e79b)", + "thiserror 2.0.21", +] + [[package]] name = "craft-doc" version = "0.1.0" @@ -1203,6 +1212,11 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-media" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8cfbbc7597221c64f9360657e9acb11a7c79e79b#8cfbbc7597221c64f9360657e9acb11a7c79e79b" + [[package]] name = "craft-media" version = "0.1.0" @@ -1717,7 +1731,7 @@ dependencies = [ name = "effectcraft-export" version = "0.24.1" dependencies = [ - "craft-audio", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)", "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)", "craft-video", "effectcraft-color", @@ -1883,7 +1897,8 @@ dependencies = [ name = "effectcraft-media" version = "0.24.1" dependencies = [ - "craft-audio", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8cfbbc7597221c64f9360657e9acb11a7c79e79b)", "craft-docpath", "craft-dpx", "craft-exr", @@ -1932,7 +1947,7 @@ dependencies = [ name = "effectcraft-opusenc" version = "0.24.1" dependencies = [ - "craft-audio", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)", ] [[package]] diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index f744c684c..814ea4846 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -10,6 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] +craft-audio-markers = { package = "craft-audio", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8cfbbc7597221c64f9360657e9acb11a7c79e79b", default-features = false } craft-docpath = { workspace = true } effectcraft-time = { workspace = true } effectcraft-color = { workspace = true } diff --git a/crates/media/src/wav_markers.rs b/crates/media/src/wav_markers.rs index ca40824b6..2f8ee8c48 100644 --- a/crates/media/src/wav_markers.rs +++ b/crates/media/src/wav_markers.rs @@ -1,266 +1,37 @@ -//! Markers a WAV file carries, read from its RIFF chunks. -//! -//! Two encodings are read and merged: -//! - **Cue points** (the standard): a `cue ` chunk with one point per marker, named by `labl` (or -//! `note`) sub-chunks of a `LIST` `adtl` chunk, and given a length by `ltxt`. -//! - **XMP** (Adobe's tools): an `_PMX` chunk holding an XMP packet whose `xmpDM:markers` list has -//! one entry per marker (`xmpDM:startTime`, `xmpDM:duration`, `xmpDM:name`), counted in frames -//! of `xmpDM:frameRate` (`f44100` for samples at 44.1 kHz). -//! -//! RF64 files (WAVs over 4 GB) carry a `0xFFFFFFFF` size for a chunk too big for 32 bits and give its real size in a -//! `ds64` chunk; those sizes are resolved so the chunks after the audio are still found. -//! -//! The file is untrusted input: every read is bounds-checked, sizes use checked arithmetic, and -//! the number of markers, of `adtl` sub-chunks looked at and the size of the XMP packet are capped. - -use std::collections::{HashMap, HashSet}; - +//! WAV cue/adtl/RF64/XMP metadata is parsed by craft-audio; timeline policy remains here. +use craft_audio_markers::wav_markers as shared; use effectcraft_color::Label; use effectcraft_project::Marker; use effectcraft_time::Tick; +use std::collections::HashSet; -/// Most markers read from one file. -pub const MAX_MARKERS: usize = 10_000; -/// Largest XMP packet read (bytes). -const MAX_XMP: usize = 4 << 20; -/// Most `adtl` sub-chunks (`labl`, `note`, `ltxt`) looked at in one file: a few per cue point is plenty. +pub use shared::{MAX_MARKERS, is_wav}; +#[cfg(test)] const MAX_ADTL_RECORDS: usize = 4 * MAX_MARKERS; -/// Most entries read from an RF64 file's `ds64` size table. -const MAX_DS64_TABLE: usize = 1_024; - -fn u32_at(b: &[u8], at: usize) -> Option { - let s = b.get(at..at.checked_add(4)?)?; - Some(u32::from_le_bytes(s.try_into().ok()?)) -} - -fn u64_at(b: &[u8], at: usize) -> Option { - let s = b.get(at..at.checked_add(8)?)?; - Some(u64::from_le_bytes(s.try_into().ok()?)) -} - -/// The text of a NUL-terminated label (the rest of the chunk), lossily decoded. -fn label(b: &[u8]) -> String { - let end = b.iter().position(|&c| c == 0).unwrap_or(b.len()); - String::from_utf8_lossy(b.get(..end).unwrap_or_default()).trim().to_string() -} fn secs(frames: f64, rate: f64) -> Tick { if rate > 0.0 && frames.is_finite() { Tick::from_seconds_f64((frames / rate).max(0.0)) } else { Tick::ZERO } } -/// Whether `bytes` start a RIFF/WAVE file. -pub fn is_wav(bytes: &[u8]) -> bool { - matches!(bytes.get(0..4), Some(b"RIFF" | b"RF64")) && bytes.get(8..12) == Some(b"WAVE") -} - -/// The sizes an RF64 file's `ds64` chunk gives for chunks too big for the 32-bit size field. -struct Ds64 { - /// The `data` chunk's size. - data: u64, - /// Other chunks: `(id, size)`. - table: Vec<([u8; 4], u64)>, -} - -impl Ds64 { - /// The real size of chunk `id`, when the file says. - fn size_of(&self, id: &[u8; 4]) -> Option { - if id == b"data" { Some(self.data) } else { self.table.iter().find(|(t, _)| t == id).map(|(_, size)| *size) } - } -} - -/// The `ds64` chunk of an RF64 file (`RF64`, size, `WAVE`, then `ds64`); `None` for any other file or one whose -/// `ds64` doesn't fit. -fn ds64(bytes: &[u8]) -> Option { - if bytes.get(0..4) != Some(b"RF64") || bytes.get(12..16) != Some(b"ds64") { - return None; - } - let size = usize::try_from(u32_at(bytes, 16)?).ok()?; - let body = bytes.get(20..20usize.checked_add(size)?)?; - // riff size (8), data size (8), sample count (8), table length (4), then `(id, size)` entries of 12 bytes - let data = u64_at(body, 8)?; - let entries = usize::try_from(u32_at(body, 24)?).ok()?; - let mut table = Vec::new(); - for i in 0..entries.min(MAX_DS64_TABLE) { - let at = 28usize.checked_add(i.checked_mul(12)?)?; - let id = <[u8; 4]>::try_from(body.get(at..at.checked_add(4)?)?).ok()?; - table.push((id, u64_at(body, at + 4)?)); - } - Some(Ds64 { data, table }) -} - -/// The chunks of a WAVE file as `(id, body)`, stopping at the first one that doesn't fit. -fn chunks(bytes: &[u8]) -> Vec<([u8; 4], &[u8])> { - let big = ds64(bytes); - let mut out = Vec::new(); - let mut at = 12usize; - while let Some(head) = bytes.get(at..at.saturating_add(8)) { - let (Ok(id), Some(field)) = (<[u8; 4]>::try_from(&head[..4]), u32_at(head, 4)) else { break }; - // In an RF64 file a size field of 0xFFFFFFFF stands for the size `ds64` gives. - let size = match &big { - Some(d) if field == u32::MAX => d.size_of(&id).unwrap_or(u64::from(field)), - _ => u64::from(field), - }; - let start = at.saturating_add(8); - let Some(end) = usize::try_from(size).ok().and_then(|n| start.checked_add(n)) else { break }; - let Some(body) = bytes.get(start..end) else { break }; - out.push((id, body)); - // Chunks are padded to an even size. - at = end.saturating_add(end & 1); - } - out -} - -/// The markers `bytes` carry, in time order (empty for anything that isn't a WAV with markers). +/// File markers in timeline order, deduplicated after the app's existing Tick quantization. pub fn read(bytes: &[u8]) -> Vec { - if !is_wav(bytes) { - return Vec::new(); - } - let chunks = chunks(bytes); - let rate = chunks.iter().find(|(id, _)| id == b"fmt ").and_then(|(_, b)| u32_at(b, 4)).map_or(0.0, f64::from); - let mut out = cue_markers(&chunks, rate); - if let Some((_, xmp)) = chunks.iter().find(|(id, _)| id == b"_PMX") { - // Tools that write both encodings repeat each marker. - let mut seen: HashSet<(String, Tick)> = out.iter().map(|o| (o.comment.clone(), o.time)).collect(); - for m in xmp_markers(xmp, rate) { - if seen.insert((m.comment.clone(), m.time)) { - out.push(m); - } + let metadata = shared::read(bytes); + let map = |m: shared::Marker| Marker { + time: secs(m.start, m.rate), + duration: secs(m.duration, m.rate), + comment: m.name, + label: Label::None, + ..Default::default() + }; + let mut out: Vec<_> = metadata.cue.into_iter().map(map).collect(); + let mut seen: HashSet<(String, Tick)> = out.iter().map(|m| (m.comment.clone(), m.time)).collect(); + for marker in metadata.xmp.into_iter().map(map) { + if seen.insert((marker.comment.clone(), marker.time)) { + out.push(marker); } } out.truncate(MAX_MARKERS); - out.sort_by_key(|m| m.time); - out -} - -/// Cue points named and sized by the `adtl` list. -fn cue_markers(chunks: &[([u8; 4], &[u8])], rate: f64) -> Vec { - let Some((_, cue)) = chunks.iter().find(|(id, _)| id == b"cue ") else { return Vec::new() }; - let count = (u32_at(cue, 0).unwrap_or(0) as usize).min(MAX_MARKERS); - // The cue points first: `(id, offset in samples)`. - let mut points = Vec::new(); - for i in 0..count { - let Some(point) = cue.get(4usize.saturating_add(i.saturating_mul(24))..) else { break }; - let (Some(id), Some(offset)) = (u32_at(point, 0), u32_at(point, 20)) else { break }; - points.push((id, offset)); - } - // Only the names and lengths of those ids are kept, so a hostile `adtl` list cannot grow them past the cue count, - // and each record is a lookup, not a scan. - let wanted: HashSet = points.iter().map(|(id, _)| *id).collect(); - let mut names: HashMap = HashMap::new(); - let mut lengths: HashMap = HashMap::new(); - let mut records = 0usize; - 'lists: for (_, list) in chunks.iter().filter(|(id, b)| id == b"LIST" && b.get(0..4) == Some(b"adtl")) { - let mut at = 4usize; - while let Some(head) = list.get(at..at.saturating_add(8)) { - let (Ok(id), Some(size)) = (<[u8; 4]>::try_from(&head[..4]), u32_at(head, 4)) else { break }; - let start = at.saturating_add(8); - let Some(end) = start.checked_add(size as usize) else { break }; - let Some(body) = list.get(start..end) else { break }; - records += 1; - if records > MAX_ADTL_RECORDS { - break 'lists; - } - if let Some(cue_id) = u32_at(body, 0).filter(|c| wanted.contains(c)) { - match &id { - // A `labl` is the name; a `note` only when there is none. - b"labl" => { - names.insert(cue_id, label(body.get(4..).unwrap_or_default())); - } - b"note" => { - names.entry(cue_id).or_insert_with(|| label(body.get(4..).unwrap_or_default())); - } - // The first `ltxt` of a cue point gives its length. - b"ltxt" => { - lengths.entry(cue_id).or_insert_with(|| u32_at(body, 4).unwrap_or(0)); - } - _ => {} - } - } - at = end.saturating_add(end & 1); - } - } - points - .into_iter() - .map(|(id, offset)| { - let comment = names.get(&id).cloned().unwrap_or_default(); - let length = lengths.get(&id).copied().unwrap_or(0); - Marker { time: secs(f64::from(offset), rate), duration: secs(f64::from(length), rate), comment, label: Label::None, ..Default::default() } - }) - .collect() -} - -/// The text of `name` in an XMP entry, as an attribute (`name="v"`) or an element -/// (`v`). -fn xmp_value(entry: &str, name: &str) -> Option { - let attr = format!("{name}=\""); - if let Some(i) = entry.find(&attr) { - let rest = entry.get(i + attr.len()..)?; - return Some(unescape(rest.get(..rest.find('"')?)?)); - } - let open = format!("<{name}>"); - let i = entry.find(&open)?; - let rest = entry.get(i + open.len()..)?; - Some(unescape(rest.get(..rest.find('<')?)?)) -} - -fn unescape(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - let mut rest = s; - while let Some(i) = rest.find('&') { - out.push_str(rest.get(..i).unwrap_or_default()); - let tail = rest.get(i..).unwrap_or_default(); - let Some(semi) = tail.find(';').filter(|&n| n <= 10) else { - out.push('&'); - rest = tail.get(1..).unwrap_or_default(); - continue; - }; - let ent = tail.get(1..semi).unwrap_or_default(); - match ent { - "amp" => out.push('&'), - "lt" => out.push('<'), - "gt" => out.push('>'), - "quot" => out.push('"'), - "apos" => out.push('\''), - _ => { - let code = ent.strip_prefix("#x").and_then(|h| u32::from_str_radix(h, 16).ok()).or_else(|| ent.strip_prefix('#').and_then(|d| d.parse().ok())); - match code.and_then(char::from_u32) { - Some(c) => out.push(c), - None => out.push_str(tail.get(..=semi).unwrap_or_default()), - } - } - } - rest = tail.get(semi + 1..).unwrap_or_default(); - } - out.push_str(rest); - out.trim().to_string() -} - -/// A frame rate as XMP writes it: `f44100`, or `f30000s1001` (rate over scale). -fn xmp_rate(text: &str) -> Option { - let t = text.trim().strip_prefix('f')?; - let (num, den) = t.split_once('s').unwrap_or((t, "1")); - let (n, d): (f64, f64) = (num.parse().ok()?, den.parse().ok()?); - (n > 0.0 && d > 0.0).then_some(n / d) -} - -/// The markers of an XMP packet's `xmpDM:markers` entries. -fn xmp_markers(packet: &[u8], file_rate: f64) -> Vec { - let text = String::from_utf8_lossy(packet.get(..packet.len().min(MAX_XMP)).unwrap_or_default()); - let mut out = Vec::new(); - // The frame rate belongs to the track an entry follows. - let mut rate = file_rate; - for entry in text.split("().ok()) else { continue }; - let length = xmp_value(entry, "xmpDM:duration").and_then(|v| v.trim().parse::().ok()).unwrap_or(0.0); - let comment = xmp_value(entry, "xmpDM:name").unwrap_or_default(); - out.push(Marker { time: secs(start, rate), duration: secs(length, rate), comment, label: Label::None, ..Default::default() }); - if out.len() >= MAX_MARKERS { - break; - } - } + out.sort_by_key(|marker| marker.time); out } @@ -324,6 +95,16 @@ mod tests { chunk(b"LIST", &b) } + #[test] + fn shared_sources_deduplicate_after_app_tick_quantization() { + let xmp = br#""#; + let file = wav(&[fmt(44100), cue(&[(1, 0)]), adtl(&[labl(b"labl", 1, "Same")]), chunk(b"_PMX", xmp)]); + let markers = read(&file); + assert_eq!(markers.len(), 1); + assert_eq!(markers[0].time, Tick::ZERO); + assert_eq!(markers[0].comment, "Same"); + } + #[test] fn cue_points_are_named_by_the_adtl_list_and_timed_in_samples() { let file = wav(&[ From b450219e95d6a5778994e5a0bf17a41514da29c7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:35:22 -0500 Subject: [PATCH 04/78] media: pin reviewed WAV marker memory limits --- Cargo.lock | 8 ++++---- crates/media/Cargo.toml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index dbe3ea876..73c810c44 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1106,9 +1106,9 @@ dependencies = [ [[package]] name = "craft-audio" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8cfbbc7597221c64f9360657e9acb11a7c79e79b#8cfbbc7597221c64f9360657e9acb11a7c79e79b" +source = "git+https://github.com/storytold/craft-libs?rev=4cf4ded6815fb7d37b381ff10cd2654bcbf8e71d#4cf4ded6815fb7d37b381ff10cd2654bcbf8e71d" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8cfbbc7597221c64f9360657e9acb11a7c79e79b)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=4cf4ded6815fb7d37b381ff10cd2654bcbf8e71d)", "thiserror 2.0.21", ] @@ -1215,7 +1215,7 @@ dependencies = [ [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8cfbbc7597221c64f9360657e9acb11a7c79e79b#8cfbbc7597221c64f9360657e9acb11a7c79e79b" +source = "git+https://github.com/storytold/craft-libs?rev=4cf4ded6815fb7d37b381ff10cd2654bcbf8e71d#4cf4ded6815fb7d37b381ff10cd2654bcbf8e71d" [[package]] name = "craft-media" @@ -1898,7 +1898,7 @@ name = "effectcraft-media" version = "0.24.1" dependencies = [ "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)", - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8cfbbc7597221c64f9360657e9acb11a7c79e79b)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=4cf4ded6815fb7d37b381ff10cd2654bcbf8e71d)", "craft-docpath", "craft-dpx", "craft-exr", diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 814ea4846..904b9e68f 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -10,7 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] -craft-audio-markers = { package = "craft-audio", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8cfbbc7597221c64f9360657e9acb11a7c79e79b", default-features = false } +craft-audio-markers = { package = "craft-audio", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "4cf4ded6815fb7d37b381ff10cd2654bcbf8e71d", default-features = false } craft-docpath = { workspace = true } effectcraft-time = { workspace = true } effectcraft-color = { workspace = true } From 5167f8e2fa40fb62e4dfd9521f2f37a68256cf6d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:48:15 -0500 Subject: [PATCH 05/78] media: pin format-clean WAV marker extraction --- Cargo.lock | 8 ++++---- crates/media/Cargo.toml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 73c810c44..30864fae4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1106,9 +1106,9 @@ dependencies = [ [[package]] name = "craft-audio" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4cf4ded6815fb7d37b381ff10cd2654bcbf8e71d#4cf4ded6815fb7d37b381ff10cd2654bcbf8e71d" +source = "git+https://github.com/storytold/craft-libs?rev=58eba9ada1bfe76a1258b55ef0e86ee2ea78dfae#58eba9ada1bfe76a1258b55ef0e86ee2ea78dfae" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=4cf4ded6815fb7d37b381ff10cd2654bcbf8e71d)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=58eba9ada1bfe76a1258b55ef0e86ee2ea78dfae)", "thiserror 2.0.21", ] @@ -1215,7 +1215,7 @@ dependencies = [ [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4cf4ded6815fb7d37b381ff10cd2654bcbf8e71d#4cf4ded6815fb7d37b381ff10cd2654bcbf8e71d" +source = "git+https://github.com/storytold/craft-libs?rev=58eba9ada1bfe76a1258b55ef0e86ee2ea78dfae#58eba9ada1bfe76a1258b55ef0e86ee2ea78dfae" [[package]] name = "craft-media" @@ -1898,7 +1898,7 @@ name = "effectcraft-media" version = "0.24.1" dependencies = [ "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)", - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=4cf4ded6815fb7d37b381ff10cd2654bcbf8e71d)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=58eba9ada1bfe76a1258b55ef0e86ee2ea78dfae)", "craft-docpath", "craft-dpx", "craft-exr", diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 904b9e68f..7a858ddd4 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -10,7 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] -craft-audio-markers = { package = "craft-audio", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "4cf4ded6815fb7d37b381ff10cd2654bcbf8e71d", default-features = false } +craft-audio-markers = { package = "craft-audio", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "58eba9ada1bfe76a1258b55ef0e86ee2ea78dfae", default-features = false } craft-docpath = { workspace = true } effectcraft-time = { workspace = true } effectcraft-color = { workspace = true } From 18c20b41195403f898f89bf53a6f743f2c7599c5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:46:09 -0500 Subject: [PATCH 06/78] Pin WAV marker metadata to merged shared implementation --- Cargo.lock | 8 ++++---- crates/media/Cargo.toml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 30864fae4..8ab12e52c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1106,9 +1106,9 @@ dependencies = [ [[package]] name = "craft-audio" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=58eba9ada1bfe76a1258b55ef0e86ee2ea78dfae#58eba9ada1bfe76a1258b55ef0e86ee2ea78dfae" +source = "git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9cf145669f391e2eb0d#30596f73c5ef851ba3dad9cf145669f391e2eb0d" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=58eba9ada1bfe76a1258b55ef0e86ee2ea78dfae)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9cf145669f391e2eb0d)", "thiserror 2.0.21", ] @@ -1215,7 +1215,7 @@ dependencies = [ [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=58eba9ada1bfe76a1258b55ef0e86ee2ea78dfae#58eba9ada1bfe76a1258b55ef0e86ee2ea78dfae" +source = "git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9cf145669f391e2eb0d#30596f73c5ef851ba3dad9cf145669f391e2eb0d" [[package]] name = "craft-media" @@ -1898,7 +1898,7 @@ name = "effectcraft-media" version = "0.24.1" dependencies = [ "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=47107f660191de2f0b425569506f4daa4faadac9)", - "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=58eba9ada1bfe76a1258b55ef0e86ee2ea78dfae)", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=30596f73c5ef851ba3dad9cf145669f391e2eb0d)", "craft-docpath", "craft-dpx", "craft-exr", diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 7a858ddd4..7e5869c98 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -10,7 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] -craft-audio-markers = { package = "craft-audio", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "58eba9ada1bfe76a1258b55ef0e86ee2ea78dfae", default-features = false } +craft-audio-markers = { package = "craft-audio", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "30596f73c5ef851ba3dad9cf145669f391e2eb0d", default-features = false } craft-docpath = { workspace = true } effectcraft-time = { workspace = true } effectcraft-color = { workspace = true } From 4b658873b745cb5d941d58ccfd80f07cc49d79b9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 08:34:11 -0500 Subject: [PATCH 07/78] psd: delegate bounded recovery PackBits rows to craft-psd --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/psd/src/pixels.rs | 27 ++++++--------------------- crates/psd/src/tests.rs | 14 ++++++++++++++ 4 files changed, 22 insertions(+), 23 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ae7f294a7..a9c0fcf11 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1359,7 +1359,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +source = "git+https://github.com/storytold/craft-libs?rev=55baef0c8d2180b50bcbd8f99a4e8d5bb2389dd6#55baef0c8d2180b50bcbd8f99a4e8d5bb2389dd6" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 21f47439c..94aae50b0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "55baef0c8d2180b50bcbd8f99a4e8d5bb2389dd6" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } diff --git a/crates/psd/src/pixels.rs b/crates/psd/src/pixels.rs index 290a7b6f4..6a2bfc65a 100644 --- a/crates/psd/src/pixels.rs +++ b/crates/psd/src/pixels.rs @@ -482,27 +482,12 @@ enum PlaneStream { /// PackBits decoding of one row (appends exactly `row` bytes, zero-padded). pub(crate) fn unpack_bits(src: &[u8], row: usize, out: &mut Vec) -> Result<()> { - let start = out.len(); - let mut i = 0; - while i < src.len() && out.len() - start < row { - let n = src[i] as i8; - i += 1; - // A packet is written only up to the row's end, so the reserved plane never grows. - let room = row - (out.len() - start); - if n >= 0 { - let k = n as usize + 1; - let s = src.get(i..i + k).ok_or(Error::Truncated)?; - out.extend_from_slice(&s[..k.min(room)]); - i += k; - } else if n != -128 { - let k = (1 - n as isize) as usize; - let v = *src.get(i).ok_or(Error::Truncated)?; - out.extend(std::iter::repeat_n(v, k.min(room))); - i += 1; - } - } - out.resize(start + row, 0); - Ok(()) + // The production caller already charges/reserves the complete plane in Budget. + // Keep the shared recovery API bounded to this row; never relax the app budget. + craft_psd::compression::packbits::decode_padded_into(src, row, row, out).map_err(|error| match error { + craft_psd::PsdError::Decompress(_) => Error::Truncated, + other => Error::Invalid(other.to_string()), + }) } /// PackBits encoding of one row. diff --git a/crates/psd/src/tests.rs b/crates/psd/src/tests.rs index 22c575154..3930e9c53 100644 --- a/crates/psd/src/tests.rs +++ b/crates/psd/src/tests.rs @@ -520,3 +520,17 @@ fn a_failed_inflate_reports_its_status_not_its_output() { let Err(Error::Invalid(msg)) = crate::limits::inflate(&z, 1 << 21) else { panic!("the checksum fails") }; assert!(msg.len() < 100, "{} bytes", msg.len()); } + +#[test] +fn shared_packbits_keeps_padded_rows_and_truncated_packet_errors() { + let mut out = vec![42]; + unpack_bits(&[0, 7], 3, &mut out).unwrap(); + assert_eq!(out, [42, 7, 0, 0]); + unpack_bits(&[128], 2, &mut out).unwrap(); + assert_eq!(out, [42, 7, 0, 0, 0, 0]); + assert_eq!(unpack_bits(&[3, 1], 1, &mut vec![]), Err(Error::Truncated)); + assert_eq!(unpack_bits(&[255], 1, &mut vec![]), Err(Error::Truncated)); + let mut row = vec![]; + unpack_bits(&[0, 9, 255], 1, &mut row).unwrap(); + assert_eq!(row, [9]); +} From 9f2f4a314cdaa1f0edc9cd1cc892f675e1a83ade Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 10:03:37 -0500 Subject: [PATCH 08/78] Pin merged shared PSD PackBits recovery API --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e91297213..a26ae3284 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1359,7 +1359,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=25d2abeb737ccae9ae36ff9aea8af07027e9dbbd#25d2abeb737ccae9ae36ff9aea8af07027e9dbbd" +source = "git+https://github.com/storytold/craft-libs?rev=b774e4d1680a69ab0dc17bc437db93fe530cce36#b774e4d1680a69ab0dc17bc437db93fe530cce36" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index a1520d0b8..63f457c41 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "25d2abeb737ccae9ae36ff9aea8af07027e9dbbd" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "b774e4d1680a69ab0dc17bc437db93fe530cce36" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } From 3bc3adb4e0156ccfede75eae2b955f12dae01e37 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:15:25 +0100 Subject: [PATCH 09/78] psd: parse descriptors and placed layers with craft-psd Pin only craft-psd to craft-libs main 9fc471fc (includes #1887 parse_prefix and #1885 PackBits recovery). Mid-stream descriptor reads use Descriptor::parse_prefix, mapped back to the public effectcraft Descriptor/DValue types. SoLd/SoLE/PlLd placements come from craft_psd::smart::SmartObject, including quiltWarp, and render_placed bakes through craft_psd::FloatImage. Pixel decode stays local until a follow-up can check unmatte parity on composite_f32. --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/psd/src/descriptor.rs | 179 ++++++++++++----------------------- crates/psd/src/parse.rs | 30 +----- crates/psd/src/placed.rs | 149 ++++++++--------------------- crates/psd/src/tests/opt.rs | 6 +- 6 files changed, 107 insertions(+), 261 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1284590d6..ec8643703 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1359,7 +1359,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e836b6fd893eca3fbe5880f000dbf446c3a32fcc#e836b6fd893eca3fbe5880f000dbf446c3a32fcc" +source = "git+https://github.com/storytold/craft-libs?rev=9fc471fc5c18f467394a043adf17f021c2b27cae#9fc471fc5c18f467394a043adf17f021c2b27cae" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 0ed32db9a..5f9b2bede 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e836b6fd893eca3fbe5880f000dbf446c3a32fcc" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9fc471fc5c18f467394a043adf17f021c2b27cae" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } diff --git a/crates/psd/src/descriptor.rs b/crates/psd/src/descriptor.rs index ca711b7ae..74bb44c3f 100644 --- a/crates/psd/src/descriptor.rs +++ b/crates/psd/src/descriptor.rs @@ -108,14 +108,6 @@ impl Descriptor { } } -/// A key or class id: length-prefixed string, or a 4-character code when the length is 0. -pub(crate) fn read_id(r: &mut Reader) -> Result { - let n = r.u32()? as usize; - let n = if n == 0 { 4 } else { n }; - let b = r.bytes(n)?; - Ok(String::from_utf8_lossy(b).into_owned()) -} - pub(crate) fn read_unicode(r: &mut Reader) -> Result { let n = r.u32()? as usize; let mut v = Vec::with_capacity(n.min(r.remaining() / 2)); @@ -128,122 +120,70 @@ pub(crate) fn read_unicode(r: &mut Reader) -> Result { Ok(String::from_utf16_lossy(&v)) } -/// Read a descriptor (after its version field). +/// Read a descriptor (after its version field) with [`craft_psd::descriptor::Descriptor::parse_prefix`]. +/// The public [`Descriptor`] / [`DValue`] types stay this crate's (engine interchange uses them). pub fn read_descriptor(r: &mut Reader) -> Result { - read_descriptor_at(r, 0) + let rest = r.data.get(r.pos..).unwrap_or(&[]); + let (d, used) = craft_psd::descriptor::Descriptor::parse_prefix(rest).map_err(desc_err)?; + r.skip(used)?; + Ok(from_craft_descriptor(d)) } -/// [`read_descriptor`] nested `depth` values deep: the limit in [`read_value`] counts nested -/// descriptors too, so a file can't recurse until the stack overflows. -fn read_descriptor_at(r: &mut Reader, depth: usize) -> Result { - let class_name = read_unicode(r)?; - let class_id = read_id(r)?; - let n = r.u32()? as usize; - if n > 100_000 { - return Err(Error::Invalid("descriptor item count".into())); +fn desc_err(e: craft_psd::PsdError) -> Error { + match e { + craft_psd::PsdError::UnexpectedEof { .. } => Error::Truncated, + craft_psd::PsdError::Unsupported(s) => Error::Unsupported(s), + other => Error::Invalid(other.to_string()), } - let mut items = Vec::with_capacity(n.min(64)); - for _ in 0..n { - let key = read_id(r)?; - let ty = r.tag()?; - let v = read_value(r, &ty, depth)?; - items.push((key, v)); - } - Ok(Descriptor { class_name, class_id, items }) } -fn read_value(r: &mut Reader, ty: &[u8; 4], depth: usize) -> Result { - if depth > 64 { - return Err(Error::Invalid("descriptor nesting".into())); +fn id_str(id: &craft_psd::descriptor::Id) -> String { + String::from_utf8_lossy(id.as_bytes()).into_owned() +} + +fn unit_str(u: &[u8; 4]) -> String { + String::from_utf8_lossy(u).into_owned() +} + +fn from_craft_descriptor(d: craft_psd::descriptor::Descriptor) -> Descriptor { + Descriptor { + class_name: d.name.to_string_lossy(), + class_id: id_str(&d.class_id), + items: d.items.into_iter().map(|(k, v)| (id_str(&k), from_craft_value(v))).collect(), + } +} + +fn from_craft_value(v: craft_psd::descriptor::Value) -> DValue { + use craft_psd::descriptor::Value; + match v { + Value::Descriptor(d) | Value::GlobalObject(d) => DValue::Descriptor(from_craft_descriptor(d)), + Value::List(l) => DValue::List(l.into_iter().map(from_craft_value).collect()), + Value::Double(x) => DValue::Double(if x.is_finite() { x } else { 0.0 }), + Value::UnitFloat { unit, value } => DValue::UnitFloat(unit_str(&unit), if value.is_finite() { value } else { 0.0 }), + Value::UnitFloats { unit, values } => DValue::UnitFloats(unit_str(&unit), values.into_iter().map(|x| if x.is_finite() { x } else { 0.0 }).collect()), + Value::Text(s) => DValue::Text(s.to_string_lossy()), + Value::Enumerated { type_id, value } => DValue::Enum(id_str(&type_id), id_str(&value)), + Value::Integer(i) => DValue::Integer(i), + Value::LargeInteger(i) => DValue::LargeInteger(i), + Value::Boolean(b) => DValue::Bool(b), + Value::Class(c) | Value::GlobalClass(c) => DValue::Class(c.name.to_string_lossy(), id_str(&c.class_id)), + Value::Alias(b) | Value::Path(b) | Value::RawData(b) => DValue::Raw(b), + Value::ObjectArray(o) => DValue::ObjectArray(o.prefix, from_craft_descriptor(o.body)), + Value::Reference(items) => DValue::Reference(items.into_iter().map(from_craft_ref).collect()), + } +} + +fn from_craft_ref(it: craft_psd::descriptor::ReferenceItem) -> RefItem { + use craft_psd::descriptor::ReferenceItem; + match it { + ReferenceItem::Property { class, key } => RefItem::Property(id_str(&class.class_id), id_str(&key)), + ReferenceItem::Class(c) => RefItem::Class(id_str(&c.class_id)), + ReferenceItem::Enumerated { class, type_id, value } => RefItem::Enum(id_str(&class.class_id), id_str(&type_id), id_str(&value)), + ReferenceItem::Offset { class, offset } => RefItem::Offset(id_str(&class.class_id), offset), + ReferenceItem::Identifier { id, .. } => RefItem::Identifier(id as i32), + ReferenceItem::Index { index, .. } => RefItem::Index(index as i32), + ReferenceItem::Name { class, name } => RefItem::Name(id_str(&class.class_id), name.to_string_lossy()), } - Ok(match ty { - b"Objc" | b"GlbO" => DValue::Descriptor(read_descriptor_at(r, depth + 1)?), - b"VlLs" => { - let n = r.u32()? as usize; - if n > 1_000_000 { - return Err(Error::Invalid("descriptor list length".into())); - } - let mut v = Vec::with_capacity(n.min(256)); - for _ in 0..n { - let t = r.tag()?; - v.push(read_value(r, &t, depth + 1)?); - } - DValue::List(v) - } - b"ObAr" => { - let n = r.u32()?; - DValue::ObjectArray(n, read_descriptor_at(r, depth + 1)?) - } - b"doub" => DValue::Double(r.f64_finite()?), - b"UntF" => { - let unit = String::from_utf8_lossy(&r.tag()?).into_owned(); - DValue::UnitFloat(unit, r.f64_finite()?) - } - b"UnFl" => { - let unit = String::from_utf8_lossy(&r.tag()?).into_owned(); - let n = r.u32()? as usize; - let mut v = Vec::with_capacity(n.min(1024)); - for _ in 0..n { - v.push(r.f64_finite()?); - } - DValue::UnitFloats(unit, v) - } - b"TEXT" => DValue::Text(read_unicode(r)?), - b"enum" => { - let t = read_id(r)?; - DValue::Enum(t, read_id(r)?) - } - b"long" => DValue::Integer(r.u32()? as i32), - b"comp" => DValue::LargeInteger(r.u64()? as i64), - b"bool" => DValue::Bool(r.u8()? != 0), - b"type" | b"GlbC" => { - let name = read_unicode(r)?; - DValue::Class(name, read_id(r)?) - } - b"alis" | b"tdta" | b"Pth " => { - let n = r.u32()? as usize; - DValue::Raw(r.bytes(n)?.to_vec()) - } - b"obj " => { - let n = r.u32()? as usize; - let mut items = Vec::with_capacity(n.min(16)); - for _ in 0..n { - let t = r.tag()?; - items.push(match &t { - b"prop" => { - let _name = read_unicode(r)?; - let class = read_id(r)?; - RefItem::Property(class, read_id(r)?) - } - b"Clss" => { - let _name = read_unicode(r)?; - RefItem::Class(read_id(r)?) - } - b"Enmr" => { - let _name = read_unicode(r)?; - let class = read_id(r)?; - let ty = read_id(r)?; - RefItem::Enum(class, ty, read_id(r)?) - } - b"rele" => { - let _name = read_unicode(r)?; - let class = read_id(r)?; - RefItem::Offset(class, r.u32()? as i32) - } - b"Idnt" => RefItem::Identifier(r.u32()? as i32), - b"indx" => RefItem::Index(r.u32()? as i32), - b"name" => { - let _name = read_unicode(r)?; - let class = read_id(r)?; - RefItem::Name(class, read_unicode(r)?) - } - other => return Err(Error::Invalid(format!("reference item `{}`", String::from_utf8_lossy(other)))), - }); - } - DValue::Reference(items) - } - other => return Err(Error::Invalid(format!("descriptor type `{}`", String::from_utf8_lossy(other)))), - }) } // ---------------------------------------------------------------- writing @@ -387,11 +327,16 @@ fn write_value(out: &mut Vec, v: &DValue) { out.extend_from_slice(&o.to_be_bytes()); } RefItem::Identifier(i) => { + // Photoshop stores a class before the id; craft-psd reads it that way. out.extend_from_slice(b"Idnt"); + put_unicode(out, ""); + put_id(out, "null"); out.extend_from_slice(&i.to_be_bytes()); } RefItem::Index(i) => { out.extend_from_slice(b"indx"); + put_unicode(out, ""); + put_id(out, "null"); out.extend_from_slice(&i.to_be_bytes()); } RefItem::Name(c, n) => { diff --git a/crates/psd/src/parse.rs b/crates/psd/src/parse.rs index 3f70a67b5..9fb2ce6b6 100644 --- a/crates/psd/src/parse.rs +++ b/crates/psd/src/parse.rs @@ -1,7 +1,5 @@ use super::limits::{Error, Result}; -use super::model::{ - Adjustment, ChannelInfo, ColorMode, Layer, LayerMask, LinkedFile, MAX_GROUP_DEPTH, Node, Rect, Section, SmartObject, SubPath, TextInfo, VectorMask, -}; +use super::model::{Adjustment, ChannelInfo, ColorMode, Layer, LayerMask, LinkedFile, MAX_GROUP_DEPTH, Node, Rect, Section, SubPath, TextInfo, VectorMask}; use super::{Psd, Reader, descriptor, engine_data, placed}; use std::sync::Arc; @@ -236,32 +234,10 @@ impl Psd { l.adjustment = Some(Adjustment::Other(String::from_utf8_lossy(key).into_owned())); } b"SoLd" | b"SoLE" => { - let _id = r.tag()?; - let _ver = r.u32()?; - let _dver = r.u32()?; - let d = descriptor::read_descriptor(&mut r)?; - let uuid = d.text("Idnt").unwrap_or_default().to_string(); - let t = placed::eight(&d, "Trnf").unwrap_or([0.0; 8]); - // The non-affine transform when present (perspective), else the transform. - let t = placed::eight(&d, "nonAffineTransform").unwrap_or(t); - let size = d.obj("Sz ").and_then(|s| Some([s.num("Wdth")?, s.num("Hght")?])); - let warp = d.obj("warp").and_then(placed::Warp::read); - l.smart_object = Some(SmartObject { uuid, quad: placed::quad_from(t), size, warp }); + l.smart_object = Some(placed::from_craft_smart(craft_psd::smart::SmartObject::from_placed_layer_data(b).map_err(|e| error(&e))?)); } b"PlLd" if l.smart_object.is_none() => { - let _id = r.tag()?; - let _ver = r.u32()?; - let n = r.u8()? as usize; - let uuid = String::from_utf8_lossy(r.bytes(n)?).into_owned(); - let _page = r.u32()?; - let _pages = r.u32()?; - let _aa = r.u32()?; - let _ty = r.u32()?; - let mut t = [0.0; 8]; - for v in &mut t { - *v = r.f64_finite()?; - } - l.smart_object = Some(SmartObject { uuid, quad: placed::quad_from(t), size: None, warp: None }); + l.smart_object = Some(placed::from_craft_smart(craft_psd::smart::SmartObject::from_placed_layer(b).map_err(|e| error(&e))?)); } b"vmsk" | b"vsms" => { let _ver = r.u32()?; diff --git a/crates/psd/src/placed.rs b/crates/psd/src/placed.rs index 981f4ff23..5cc0c336d 100644 --- a/crates/psd/src/placed.rs +++ b/crates/psd/src/placed.rs @@ -14,14 +14,7 @@ use crate::{Pixels, SmartObject}; /// The most pixels a baked smart object may have: 2^24 (256 MiB as float RGBA). The size comes /// from the file's transform, which is untrusted. -pub const MAX_BAKE_PIXELS: u64 = 1 << 24; - -/// The bake's rasterising budget, in bounding-box pixels visited over all mesh triangles, as a -/// multiple of the output pixel count. A sane warp visits about 2× the output; a hostile mesh -/// that makes every triangle cover the whole output would visit thousands of times more. -const BAKE_WORK_FACTOR: u64 = 8; -/// The smallest budget, so tiny outputs are never refused for rounding at the triangle edges. -const MIN_BAKE_WORK: u64 = 1 << 20; +pub const MAX_BAKE_PIXELS: u64 = craft_psd::smart::MAX_BAKE_PIXELS; /// A placed layer's warp. #[derive(Clone, Debug, Default, PartialEq)] @@ -61,14 +54,40 @@ pub(crate) fn floats(v: Option<&DValue>) -> Vec { } } -/// The eight numbers of a transform entry (`Trnf`, `nonAffineTransform`), when it has exactly eight. -pub(crate) fn eight(d: &Descriptor, key: &str) -> Option<[f64; 8]> { - floats(d.get(key)).try_into().ok() +pub(crate) fn from_craft_smart(s: craft_psd::smart::SmartObject) -> SmartObject { + SmartObject { uuid: s.uuid, quad: s.quad, size: s.size, warp: s.warp.map(from_craft_warp) } } -/// The corner quad (top-left, top-right, bottom-right, bottom-left) from x0 y0 … x3 y3. -pub(crate) fn quad_from(t: [f64; 8]) -> [[f64; 2]; 4] { - [[t[0], t[1]], [t[2], t[3]], [t[4], t[5]], [t[6], t[7]]] +fn from_craft_warp(w: craft_psd::smart::Warp) -> Warp { + Warp { + style: w.style, + bend: w.bend, + horizontal: w.horizontal, + vertical: w.vertical, + rotate_vertical: w.rotate_vertical, + bounds: w.bounds, + cols: w.cols, + rows: w.rows, + mesh: w.mesh, + } +} + +fn to_craft_smart(s: &SmartObject) -> craft_psd::smart::SmartObject { + craft_psd::smart::SmartObject { uuid: s.uuid.clone(), quad: s.quad, size: s.size, warp: s.warp.as_ref().map(to_craft_warp) } +} + +fn to_craft_warp(w: &Warp) -> craft_psd::smart::Warp { + craft_psd::smart::Warp { + style: w.style.clone(), + bend: w.bend, + horizontal: w.horizontal, + vertical: w.vertical, + rotate_vertical: w.rotate_vertical, + bounds: w.bounds, + cols: w.cols, + rows: w.rows, + mesh: w.mesh.clone(), + } } impl Warp { @@ -313,105 +332,11 @@ impl SmartObject { /// `k` pixels per document pixel (into `size` pixels when given; see [`Self::placed_size`]). /// Returns the pixels and their document-space origin. `None` when the content is empty or /// the baked image would exceed [`MAX_BAKE_PIXELS`] or the mesh needs more rasterising work than - /// the budget allows (see [`BAKE_WORK_FACTOR`]). + /// the budget allows. pub fn render_placed(&self, content: &Pixels, k: f64, size: Option<(u32, u32)>) -> Option<(Pixels, [f64; 2])> { - let (cw, ch) = (content.width as f64, content.height as f64); - if content.width == 0 || content.height == 0 { - return None; - } - // The quad is solved once for the bounds, the size and the whole grid. - let m = square_to_quad(self.quad); - let bb = self.bounds_with(&m, cw, ch); - let (ow, oh) = match size { - Some((w, h)) => (w.max(1), h.max(1)), - None => size_for(bb, k), - }; - let (ow, oh) = (ow as usize, oh as usize); - let count = ow.checked_mul(oh).filter(|&c| c as u64 <= MAX_BAKE_PIXELS)?; - // A forward grid, filled triangle by triangle with inverse barycentric sampling. - let n = 48usize; - let mut dst = Vec::with_capacity((n + 1) * (n + 1)); - let mut src = Vec::with_capacity((n + 1) * (n + 1)); - for j in 0..=n { - for i in 0..=n { - let s = [i as f64 / n as f64 * cw, j as f64 / n as f64 * ch]; - let d = self.map_with(&m, s, cw, ch); - dst.push([(d[0] - bb[0]) * k, (d[1] - bb[1]) * k]); - src.push(s); - } - } - let mut out: Vec<[f32; 4]> = Vec::new(); - out.try_reserve_exact(count).ok()?; - out.resize(count, [0.0; 4]); - let sample = |x: f64, y: f64| -> [f32; 4] { - let (fx, fy) = ((x - 0.5).clamp(0.0, cw - 1.0), (y - 0.5).clamp(0.0, ch - 1.0)); - let (x0, y0) = (fx.floor() as usize, fy.floor() as usize); - let (x1, y1) = ((x0 + 1).min(content.width as usize - 1), (y0 + 1).min(content.height as usize - 1)); - let (a, b) = ((fx - x0 as f64) as f32, (fy - y0 as f64) as f32); - let at = |x: usize, y: usize| { - let p = content.data[y * content.width as usize + x]; - [p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]] - }; - let (p00, p10, p01, p11) = (at(x0, y0), at(x1, y0), at(x0, y1), at(x1, y1)); - let mut o = [0.0; 4]; - for c in 0..4 { - o[c] = (p00[c] * (1.0 - a) + p10[c] * a) * (1.0 - b) + (p01[c] * (1.0 - a) + p11[c] * a) * b; - } - o - }; - let idx = |i: usize, j: usize| j * (n + 1) + i; - // A sane mesh's triangles each span about one grid cell (ow/n by oh/n), rounded out to - // whole pixels. A thin output (16384×1) stacks every grid row onto the same pixel row, so - // allow each of the 2n² triangles about two cells' extent along each axis, with margin. - let rounding = (4 * n as u64).saturating_mul((ow as u64).saturating_add(oh as u64).saturating_add(n as u64)); - let budget = (count as u64).saturating_mul(BAKE_WORK_FACTOR).max(MIN_BAKE_WORK).saturating_add(rounding); - let mut work = 0u64; - for j in 0..n { - for i in 0..n { - for tri in [[idx(i, j), idx(i + 1, j), idx(i + 1, j + 1)], [idx(i, j), idx(i + 1, j + 1), idx(i, j + 1)]] { - let [a, b, c] = tri.map(|t| dst[t]); - let den = (b[1] - c[1]) * (a[0] - c[0]) + (c[0] - b[0]) * (a[1] - c[1]); - if den.abs() < 1e-12 { - continue; - } - // Loop-invariant per triangle: the source corners and the barycentric coefficients. - let [sa, sb, sc] = tri.map(|t| src[t]); - let (l1y, l1x) = (b[1] - c[1], c[0] - b[0]); - let (l2y, l2x) = (c[1] - a[1], a[0] - c[0]); - let x0 = a[0].min(b[0]).min(c[0]).floor().max(0.0) as usize; - let x1 = (a[0].max(b[0]).max(c[0]).ceil() as usize).min(ow); - let y0 = a[1].min(b[1]).min(c[1]).floor().max(0.0) as usize; - let y1 = (a[1].max(b[1]).max(c[1]).ceil() as usize).min(oh); - work = work.saturating_add((x1.saturating_sub(x0) as u64).saturating_mul(y1.saturating_sub(y0) as u64)); - if work > budget { - return None; - } - for y in y0..y1 { - for x in x0..x1 { - let (px, py) = (x as f64 + 0.5, y as f64 + 0.5); - let l1 = (l1y * (px - c[0]) + l1x * (py - c[1])) / den; - let l2 = (l2y * (px - c[0]) + l2x * (py - c[1])) / den; - let l3 = 1.0 - l1 - l2; - if l1 < -1e-9 || l2 < -1e-9 || l3 < -1e-9 { - continue; - } - let sx = sa[0] * l1 + sb[0] * l2 + sc[0] * l3; - let sy = sa[1] * l1 + sb[1] * l2 + sc[1] * l3; - out[y * ow + x] = sample(sx, sy); - } - } - } - } - } - // Back to straight alpha. - for p in &mut out { - if p[3] > 0.0 { - for c in 0..3 { - p[c] /= p[3]; - } - } - } - Some((Pixels { width: ow as u32, height: oh as u32, data: out }, [bb[0], bb[1]])) + let img = craft_psd::FloatImage { width: content.width, height: content.height, data: content.data.clone() }; + let (out, origin) = to_craft_smart(self).render_placed(&img, k, size)?; + Some((Pixels { width: out.width, height: out.height, data: out.data }, origin)) } } diff --git a/crates/psd/src/tests/opt.rs b/crates/psd/src/tests/opt.rs index 241af0069..fac3a9c63 100644 --- a/crates/psd/src/tests/opt.rs +++ b/crates/psd/src/tests/opt.rs @@ -641,11 +641,11 @@ fn placed_bake_solves_the_quad_once() { assert_eq!(counters::take(&QUAD), 1, "33×33 mapped points, one solve (was 1089)"); so.placed_size(20.0, 10.0, 1.0); assert_eq!(counters::take(&QUAD), 1); - // The bounds, the size and the 49×49 grid of one bake share a single solve (was 1089 × 2 + 2401). + // The bake itself runs in craft-psd, so it no longer bumps this crate's quad counter. so.render_placed(&content(20, 10), 1.0, None).unwrap(); - assert_eq!(counters::take(&QUAD), 1); + assert_eq!(counters::take(&QUAD), 0); so.render_placed(&content(20, 10), 1.0, Some((40, 40))).unwrap(); - assert_eq!(counters::take(&QUAD), 1); + assert_eq!(counters::take(&QUAD), 0); // A single `map` still solves for itself. so.map([1.0, 1.0], 20.0, 10.0); assert_eq!(counters::take(&QUAD), 1); From c7505fcafc0bb2823e7070dbbbe141aa0303f92b Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:00:59 +0530 Subject: [PATCH 10/78] #3464: raster: Gaussian blur as if the image went on with transparency gaussian_blur's box passes drop what they spread past the buffer's edge, so a blur wider than its buffer comes out far too faint: three boxes of radius 15000 on a 4096-pixel line keep about 3 % of the centre value per axis. gaussian_blur_unbounded gives the same three boxes as if the image continued with transparency, at O(length) per line whatever the sigma: each box is a difference of prefix sums, so three are eight terms of the third prefix sum, which is a polynomial past the line's ends. The sums are f64. The test compares it with gaussian_blur on a buffer padded past the blur's reach, up to sigma 15000 along each axis. --- crates/raster/src/blur.rs | 148 ++++++++++++++++++++++++++++++++++++++ crates/raster/src/lib.rs | 2 +- 2 files changed, 149 insertions(+), 1 deletion(-) diff --git a/crates/raster/src/blur.rs b/crates/raster/src/blur.rs index 76e51f865..e8e98281a 100644 --- a/crates/raster/src/blur.rs +++ b/crates/raster/src/blur.rs @@ -182,6 +182,111 @@ pub fn gaussian_blur(img: &Image, sigma_x: f64, sigma_y: f64, repeat: bool) -> I box_passes(img, &rx, &ry, repeat) } +/// [`gaussian_blur`] with transparent edges, as if the image went on with transparency on +/// every side: what a box pass spreads past the edge still feeds the passes after it, where +/// [`gaussian_blur`] drops it. For blurs that reach past the buffer holding them (an effect's +/// padding cut to its pixel budget), which [`gaussian_blur`] leaves far too faint once the +/// boxes are wider than the buffer. A line costs O(length) whatever the sigma. +pub fn gaussian_blur_unbounded(img: &Image, sigma_x: f64, sigma_y: f64) -> Image { + let (w, h) = (img.width as usize, img.height as usize); + let mut out = img.clone(); + if w == 0 || h == 0 { + return out; + } + if let Some(r) = unbounded_radii(sigma_x) { + out.data.par_chunks_mut(w).for_each(|row| boxes_unbounded(row, r)); + } + if let Some(r) = unbounded_radii(sigma_y) { + let cols: Vec> = (0..w) + .into_par_iter() + .map(|x| { + let mut col: Vec = out.data.iter().skip(x).step_by(w).copied().collect(); + boxes_unbounded(&mut col, r); + col + }) + .collect(); + out.data.par_chunks_mut(w).enumerate().for_each(|(y, row)| { + for (o, col) in row.iter_mut().zip(&cols) { + if let Some(v) = col.get(y) { + *o = *v; + } + } + }); + } + out +} + +/// [`gaussian_blur`]'s three box radii for `sigma`, or `None` where it doesn't blur (and for +/// a sigma that isn't finite). +fn unbounded_radii(sigma: f64) -> Option<[i64; 3]> { + if !(sigma > 0.05 && sigma.is_finite()) { + return None; + } + match box_radii(sigma, 3).as_slice() { + &[a, b, c] => Some([a, b, c].map(|r| i64::try_from(r).unwrap_or(i64::MAX / 8))), + _ => None, + } +} + +/// Three transparent-edged box passes of radii `r` over `line`, as if it went on with zeros. +/// +/// One box is a difference of prefix sums, `(S(x + r) − S(x − r − 1)) / (2r + 1)`, so three are +/// eight signed terms of the third prefix sum `S3`. Past the line's ends the prefix sums are +/// polynomials: `S3(m) = 0` before it, and after it, `j = m − n + 1` steps on, +/// `S3(m) = S3(n − 1) + j·S2(n − 1) + T·j(j + 1)/2` with `T` the line's total. The sums are +/// `f64`: the eight terms cancel to a value `(2r + 1)³` times smaller. +fn boxes_unbounded(line: &mut [Px], r: [i64; 3]) { + let n = line.len(); + let Ok(n_i) = i64::try_from(n) else { return }; + if n == 0 { + return; + } + let mut s3 = Vec::with_capacity(n); + let (mut s1, mut s2, mut acc) = ([0.0f64; 4], [0.0f64; 4], [0.0f64; 4]); + for p in line.iter() { + for c in 0..4 { + s1[c] += f64::from(p[c]); + s2[c] += s1[c]; + acc[c] += s2[c]; + } + s3.push(acc); + } + let (total, s2_end, s3_end) = (s1, s2, acc); + let at = |m: i64| -> [f64; 4] { + if m < 0 { + return [0.0; 4]; + } + if let Some(v) = usize::try_from(m).ok().and_then(|i| s3.get(i)) { + return *v; + } + let j = (m - n_i + 1) as f64; + std::array::from_fn(|c| s3_end[c] + j * s2_end[c] + total[c] * j * (j + 1.0) / 2.0) + }; + // The eight shifts and signs: each box adds `S(x + r)` and subtracts `S(x − r − 1)`. + let mut terms = [(0i64, 1.0f64); 8]; + for (k, t) in terms.iter_mut().enumerate() { + for (b, &ri) in r.iter().enumerate() { + if k >> b & 1 == 0 { + t.0 = t.0.saturating_add(ri); + } else { + t.0 = t.0.saturating_sub(ri.saturating_add(1)); + t.1 = -t.1; + } + } + } + let norm: f64 = r.iter().map(|&ri| (2 * ri + 1) as f64).product(); + for (x, o) in (0i64..).zip(line.iter_mut()) { + let mut v = [0.0f64; 4]; + for &(shift, sign) in &terms { + let s = at(x.saturating_add(shift)); + for c in 0..4 { + v[c] += sign * s[c]; + } + } + *o = v.map(|v| (v / norm) as f32); + } +} + /// Below this sigma (pixels) three integer-radius box passes are too coarse (sigma under ~0.6 is /// a no-op and the result steps between a few shapes), so [`gaussian_blur_exact`] is used instead. const EXACT_SIGMA_BELOW: f64 = 3.0; @@ -520,4 +625,47 @@ mod tests { assert_eq!(r.len(), 3); assert!(r.iter().all(|&v| (7..=10).contains(&v)), "{r:?}"); } + + /// #3464: [`gaussian_blur_unbounded`] is [`gaussian_blur`] on the image padded with enough + /// transparency to hold every pass, cropped back: what a pass spreads past the edge comes + /// back in the passes after it. Sigmas far wider than the image too, along each axis. + #[test] + fn unbounded_gaussian_matches_a_buffer_padded_past_its_reach() { + let pattern = |w: u32, h: u32| { + let mut img = Image::new(w, h); + for (i, p) in img.data.iter_mut().enumerate() { + let v = ((i * 7919) % 101) as f32 / 101.0; + *p = [v, v * 0.5, 1.0 - v, (v + 0.3).min(1.0)]; + } + img + }; + let cases = [ + (pattern(23, 17), 4.0f64, 0.0f64, 1e-4), + (pattern(23, 17), 0.0, 6.0, 1e-4), + (pattern(23, 17), 7.5, 3.2, 1e-4), + (pattern(23, 17), 60.0, 45.0, 1e-4), + // The reference's f32 running sums drift over its 90 000-pixel line (by 1.5e-4 of + // the value against an f64 evaluation, which this matches to 1e-9). + (pattern(40, 1), 15000.0, 0.0, 1e-3), + (pattern(1, 40), 0.0, 15000.0, 1e-3), + ]; + for (img, sx, sy, tol) in cases { + // Three boxes of radius about σ each reach at most 3σ + 2. Padded by hand, along + // the blurred axes only (`Image::padded` pads both and caps a side at 30000). + let reach = |s: f64| if s > 0.0 { (s * 3.0 + 4.0).ceil() as u32 } else { 0 }; + let (px, py) = (reach(sx), reach(sy)); + let mut big = Image::new(img.width + 2 * px, img.height + 2 * py); + for y in 0..img.height { + for x in 0..img.width { + big.set(x + px, y + py, img.get(x as i64, y as i64)); + } + } + let want = gaussian_blur(&big, sx, sy, false).crop(px as i64, py as i64, img.width, img.height); + let got = gaussian_blur_unbounded(&img, sx, sy); + let peak = want.data.iter().flatten().fold(0.0f32, |m, v| m.max(v.abs())); + for (a, b) in got.data.iter().flatten().zip(want.data.iter().flatten()) { + assert!((a - b).abs() <= tol * peak.max(1e-6), "σ ({sx}, {sy}) on {}×{}: {a} vs {b} (peak {peak})", img.width, img.height); + } + } + } } diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index e18a24c63..b94874944 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -17,7 +17,7 @@ pub mod yuv; use effectcraft_color::{BlendMode, blend_pixel}; use rayon::prelude::*; -pub use blur::{box_blur, directional_blur, gaussian_blur, gaussian_blur_exact, gaussian_is_exact, radial_blur}; +pub use blur::{box_blur, directional_blur, gaussian_blur, gaussian_blur_exact, gaussian_blur_unbounded, gaussian_is_exact, radial_blur}; pub use channels3d::AuxChannels; pub use warp::{Sampling, WarpOpts, accumulate_warp, composite_warp, composite_warp_changed, composite_warp_reference, resample}; From cfea5b4bf96f43cd8a463b82ab461c88c8f0066e Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:04:44 +0530 Subject: [PATCH 11/78] #3492: CC Power Pin Expansion takes After Effects' -200 minimum Top, Left, Right and Bottom Expansion had a hard range of -100..1000, so prop.set and the value editors stored -100 for After Effects' valid -200..-100. The hard minimum is now -200; the 1000 maximum, the default and the 0..100 slider are unchanged. The engine range table covers both ends through prop.set, undo/redo, save/reopen and an older project's stored range, and the four rows leave the aep KNOWN_NARROWER list. --- crates/aep/src/export/fx_defs.rs | 4 ---- crates/effects/src/distort3.rs | 10 ++++++---- crates/engine/src/tests/effect_ranges.rs | 4 ++++ 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index 338e00fc5..e32ecbb6f 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -737,10 +737,6 @@ mod tests { ("ec.time.pixelmotionblur", "shutterSamples", 3482), ("ec.noise.fractal", "subSettings/subInfluence", 3485), ("ec.noise.fractal", "subSettings/subScaling", 3486), - ("ec.distort.ccpowerpin", "expandTop", 3492), - ("ec.distort.ccpowerpin", "expandLeft", 3492), - ("ec.distort.ccpowerpin", "expandRight", 3492), - ("ec.distort.ccpowerpin", "expandBottom", 3492), ]; /// `a` is at most `b`, allowing for the `f32` the recorded bounds were read from. diff --git a/crates/effects/src/distort3.rs b/crates/effects/src/distort3.rs index 34fc282ed..ed88e2d84 100644 --- a/crates/effects/src/distort3.rs +++ b/crates/effects/src/distort3.rs @@ -955,10 +955,12 @@ pub fn specs() -> Vec { p("bottomRight", "Bottom Right", pt(1.0, 1.0), ParamUi::Point), p("perspective", "Perspective", num(100.0), pct()), p("unstretch", "Unstretch", Value::Bool(false), ParamUi::Checkbox), - p("expandTop", "Top", num(0.0), slider(-100.0, 1000.0, 0.0, 100.0, 1)), - p("expandLeft", "Left", num(0.0), slider(-100.0, 1000.0, 0.0, 100.0, 1)), - p("expandRight", "Right", num(0.0), slider(-100.0, 1000.0, 0.0, 100.0, 1)), - p("expandBottom", "Bottom", num(0.0), slider(-100.0, 1000.0, 0.0, 100.0, 1)), + // Expansion: percent of the layer size each source edge moves out (After Effects' + // valid range is -200..200; the maximum stays at 1000 so existing values are kept). + p("expandTop", "Top", num(0.0), slider(-200.0, 1000.0, 0.0, 100.0, 1)), + p("expandLeft", "Left", num(0.0), slider(-200.0, 1000.0, 0.0, 100.0, 1)), + p("expandRight", "Right", num(0.0), slider(-200.0, 1000.0, 0.0, 100.0, 1)), + p("expandBottom", "Bottom", num(0.0), slider(-200.0, 1000.0, 0.0, 100.0, 1)), ], cc_power_pin, ), diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index 7deaaa911..37f7053af 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -60,6 +60,10 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3471, "ec.distort.transform", "scaleHeight", -30000.0, 30000.0), (3471, "ec.distort.transform", "scaleWidth", -30000.0, 30000.0), (3470, "ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 0.0, 100000.0), + (3492, "ec.distort.ccpowerpin", "expandTop", -200.0, 1000.0), + (3492, "ec.distort.ccpowerpin", "expandLeft", -200.0, 1000.0), + (3492, "ec.distort.ccpowerpin", "expandRight", -200.0, 1000.0), + (3492, "ec.distort.ccpowerpin", "expandBottom", -200.0, 1000.0), ]; fn path(effect: &str, param: &str) -> String { From 9e3cfa639ac9d3ac28af9b0d5e1317555cd41e20 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:04:45 +0530 Subject: [PATCH 12/78] #3492: test CC Power Pin below -100 % Expansion on CPU and GPU Below -100 % an Expansion edge crosses the opposite one and the source rectangle flips. Pin that geometry, check that the extremes (including a zero-size source and Unstretch) keep the buffer size and render finite pixels, and compare CPU and GPU at the new minimum. --- crates/effects/src/distort3/tests.rs | 51 ++++++++++++++++++++++++++++ crates/gpu/src/tests/fx_stylize.rs | 6 ++++ 2 files changed, 57 insertions(+) diff --git a/crates/effects/src/distort3/tests.rs b/crates/effects/src/distort3/tests.rs index b50d6b450..cea83cfd2 100644 --- a/crates/effects/src/distort3/tests.rs +++ b/crates/effects/src/distort3/tests.rs @@ -250,6 +250,57 @@ fn power_pin_unstretch_expands_pinned_region() { assert!(maxd(&id.img, &im) < 1e-4); } +/// #3492: an Expansion side moves that edge of the source rectangle by a percent of the layer +/// size. Below -100 % it crosses the opposite edge, so the rectangle flips: Top -200 and Bottom +/// -100 take rows 40 down to 0 of a 20-row layer, a mirrored copy squeezed into the bottom half +/// (the top half samples below the layer and is transparent). -100 for both would mirror the +/// whole layer. +#[test] +fn power_pin_expansion_below_minus_100_flips_the_source() { + let im = img(20, 20); + let o = run("ec.distort.ccpowerpin", &[("expandTop", num(-200.0)), ("expandBottom", num(-100.0))], im.clone(), &[]); + assert_eq!((o.img.width, o.img.height), (20, 20)); + // Output row 15: v = 15.5 / 20, source y = 40 - 40 v = 9 (between rows 8 and 9). + let px = o.img.get(10, 15); + assert!((px[1] - 8.5 / 20.0).abs() < 1e-3, "{px:?}"); + assert_eq!(o.img.get(10, 5)[3], 0.0); + let both = run("ec.distort.ccpowerpin", &[("expandTop", num(-100.0)), ("expandBottom", num(-100.0))], im.clone(), &[]); + // Source y = 20 - 20 v = 4.5, row 4's centre. + let px = both.img.get(10, 15); + assert!((px[1] - 4.0 / 20.0).abs() < 1e-3, "{px:?}"); +} + +/// #3492: the buffer is sized by the pins alone, and Expansions at the ends of -200..1000 render +/// finite images: all sides at either end, flipped sources, a zero-size source (Top -50, Bottom +/// -50), and Unstretch, which divides by the source size (a zero size renders transparent). +#[test] +fn power_pin_is_finite_at_the_expansion_extremes() { + let im = img(24, 16); + let pins = [("topLeft", pt(3.0, -4.0)), ("topRight", pt(26.0, 2.0)), ("bottomRight", pt(20.0, 18.0)), ("bottomLeft", pt(-2.0, 14.0))]; + let sides = ["expandTop", "expandLeft", "expandRight", "expandBottom"]; + let cases: &[[f64; 4]] = + &[[-200.0; 4], [1000.0; 4], [-50.0, 0.0, 0.0, -50.0], [0.0, -200.0, -200.0, 0.0], [-200.0, 1000.0, -200.0, 1000.0], [-100.0, -150.0, 50.0, -200.0]]; + for unstretch in [false, true] { + for perspective in [100.0, 40.0] { + let mut base: Vec<(&str, Value)> = pins.to_vec(); + base.push(("unstretch", Value::Bool(unstretch))); + base.push(("perspective", num(perspective))); + let size = |o: &Buf| (o.img.width, o.img.height); + let neutral = size(&run("ec.distort.ccpowerpin", &base, im.clone(), &[])); + for ex in cases { + let mut set = base.clone(); + set.extend(sides.iter().zip(ex).map(|(s, v)| (*s, num(*v)))); + let o = run("ec.distort.ccpowerpin", &set, im.clone(), &[]); + let at = format!("{ex:?} unstretch {unstretch} perspective {perspective}"); + assert_eq!(size(&o), neutral, "{at}"); + for p in &o.img.data { + assert!(p.iter().all(|c| c.is_finite()) && (0.0..=1.0).contains(&p[3]), "{at}: {p:?}"); + } + } + } + } +} + #[test] fn split_opens_a_gap() { let im = img(40, 30); diff --git a/crates/gpu/src/tests/fx_stylize.rs b/crates/gpu/src/tests/fx_stylize.rs index 8c6c7be33..b75ec5a5e 100644 --- a/crates/gpu/src/tests/fx_stylize.rs +++ b/crates/gpu/src/tests/fx_stylize.rs @@ -218,6 +218,12 @@ fn twirl_legacy_ripple_pulse_power_pin() { // Perspective below 100 %: blended toward the bilinear inverse. effect_case("ec.distort.ccpowerpin", &[("topRight", pt(80.0, -6.0)), ("bottomLeft", pt(-4.0, 50.0)), ("perspective", n(0.0))]); effect_case("ec.distort.ccpowerpin", &[("topLeft", pt(12.0, 6.0)), ("bottomRight", pt(75.0, 30.0)), ("perspective", n(40.0)), ("expandTop", n(15.0))]); + // #3492: Expansion down to -200 flips the source rectangle; zero size at Top -50 / Bottom -50. + effect_case("ec.distort.ccpowerpin", &[("topRight", pt(80.0, -6.0)), ("expandTop", n(-200.0)), ("expandBottom", n(-100.0)), ("expandLeft", n(-150.0))]); + effect_case( + "ec.distort.ccpowerpin", + &[("bottomLeft", pt(-4.0, 50.0)), ("perspective", n(40.0)), ("expandTop", n(-50.0)), ("expandBottom", n(-50.0)), ("expandRight", n(-200.0))], + ); } #[test] From fa11f724349116ee8583e0542259349db8438fc3 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:04:45 +0530 Subject: [PATCH 13/78] #3492: note CC Power Pin's Expansion range in the parity log --- docs/effects-parity.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/effects-parity.md b/docs/effects-parity.md index b07c624f8..94e1a6c9a 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -64,6 +64,7 @@ the GPU is performance, not parity. | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | CC Power Pin: Expansion (Top, Left, Right, Bottom) takes After Effects' minimum of −200 % (hard range −200..1000; default and slider unchanged). Below −100 % an edge crosses the opposite one and the source flips (CPU and GPU) | | 2026-11-12 | minor | Parameters take After Effects' recorded valid ranges (hard range; defaults and sliders unchanged): Levels (Individual Controls) levels −10000..10000 and Gamma from 0; 4-Color Gradient Blend to 10000 and Jitter to 500 %; Change Color Hue Transform ±1800°; Noise HLS (and Auto) amounts to 1000 % and Grain Size from 0; Grid Border to 2000; Venetian Blinds Width 1..32000 and Feather to 32000; Radial Wipe Feather to 32000; Scatter Amount to 1000; Beam thicknesses to 4000; Transform Scale ±30000 %; Turbulent Displace Random Seed to 100000. A test checks every mapped parameter's range against the recorded table (CPU and GPU) | | 2026-10-19 | minor | Glow (original colours): bright pass per channel, 8 × (value − threshold + 0.061), measured against After Effects 2026 (CPU and GPU) | | 2026-10-19 | minor | Glow (colour channels): the glow covers the layer's blurred alpha, blur σ = 0.384 × radius, measured against After Effects 2026 renders (CPU and GPU) | From 1dc70637bd562d921f9eee8db5ed22633a76a253 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:05:29 +0530 Subject: [PATCH 14/78] #3466: Sharpen Amount takes After Effects' 0..4000 range The hard range was 0..500, so prop.set and the value editors clamped values After Effects accepts (its recorded valid range is 0..4000; the 0..100 slider and the default are unchanged). The engine range test now covers both ends through prop.set, undo/redo, save/reopen and projects saved with the old range, and the recorded-range guard no longer lists Sharpen as narrower. --- crates/aep/src/export/fx_defs.rs | 1 - crates/effects/src/misc.rs | 15 ++++++++++++++- crates/engine/src/tests/effect_ranges.rs | 1 + 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index 338e00fc5..3c0c3a357 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -729,7 +729,6 @@ mod tests { ("ec.obsolete.gaussianlegacy", "blurriness", 3463), ("ec.perspective.dropshadow", "softness", 3464), ("ec.blur.compound", "maximumBlur", 3465), - ("ec.blur.sharpen", "amount", 3466), ("ec.blur.radial", "amount", 3467), ("ec.blur.ccradial", "amount", 3468), ("ec.distort.turbulentdisplace", "amount", 3469), diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index 9c7131657..13167a3ba 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -794,7 +794,7 @@ pub fn specs() -> Vec { ], radial, ), - spec("ec.blur.sharpen", "Sharpen", "Blur & Sharpen", vec![p("amount", "Sharpen Amount", num(0.0), slider(0.0, 500.0, 0.0, 100.0, 0))], sharpen), + spec("ec.blur.sharpen", "Sharpen", "Blur & Sharpen", vec![p("amount", "Sharpen Amount", num(0.0), slider(0.0, 4000.0, 0.0, 100.0, 0))], sharpen), spec( "ec.blur.unsharp", "Unsharp Mask", @@ -1036,6 +1036,19 @@ mod tests { assert_ne!(row(2.0), row(2.4)); } + /// #3466: Sharpen Amount takes After Effects' valid range, 0..4000, and keeps its 0..100 + /// slider. `prop.set` and the value editors clamp to the hard range. + #[test] + fn sharpen_amount_takes_the_after_effects_range() { + let spec = crate::find("ec.blur.sharpen").unwrap(); + let ui = &spec.params.iter().find(|p| p.id == "amount").unwrap().ui; + assert!( + matches!(ui, ParamUi::Slider { min, max, slider_min, slider_max, .. } + if *min == 0.0 && *max == 4000.0 && *slider_min == 0.0 && *slider_max == 100.0), + "{ui:?}" + ); + } + #[test] fn fractional_box_blur_radius_is_continuous() { let row = |v| blurred_row("ec.blur.fastbox", "radius", v); diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index 7deaaa911..f2ad2112e 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -60,6 +60,7 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3471, "ec.distort.transform", "scaleHeight", -30000.0, 30000.0), (3471, "ec.distort.transform", "scaleWidth", -30000.0, 30000.0), (3470, "ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 0.0, 100000.0), + (3466, "ec.blur.sharpen", "amount", 0.0, 4000.0), ]; fn path(effect: &str, param: &str) -> String { From 1a4697de31ac2fc49174a92ffe0cf7fac78b40a2 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:05:37 +0530 Subject: [PATCH 15/78] #3466: test Sharpen's render at Amount 4000 At the top of the new range the CPU render stays linear in Amount (colour moves Amount / 50 of its difference from the blur) and finite on 32 bpc over-range input, and the GPU matches the CPU at 8 and 32 bpc. --- crates/effects/src/misc.rs | 30 ++++++++++++++++++++++++++++++ crates/gpu/src/tests/fx_noise.rs | 2 ++ 2 files changed, 32 insertions(+) diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index 13167a3ba..351460de7 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -1049,6 +1049,36 @@ mod tests { ); } + /// #3466: at the new top of the range the render stays linear in Amount and finite on 32 bpc + /// over-range input: colour moves away from the blur by Amount / 50 of the difference + /// (2000 → 4000 doubles it), never below 0, and alpha is untouched. + #[test] + fn sharpen_is_linear_and_finite_up_to_amount_4000() { + let mut img = edge(); + for y in 0..8 { + for x in 0..20 { + img.set(x, y, [1000.0, 1000.0, 1000.0, 1.0]); + } + } + let sharpen = |a: f64| run_fx("ec.blur.sharpen", &[("amount", num(a))], img.clone(), 0.0, EffectEnv::default()).img; + let (half, top) = (sharpen(2000.0), sharpen(4000.0)); + for y in 0..8 { + for x in 0..40 { + let (i, h, t) = (img.get(x, y), half.get(x, y), top.get(x, y)); + assert_eq!(t[3], i[3], "alpha at {x}"); + for c in 0..3 { + assert!(t[c].is_finite() && t[c] >= 0.0, "({x}, {y}): {t:?}"); + if t[c] > 0.0 && h[c] > 0.0 { + let (dh, dt) = (h[c] - i[c], t[c] - i[c]); + assert!((dt - 2.0 * dh).abs() <= 1e-3 * dt.abs().max(1.0), "({x}, {y}): {dh} {dt}"); + } + } + } + } + // The bright side of the edge moves 80 × its difference from the blur: far past 10 × the input. + assert!(top.get(19, 4)[0] > 1000.0 * 10.0, "{:?}", top.get(19, 4)); + } + #[test] fn fractional_box_blur_radius_is_continuous() { let row = |v| blurred_row("ec.blur.fastbox", "radius", v); diff --git a/crates/gpu/src/tests/fx_noise.rs b/crates/gpu/src/tests/fx_noise.rs index 006128c73..5e31e7e84 100644 --- a/crates/gpu/src/tests/fx_noise.rs +++ b/crates/gpu/src/tests/fx_noise.rs @@ -75,6 +75,8 @@ fn edge_preserving_blurs() { fn sharpen_and_unsharp_mask() { effect_case("ec.blur.sharpen", &[("amount", n(60.0))]); effect_case("ec.blur.sharpen", &[("amount", n(250.0))]); + // #3466: the top of After Effects' range (80 × the difference from the blur). + effect_case("ec.blur.sharpen", &[("amount", n(4000.0))]); effect_case("ec.blur.unsharp", &[("amount", n(120.0)), ("radius", n(4.0))]); effect_case("ec.blur.unsharp", &[("amount", n(80.0)), ("radius", n(2.5)), ("threshold", n(12.0))]); } From 6c5d0b51ec482339c4b2739e508a386ff7044bb0 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:05:37 +0530 Subject: [PATCH 16/78] #3466: note Sharpen's Amount range in the parity history --- docs/effects-parity.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/effects-parity.md b/docs/effects-parity.md index b07c624f8..d9bcfcedf 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -64,6 +64,7 @@ the GPU is performance, not parity. | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | Sharpen: Amount takes After Effects' recorded valid range, 0..4000 (was 0..500; default and the 0..100 slider unchanged). Sharpen stays linear in Amount and finite up to 4000, CPU and GPU agree there | | 2026-11-12 | minor | Parameters take After Effects' recorded valid ranges (hard range; defaults and sliders unchanged): Levels (Individual Controls) levels −10000..10000 and Gamma from 0; 4-Color Gradient Blend to 10000 and Jitter to 500 %; Change Color Hue Transform ±1800°; Noise HLS (and Auto) amounts to 1000 % and Grain Size from 0; Grid Border to 2000; Venetian Blinds Width 1..32000 and Feather to 32000; Radial Wipe Feather to 32000; Scatter Amount to 1000; Beam thicknesses to 4000; Transform Scale ±30000 %; Turbulent Displace Random Seed to 100000. A test checks every mapped parameter's range against the recorded table (CPU and GPU) | | 2026-10-19 | minor | Glow (original colours): bright pass per channel, 8 × (value − threshold + 0.061), measured against After Effects 2026 (CPU and GPU) | | 2026-10-19 | minor | Glow (colour channels): the glow covers the layer's blurred alpha, blur σ = 0.384 × radius, measured against After Effects 2026 renders (CPU and GPU) | From e83be3a08f38be21a7345e86ebdc132a44c87b98 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:05:40 +0530 Subject: [PATCH 17/78] #3486: Fractal Noise: lattice neighbours wrap past the i32 range At Sub Scaling 10 % and high Complexity an octave's lattice coordinates pass the i32 range. The cast saturates, and adding the neighbour offset overflowed (a panic in debug builds). Wrap it, as the GPU's i32 adds do. --- crates/effects/src/noise3.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/effects/src/noise3.rs b/crates/effects/src/noise3.rs index 49f200553..0533db03b 100644 --- a/crates/effects/src/noise3.rs +++ b/crates/effects/src/noise3.rs @@ -158,7 +158,8 @@ pub fn typed_noise(x: f32, y: f32, z: f32, seed: u32, noise_type: u32) -> f32 { let (ix, iy, iz) = (x0 as i32, y0 as i32, z0 as i32); let l = |a: f32, b: f32, t: f32| a + (b - a) * t; let slice = |dz: i32| -> f32 { - let c = |dx: i32, dy: i32| lattice(ix + dx, iy + dy, iz + dz, seed); + // Coordinates past the i32 range saturate; the neighbours wrap, as on the GPU (#3486). + let c = |dx: i32, dy: i32| lattice(ix.wrapping_add(dx), iy.wrapping_add(dy), iz.wrapping_add(dz), seed); match noise_type { 0 => c(0, 0), 1 => l(l(c(0, 0), c(1, 0), tx), l(c(0, 1), c(1, 1), tx), ty), @@ -483,6 +484,18 @@ mod tests { run_fx(id, vals, Image::filled(40, 24, [0.2, 0.4, 0.6, 1.0]), 0.0, EffectEnv::default()).img } + /// #3486: lattice coordinates past the i32 range (an octave's frequency at Sub Scaling 10 % and + /// high Complexity) saturate, and their neighbours wrap instead of overflowing. + #[test] + fn noise_past_the_i32_range_is_finite() { + for noise_type in [0, 1, 2, 3] { + for (x, y) in [(1e30, -1e30), (f32::MAX, f32::MIN), (3e9, 2.5e9)] { + let n = typed_noise(x, y, 1e12, 7, noise_type); + assert!(n.is_finite(), "type {noise_type} at ({x}, {y}): {n}"); + } + } + } + /// Evolution moves the noise at a constant rate: no ease in or out within a revolution. #[test] fn evolution_is_linear() { From 4b4d2730863d958b2d6f4d87f5f7b89009c44d7a Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:06:36 +0530 Subject: [PATCH 18/78] #3460: legacy Roto Brush keys hash Gaussian Blur's 0.24 Blurriness range Roto Brush Input Keys saved by 0.22-0.24 hashed each effect above the brush through its derived Debug text, UI hints included. Opening a project replaces an instance's hints with the current spec's, so widening a range would stop those keys matching and drop the frozen matte. The legacy text now puts back the slider range 0.24 shipped for parameters listed in SLIDERS_0_24, starting with Gaussian Blur's Blurriness. --- .../engine/src/analysis/frames_key/legacy.rs | 31 +++++++++++++++++-- crates/engine/src/tests/analysis_signature.rs | 15 ++++++++- 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/analysis/frames_key/legacy.rs b/crates/engine/src/analysis/frames_key/legacy.rs index 882c82d80..4b1b090a5 100644 --- a/crates/engine/src/analysis/frames_key/legacy.rs +++ b/crates/engine/src/analysis/frames_key/legacy.rs @@ -2,7 +2,7 @@ //! keyed with them. They hash derived `Debug` text, so `tests::analysis_signature` pins keys //! those releases saved: if a type change alters this text, write that part out here. -use effectcraft_project::{Footage, ItemId, ItemKind, Layer, LayerSource, Project, Uid}; +use effectcraft_project::{Footage, GroupKind, ItemId, ItemKind, Layer, LayerSource, ParamUi, Project, PropGroup, Uid}; use super::fnv; @@ -41,12 +41,39 @@ pub(crate) fn input_key_of(mut s: String, layer: &Layer, uid: Uid) -> String { if g.uid == uid { break; } - s.push_str(&format!("{g:?}")); + s.push_str(&effect_text(g)); } } format!("{:016x}", fnv(&s)) } +/// The slider ranges 0.22–0.24 gave effect parameters whose range has changed since, as +/// (effect, parameter path, [min, max, slider min, slider max], decimals). Those releases hashed +/// each effect's UI hints into the Roto Brush Input Key, and opening a project replaces an +/// instance's hints with the current ones, so [`effect_text`] puts these back. A range change +/// above a Roto Brush would otherwise drop the analysis such a key kept: add a row with it. +#[rustfmt::skip] +const SLIDERS_0_24: &[(&str, &str, [f64; 4], u8)] = &[ + ("ec.blur.gaussian", "blurriness", [0.0, 3000.0, 0.0, 50.0], 1), +]; + +/// An effect instance as 0.22–0.24 wrote it into a Roto Brush Input Key: its derived `Debug`, +/// with the [`SLIDERS_0_24`] ranges in place of today's. +pub(crate) fn effect_text(g: &PropGroup) -> String { + let GroupKind::Effect { effect } = &g.kind else { return format!("{g:?}") }; + let mut rows = SLIDERS_0_24.iter().filter(|r| r.0 == effect).peekable(); + if rows.peek().is_none() { + return format!("{g:?}"); + } + let mut g = g.clone(); + for &(_, path, [min, max, slider_min, slider_max], decimals) in rows { + if let Some(p) = g.prop_mut(path).filter(|p| matches!(p.ui, ParamUi::Slider { .. })) { + p.ui = ParamUi::Slider { min, max, slider_min, slider_max, decimals }; + } + } + format!("{g:?}") +} + /// A footage item as 0.23–0.24 wrote it into a signature (without `placed_page` before 0.23), /// with `missing` in place of the item's. pub(crate) fn footage_text(f: &Footage, missing: bool, placed_page: bool) -> String { diff --git a/crates/engine/src/tests/analysis_signature.rs b/crates/engine/src/tests/analysis_signature.rs index 045e279de..a4ab86264 100644 --- a/crates/engine/src/tests/analysis_signature.rs +++ b/crates/engine/src/tests/analysis_signature.rs @@ -5,7 +5,7 @@ use effectcraft_effects::camera_tracker::{TRACKS, TRACKS_KEY}; use effectcraft_effects::roto::{FROZEN, INPUT_KEY}; use effectcraft_effects::warp_stab::{ANALYSIS, ANALYSIS_KEY}; use effectcraft_keyframe::Value; -use effectcraft_project::{ItemId, LayerId, Project}; +use effectcraft_project::{GroupKind, ItemId, LayerId, ParamUi, Project}; use serde_json::json; use crate::Session; @@ -93,6 +93,19 @@ fn analyses_saved_by_0_24_survive_edits_that_keep_their_frames() { assert_eq!(saved(&s), before); } +/// 0.24 hashed each effect's UI hints into the Roto Brush's key, and opening a project takes the +/// current ones: the legacy text puts back Gaussian Blur's 0.24 Blurriness range (#3460). +#[test] +fn legacy_roto_keys_hash_the_0_24_blurriness_range() { + let s = open(ANALYSED_0_24); + let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap(); + let is_blur = |kind: &GroupKind| matches!(kind, GroupKind::Effect { effect } if effect == "ec.blur.gaussian"); + let blur = layer.effects().and_then(|fx| fx.groups().find(|g| is_blur(&g.kind))).expect("the fixture has a Gaussian Blur above the Roto Brush"); + let mut as_0_24 = blur.clone(); + as_0_24.get_mut("blurriness").unwrap().ui = ParamUi::Slider { min: 0.0, max: 3000.0, slider_min: 0.0, slider_max: 50.0, decimals: 1 }; + assert_eq!(crate::analysis::frames_key::legacy::effect_text(blur), format!("{as_0_24:?}")); +} + /// The text keys are made from today, written field by field (#3536). It changes only when this /// test is changed with it: a new field of a type it writes doesn't compile until it is decided /// in `analysis::frames_key`, and renaming a field or variant doesn't change it. From 8d603d9db8bd1b97a6effb0d793f33cc7d6f3c24 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:06:36 +0530 Subject: [PATCH 19/78] #3460: GPU box passes count repeated edge pixels instead of visiting them Each box-pass thread started its running sum by reading all 2r+1 pixels of its window, even past the end of the line. At Gaussian Blur's Blurriness 30000 the radius is about 15000 px, so most of those reads were the same edge pixel or zero. Sum the pixels inside the line once and add the repeated edges times their count, as the CPU pass does. Apple M5 (Metal), 4096 x 4096, three passes per axis, repeated edges: r = 15000 went from about 185 ms to 75 ms; r = 1500 is unchanged (80 ms). --- crates/gpu/src/shaders/kernels.wgsl | 18 +++++++++++++++++- crates/gpu/src/tests.rs | 21 +++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/crates/gpu/src/shaders/kernels.wgsl b/crates/gpu/src/shaders/kernels.wgsl index a123b70ca..2f52b3b48 100644 --- a/crates/gpu/src/shaders/kernels.wgsl +++ b/crates/gpu/src/shaders/kernels.wgsl @@ -289,9 +289,25 @@ fn box_pass(gid: vec3, horizontal: bool) { } let norm = 1.0 / f32(2 * r + 1); var acc = vec4(0.0); - for (var i = b0 - r; i <= b0 + r; i++) { + // The starting window, as the CPU sums it: the pixels inside the line once each, and the + // repeated edge pixels counted rather than visited (a radius far past the line, such as + // Gaussian Blur's at Blurriness 30000, would otherwise loop over it once per pixel). + let lo = b0 - r; + let hi = b0 + r; + for (var i = max(lo, 0); i <= min(hi, n - 1); i++) { acc += line_get(horizontal, line, i, n, repeat); } + if (repeat) { + let before = f32(max(-lo, 0)); + let after = f32(max(hi - (n - 1), 0)); + // A zero count adds nothing (0 * NaN would be NaN). + if (before > 0.0) { + acc += line_get(horizontal, line, 0, n, repeat) * before; + } + if (after > 0.0) { + acc += line_get(horizontal, line, n - 1, n, repeat) * after; + } + } let b1 = min(b0 + block, n); for (var i = b0; i < b1; i++) { if (horizontal) { diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 1d2782262..23e67d722 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -760,6 +760,27 @@ fn box_blur_horizontal_rows_match_cpu_beyond_256() { } } +/// #3460: a box radius far past the image (Gaussian Blur's at Blurriness 30000 is about 15000 px) +/// starts each running sum as the CPU does, the pixels inside once and the repeated edges +/// counted, so the GPU matches it along rows and columns, with and without repeated edges. +#[test] +fn box_passes_with_a_radius_far_past_the_image_match_cpu() { + let Some(g) = gpu() else { return }; + let img = pattern(5, 96, 40); + let up = g.ctx.upload_image(&img).expect("upload"); + let tol = tolerance(BitDepth::Bpc32); + for repeat in [true, false] { + let mut e = crate::context::Enc::new(&g.ctx); + let r = [15_000usize; 3]; + let out = crate::effects::box_passes(&mut e, &up, &r, &r, repeat); + let got = e.download(&out).expect("download"); + let want = effectcraft_raster::box_blur(&img, 15_000, 15_000, 3, repeat); + assert_eq!((got.width, got.height), (want.width, want.height)); + let d = diff(&want, &got, tol); + assert_eq!(d.over, 0, "repeat {repeat}: max {} at {:?} on {}", d.max, d.worst, g.ctx.name); + } +} + #[test] fn gpu_effects_match_cpu() { // Sigma 3 px and up and even radii, so the half-scale pass stays on the GPU too (#1939). From ef7dd7f3d181a66e43fb532e041d55a1b6d762da Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:06:36 +0530 Subject: [PATCH 20/78] #3460: Gaussian Blur: Blurriness takes After Effects' range 0..30000 After Effects records Blurriness as valid from 0 to 30000; the hard range was 0..3000, so prop.set and the value editors clamped 4000 to 3000. The default (0) and the 0..50 slider stay as they were. Padding stays within the effect pixel budget at the new maximum, on the CPU and the GPU. Tests: the engine round trip (prop.set, undo/redo, save/reopen, older projects) gets a row, the aep guard drops its known-narrower row, and the CPU and GPU render at 30000 is checked bounded, finite and matching. --- crates/aep/src/export/fx_defs.rs | 1 - crates/effects/src/misc.rs | 21 ++++++++++++++++++++- crates/engine/src/tests/effect_ranges.rs | 1 + crates/gpu/src/tests.rs | 8 ++++++++ docs/effects-parity.md | 1 + 5 files changed, 30 insertions(+), 2 deletions(-) diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index 338e00fc5..ee24879c6 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -720,7 +720,6 @@ mod tests { /// issue is fixed; the test fails on a row that is no longer needed. #[rustfmt::skip] const KNOWN_NARROWER: &[(&str, &str, u32)] = &[ - ("ec.blur.gaussian", "blurriness", 3460), ("ec.blur.fastbox", "radius", 3461), ("ec.blur.channel", "redBlurriness", 3462), ("ec.blur.channel", "greenBlurriness", 3462), diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index 9c7131657..11a273888 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -756,7 +756,7 @@ pub fn specs() -> Vec { "Gaussian Blur", "Blur & Sharpen", vec![ - p("blurriness", "Blurriness", num(0.0), slider(0.0, 3000.0, 0.0, 50.0, 1)), + p("blurriness", "Blurriness", num(0.0), slider(0.0, 30000.0, 0.0, 50.0, 1)), p("dimensions", "Blur Dimensions", Value::Enum(0), dims()), p("repeatEdge", "Repeat Edge Pixels", Value::Bool(false), ParamUi::Checkbox), ], @@ -1036,6 +1036,25 @@ mod tests { assert_ne!(row(2.0), row(2.4)); } + /// #3460: Blurriness goes up to After Effects' 30000. There the padding stays within the + /// effect pixel budget, every pixel stays finite, and Repeat Edge Pixels still repeats the + /// layer's edges: a layer white on the left and black on the right blurs to an even grey. + #[test] + fn gaussian_blur_at_the_highest_blurriness_is_bounded() { + for repeat in [false, true] { + let out = run_fx("ec.blur.gaussian", &[("blurriness", num(30000.0)), ("repeatEdge", Value::Bool(repeat))], edge(), 0.0, EffectEnv::default()); + let (w, h) = (out.img.width, out.img.height); + assert!(u64::from(w) * u64::from(h) <= 16_777_216, "repeat {repeat}: {w} x {h}"); + assert!(out.img.data.iter().flatten().all(|v| v.is_finite()), "repeat {repeat}"); + if repeat { + assert_eq!((w, h), (40, 8)); + for p in &out.img.data { + assert!(p[..3].iter().all(|v| (v - 0.5).abs() < 0.01) && (p[3] - 1.0).abs() < 1e-4, "{p:?}"); + } + } + } + } + #[test] fn fractional_box_blur_radius_is_continuous() { let row = |v| blurred_row("ec.blur.fastbox", "radius", v); diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index 7deaaa911..49721e136 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -60,6 +60,7 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3471, "ec.distort.transform", "scaleHeight", -30000.0, 30000.0), (3471, "ec.distort.transform", "scaleWidth", -30000.0, 30000.0), (3470, "ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 0.0, 100000.0), + (3460, "ec.blur.gaussian", "blurriness", 0.0, 30000.0), ]; fn path(effect: &str, param: &str) -> String { diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 23e67d722..d08276504 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -781,6 +781,14 @@ fn box_passes_with_a_radius_far_past_the_image_match_cpu() { } } +/// #3460: Gaussian Blur's highest Blurriness, 30000, renders the same on the GPU as on the CPU, +/// with the padding cut to the effect pixel budget and with Repeat Edge Pixels. +#[test] +fn gaussian_blur_at_the_highest_blurriness_matches_cpu() { + effect_case("ec.blur.gaussian", &[("blurriness", n(30000.0))]); + effect_case("ec.blur.gaussian", &[("blurriness", n(30000.0)), ("repeatEdge", Value::Bool(true))]); +} + #[test] fn gpu_effects_match_cpu() { // Sigma 3 px and up and even radii, so the half-scale pass stays on the GPU too (#1939). diff --git a/docs/effects-parity.md b/docs/effects-parity.md index b07c624f8..6675bc131 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -64,6 +64,7 @@ the GPU is performance, not parity. | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | Gaussian Blur: Blurriness takes After Effects' recorded valid range 0..30000 (was 0..3000; default and 0..50 slider unchanged). Padding stays within the effect pixel budget at the top of the range (CPU and GPU), and Roto Brush analyses 0.24 saved below a Gaussian Blur still match (#3460) | | 2026-11-12 | minor | Parameters take After Effects' recorded valid ranges (hard range; defaults and sliders unchanged): Levels (Individual Controls) levels −10000..10000 and Gamma from 0; 4-Color Gradient Blend to 10000 and Jitter to 500 %; Change Color Hue Transform ±1800°; Noise HLS (and Auto) amounts to 1000 % and Grain Size from 0; Grid Border to 2000; Venetian Blinds Width 1..32000 and Feather to 32000; Radial Wipe Feather to 32000; Scatter Amount to 1000; Beam thicknesses to 4000; Transform Scale ±30000 %; Turbulent Displace Random Seed to 100000. A test checks every mapped parameter's range against the recorded table (CPU and GPU) | | 2026-10-19 | minor | Glow (original colours): bright pass per channel, 8 × (value − threshold + 0.061), measured against After Effects 2026 (CPU and GPU) | | 2026-10-19 | minor | Glow (colour channels): the glow covers the layer's blurred alpha, blur σ = 0.384 × radius, measured against After Effects 2026 renders (CPU and GPU) | From 8f7896b28a269739b6b8405d246ab19406c74fa2 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:07:18 +0530 Subject: [PATCH 21/78] #3486: Fractal / Turbulent Noise: bound octave scales and scaled offsets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each octave's frequency and Perspective Offset depth are Sub Scaling to the power of the octave. Above 100 % (After Effects allows 10000) that reaches 100^±19 at Complexity 20, and Perspective Offset or Turbulence Factor times the offset overflowed to infinity and drew NaN. Both stay within 1e20 and its inverse and remain each other's inverse, so an octave's offset in lattice cells is unchanged; 10..100 never reaches the bound. The scaled offset stays within 1e36 px, past where the lattice index saturates. The CPU, fxn_fractal (from fractal_gpu) and pointwise paths share the bound; one octave_origin replaces the two copies of the origin code. --- crates/effects/src/lib.rs | 2 +- crates/effects/src/noise3.rs | 82 +++++++++++++++++++++-------- crates/gpu/src/effects.rs | 2 +- crates/gpu/src/shaders/kernels.wgsl | 7 ++- 4 files changed, 67 insertions(+), 26 deletions(-) diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 5da2035ac..7f0f9cf51 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -112,7 +112,7 @@ pub use transition::{GridWipe, place_layer}; // effectcraft-gpu fx_noise. pub use keying2::{InnerOuterPlan, inner_outer_plan}; pub use noise::remove_grain_level; -pub use noise3::{FractalGpu, NOISE_CELL, fractal_gpu}; +pub use noise3::{FractalGpu, NOISE_CELL, OCTAVE_SCALE_MAX, fractal_gpu}; pub use stylize3::{BumpLight, HexTile, bump_layer_id}; pub use textfx::{TextLayer, text_layer}; pub use time_fx::{PixelMotion, TimewarpPlan, TwStep, pmb_plan, posterized_time, time_frames, timewarp_crop, timewarp_plan}; diff --git a/crates/effects/src/noise3.rs b/crates/effects/src/noise3.rs index 0533db03b..ae76d756a 100644 --- a/crates/effects/src/noise3.rs +++ b/crates/effects/src/noise3.rs @@ -65,6 +65,27 @@ pub const NOISE_SOFT_LINEAR: u32 = 2; /// correlation length), not 100 px. pub const NOISE_CELL: f64 = 2.0 / 3.0; +/// Bound on an octave's frequency and on its Perspective Offset depth (and their inverses). +/// Unbounded, at Sub Scaling 10000 and Complexity 20 they would reach 100^±19, and Perspective +/// Offset or Turbulence Factor multiplying the offset by the depth overflowed to infinity (NaN +/// noise, #3486). Sub Scaling 10..100 never reaches the bound (10^19 at most). Both stay each +/// other's inverse inside it, so an octave's offset in lattice cells is unchanged; an octave this +/// far out is a constant (or sub-pixel noise) across any layer either way. +pub const OCTAVE_SCALE_MAX: f32 = 1e20; + +/// Bound on an octave's scaled Offset Turbulence in pixels, so a huge offset times the depth stays +/// finite. Times a frequency of at least 1 / [`OCTAVE_SCALE_MAX`], over cells of at most about +/// 6700 px (Scale 10000 %), it is still over 10^12 lattice cells, past where the lattice index +/// saturates (2^31), so the output is the same. +const OCTAVE_OFFSET_MAX: f32 = 1e36; + +/// The next octave's (frequency, depth) from this one's, for a Sub Scaling ratio `s`. +#[inline] +fn next_octave(f: f32, depth: f32, s: f32) -> (f32, f32) { + let lo = 1.0 / OCTAVE_SCALE_MAX; + ((f / s).clamp(lo, OCTAVE_SCALE_MAX), (depth * s).clamp(lo, OCTAVE_SCALE_MAX)) +} + fn spec(id: &'static str, name: &'static str, params: Vec, render: crate::RenderFn) -> EffectSpec { EffectSpec { id, name, category: "Noise & Grain", params, render, gpu: false, float: true } } @@ -275,6 +296,23 @@ impl Fractal { } } + /// Octave `of`'s origin in pixels, at Perspective Offset `depth`: Perspective Offset moves finer + /// (farther) layers less; turbulence makes them drift faster. The scaled offset stays within + /// ±[`OCTAVE_OFFSET_MAX`] (#3486). + #[inline] + fn octave_origin(&self, of: f32, depth: f32) -> [f32; 2] { + let k = if self.perspective { depth } else { 1.0 } * (1.0 + self.turbulence * of); + let mut org = self.origin; + if k != 1.0 { + let d = |i: usize| ((self.origin[i] - self.center[i]) * k).clamp(-OCTAVE_OFFSET_MAX, OCTAVE_OFFSET_MAX); + org = [self.center[0] + d(0), self.center[1] + d(1)]; + } + if !self.center_subscale { + org = [org[0] + self.sub_offset[0] * of, org[1] + self.sub_offset[1] * of]; + } + org + } + /// Raw fractal value (before contrast / overflow) at pixel centre (x, y). pub(crate) fn raw(&self, x: f32, y: f32) -> f32 { let n_oct = self.octaves.ceil() as usize; @@ -285,16 +323,7 @@ impl Fractal { for o in 0..n_oct { let w = if o + 1 == n_oct && frac > 0.0 { frac } else { 1.0 }; let of = o as f32; - // This layer's origin: Perspective Offset moves finer (farther) layers less; - // turbulence makes them drift faster. - let k = if self.perspective { depth } else { 1.0 } * (1.0 + self.turbulence * of); - let mut org = self.origin; - if k != 1.0 { - org = [self.center[0] + (self.origin[0] - self.center[0]) * k, self.center[1] + (self.origin[1] - self.center[1]) * k]; - } - if !self.center_subscale { - org = [org[0] + self.sub_offset[0] * of, org[1] + self.sub_offset[1] * of]; - } + let org = self.octave_origin(of, depth); let (dx, dy) = (x - org[0], y - org[1]); let (mut u, mut v) = ((dx * cr + dy * sr) / self.size[0], (-dx * sr + dy * cr) / self.size[1]); if self.sub_rotation != 0.0 { @@ -324,8 +353,7 @@ impl Fractal { sum += n * amp * w; norm += amp * w; amp *= self.influence; - f /= self.sub_scaling; - depth *= self.sub_scaling; + (f, depth) = next_octave(f, depth, self.sub_scaling); } if self.kind == 7 { best } else { sum / norm.max(1e-6) } } @@ -377,22 +405,14 @@ pub fn fractal_gpu(ctx: &EffectCtx, offset: [f64; 2], scale: f64, turbulent: boo for o in 0..n_oct { let w = if o + 1 == n_oct && frac > 0.0 { frac } else { 1.0 }; let of = o as f32; - let k = if fr.perspective { depth } else { 1.0 } * (1.0 + fr.turbulence * of); - let mut org = fr.origin; - if k != 1.0 { - org = [fr.center[0] + (fr.origin[0] - fr.center[0]) * k, fr.center[1] + (fr.origin[1] - fr.center[1]) * k]; - } - if !fr.center_subscale { - org = [org[0] + fr.sub_offset[0] * of, org[1] + fr.sub_offset[1] * of]; - } + let org = fr.octave_origin(of, depth); let (s, c) = (fr.sub_rotation * of).sin_cos(); let evo = fr.evolution * (1.0 + fr.turbulence * of); let dk = if fr.kind == 6 { 0.5 + of * 0.35 } else { 1.0 }; octaves.push([org[0], org[1], s, c, f, amp, w, evo, of * 7.31, dk]); norm += amp * w; amp *= fr.influence; - f /= fr.sub_scaling; - depth *= fr.sub_scaling; + (f, depth) = next_octave(f, depth, fr.sub_scaling); } let cycle = fr.cycle.map(|c| { let t = fr.evolution.rem_euclid(c); @@ -496,6 +516,24 @@ mod tests { } } + /// #3486: octave frequency and depth stay each other's inverse and finite at 20 octaves of + /// either end of Sub Scaling, and are unchanged inside the old 10..100 range. + #[test] + fn octave_scales_stay_finite_and_inverse() { + for s in [0.1f32, 0.56, 1.0, 2.0, 100.0] { + let (mut f, mut depth, (mut f0, mut d0)) = (1.0f32, 1.0f32, (1.0f32, 1.0f32)); + for _ in 0..19 { + (f, depth) = next_octave(f, depth, s); + (f0, d0) = (f0 / s, d0 * s); + assert!(f.is_finite() && depth.is_finite() && f > 0.0 && depth > 0.0, "{s}: {f} {depth}"); + assert!((f * depth - 1.0).abs() < 1e-3, "{s}: {f} × {depth}"); + if s <= 1.0 { + assert_eq!((f, depth), (f0, d0), "{s}"); + } + } + } + } + /// Evolution moves the noise at a constant rate: no ease in or out within a revolution. #[test] fn evolution_is_linear() { diff --git a/crates/gpu/src/effects.rs b/crates/gpu/src/effects.rs index fd5a97c38..5f204d1c4 100644 --- a/crates/gpu/src/effects.rs +++ b/crates/gpu/src/effects.rs @@ -608,7 +608,7 @@ fn pointwise(e: &mut Enc, id: &str, ctx: &EffectCtx, b: GBuf) -> Option { (f("opacity") as f32 / 100.0).clamp(0.0, 1.0), (sh * effectcraft_effects::NOISE_CELL * b.scale).max(1.0) as f32, ]; - p.f[3] = [(f("subSettings/subInfluence") as f32 / 100.0).clamp(0.0, 1.0), 1.0 / sub as f32, 0.0, 0.0]; + p.f[3] = [(f("subSettings/subInfluence") as f32 / 100.0).clamp(0.0, 1.0), 1.0 / sub as f32, effectcraft_effects::OCTAVE_SCALE_MAX, 0.0]; } _ => return None, } diff --git a/crates/gpu/src/shaders/kernels.wgsl b/crates/gpu/src/shaders/kernels.wgsl index a123b70ca..e038a9ee8 100644 --- a/crates/gpu/src/shaders/kernels.wgsl +++ b/crates/gpu/src/shaders/kernels.wgsl @@ -618,7 +618,8 @@ fn straight(px: vec4) -> vec3 { // 9 Gradient Ramp f[0] = (sx, sy, ex, ey); f[1] = start colour; f[2] = end colour; // f[3] = (len2, scatter, blend); u[0] = (_, radial, seed) // 10 Fractal Noise f[0] = (contrast, brightness, scale x, frac); f[1] = (ox, oy, sr, cr); -// f[2] = (evo, blend, opacity, scale y); f[3] = (sub influence, 1 / sub scaling); +// f[2] = (evo, blend, opacity, scale y); f[3] = (sub influence, 1 / sub scaling, +// OCTAVE_SCALE_MAX); // u[0] = (_, kind, n_oct, seed); u[1] = (invert, overflow, normal blend) @compute @workgroup_size(16, 16) fn pointwise(@builtin(global_invocation_id) gid: vec3) { @@ -856,6 +857,7 @@ fn pointwise(@builtin(global_invocation_id) gid: vec3) { let scale_y = P.f[2].w; let infl = P.f[3].x; let fmul = P.f[3].y; + let fmax = P.f[3].z; let frac = P.f[0].w; let ox = P.f[1].x; let oy = P.f[1].y; @@ -888,7 +890,8 @@ fn pointwise(@builtin(global_invocation_id) gid: vec3) { sum += n * amp * w; norm += amp * w; amp *= infl; - f *= fmul; + // noise3::next_octave: the frequency stays within OCTAVE_SCALE_MAX (#3486). + f = clamp(f * fmul, 1.0 / fmax, fmax); } var val = sum / max(norm, 1e-6); val = (val - 0.5) * contrast + 0.5 + brightness; From d918aa6e13bf6a89e81d974f20a85826540ece54 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:09:29 +0530 Subject: [PATCH 22/78] #3467: Radial Blur Amount takes After Effects' range 0..1000 After Effects records 0..1000 for Radial Blur's Amount (slider 0..100); EffectCraft's hard range stopped at 100, so prop.set and the value editors clamped 200 to 100. The hard maximum is now 1000; the slider range and default are unchanged. The engine range test covers prop.set at both ends, undo and redo, save and reopen, and a project saved with the old range. The parameter leaves the .aep range guard's list of known narrower ranges. --- crates/aep/src/export/fx_defs.rs | 1 - crates/effects/src/misc.rs | 27 +++++++++++++++++++++++- crates/engine/src/tests/effect_ranges.rs | 1 + 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index 338e00fc5..fb83eed8a 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -730,7 +730,6 @@ mod tests { ("ec.perspective.dropshadow", "softness", 3464), ("ec.blur.compound", "maximumBlur", 3465), ("ec.blur.sharpen", "amount", 3466), - ("ec.blur.radial", "amount", 3467), ("ec.blur.ccradial", "amount", 3468), ("ec.distort.turbulentdisplace", "amount", 3469), ("ec.time.pixelmotionblur", "shutterAngle", 3481), diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index 9c7131657..168dd6110 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -786,7 +786,8 @@ pub fn specs() -> Vec { "Radial Blur", "Blur & Sharpen", vec![ - p("amount", "Amount", num(10.0), slider(0.0, 100.0, 0.0, 100.0, 1)), + // After Effects accepts 0..1000; its slider shows 0..100 (#3467). + p("amount", "Amount", num(10.0), slider(0.0, 1000.0, 0.0, 100.0, 1)), p("center", "Center", Value::Vec2([0.5, 0.5]), ParamUi::Point), p("type", "Type", Value::Enum(0), popup(&["Spin", "Zoom"])), // Our blur is always fully anti-aliased; the choice is kept for compatibility. @@ -1147,6 +1148,30 @@ mod tests { } } + /// Spin and Zoom at both ends of Amount (0..1000) and both Antialiasing settings give finite + /// colours over an opaque layer and keep it opaque (#3467). + #[test] + fn radial_blur_is_finite_across_the_amount_range() { + let mut img = effectcraft_raster::Image::new(48, 40); + img.rows_mut().for_each(|(y, row)| { + for (x, px) in row.iter_mut().enumerate() { + *px = [x as f32 / 47.0, y as f32 / 39.0, 0.5, 1.0]; + } + }); + for ty in 0..2 { + for aa in 0..2 { + for amount in [0.0, 100.0, 200.0, 1000.0] { + let vals = [("amount", num(amount)), ("type", Value::Enum(ty)), ("center", Value::Vec2([10.0, 30.0])), ("antialiasing", Value::Enum(aa))]; + let o = run_fx("ec.blur.radial", &vals, img.clone(), 0.0, EffectEnv::default()); + assert_eq!((o.img.width, o.img.height), (48, 40)); + for p in &o.img.data { + assert!(p.iter().all(|v| v.is_finite()) && (p[3] - 1.0).abs() < 1e-5, "type {ty} aa {aa} amount {amount}: {p:?}"); + } + } + } + } + } + /// After Effects 2026, Venetian Blinds Completion 40, Direction 30, Width 50, Feather 5 on /// an opaque 480 × 270 layer: alpha (0..255) along row y = 135. The transparent band starts /// at the layer centre's phase, both edges are Gaussian (σ = Feather / 2). diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index 7deaaa911..6cc457888 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -60,6 +60,7 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3471, "ec.distort.transform", "scaleHeight", -30000.0, 30000.0), (3471, "ec.distort.transform", "scaleWidth", -30000.0, 30000.0), (3470, "ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 0.0, 100000.0), + (3467, "ec.blur.radial", "amount", 0.0, 1000.0), ]; fn path(effect: &str, param: &str) -> String { From 12480ab94ece38b1a6dcfcd8937af384bcc1f610 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:09:32 +0530 Subject: [PATCH 23/78] #3492: say when crossed Expansion sides flip the CC Power Pin source The source rectangle flips when two opposite sides add up to less than -100 %, not when one side alone does. --- crates/effects/src/distort3/tests.rs | 10 +++++----- crates/gpu/src/tests/fx_stylize.rs | 3 ++- docs/effects-parity.md | 2 +- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/crates/effects/src/distort3/tests.rs b/crates/effects/src/distort3/tests.rs index cea83cfd2..8ccc80ad4 100644 --- a/crates/effects/src/distort3/tests.rs +++ b/crates/effects/src/distort3/tests.rs @@ -251,12 +251,12 @@ fn power_pin_unstretch_expands_pinned_region() { } /// #3492: an Expansion side moves that edge of the source rectangle by a percent of the layer -/// size. Below -100 % it crosses the opposite edge, so the rectangle flips: Top -200 and Bottom -/// -100 take rows 40 down to 0 of a 20-row layer, a mirrored copy squeezed into the bottom half -/// (the top half samples below the layer and is transparent). -100 for both would mirror the -/// whole layer. +/// size. When two opposite sides add up to less than -100 % the edges cross and the rectangle +/// flips: Top -200 and Bottom -100 take rows 40 down to 0 of a 20-row layer, a mirrored copy +/// squeezed into the bottom half (the top half samples below the layer and is transparent). +/// -100 for both (the most the old minimum allowed) mirrors the whole layer. #[test] -fn power_pin_expansion_below_minus_100_flips_the_source() { +fn power_pin_crossed_expansion_flips_the_source() { let im = img(20, 20); let o = run("ec.distort.ccpowerpin", &[("expandTop", num(-200.0)), ("expandBottom", num(-100.0))], im.clone(), &[]); assert_eq!((o.img.width, o.img.height), (20, 20)); diff --git a/crates/gpu/src/tests/fx_stylize.rs b/crates/gpu/src/tests/fx_stylize.rs index b75ec5a5e..108dfca53 100644 --- a/crates/gpu/src/tests/fx_stylize.rs +++ b/crates/gpu/src/tests/fx_stylize.rs @@ -218,7 +218,8 @@ fn twirl_legacy_ripple_pulse_power_pin() { // Perspective below 100 %: blended toward the bilinear inverse. effect_case("ec.distort.ccpowerpin", &[("topRight", pt(80.0, -6.0)), ("bottomLeft", pt(-4.0, 50.0)), ("perspective", n(0.0))]); effect_case("ec.distort.ccpowerpin", &[("topLeft", pt(12.0, 6.0)), ("bottomRight", pt(75.0, 30.0)), ("perspective", n(40.0)), ("expandTop", n(15.0))]); - // #3492: Expansion down to -200 flips the source rectangle; zero size at Top -50 / Bottom -50. + // #3492: Expansion down to -200; opposite sides adding up to less than -100 % flip the source, + // and Top -50 / Bottom -50 leave it zero high. effect_case("ec.distort.ccpowerpin", &[("topRight", pt(80.0, -6.0)), ("expandTop", n(-200.0)), ("expandBottom", n(-100.0)), ("expandLeft", n(-150.0))]); effect_case( "ec.distort.ccpowerpin", diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 94e1a6c9a..333511fc0 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -64,7 +64,7 @@ the GPU is performance, not parity. | Date | Change | Summary | |---|---|---| -| 2026-11-17 | minor | CC Power Pin: Expansion (Top, Left, Right, Bottom) takes After Effects' minimum of −200 % (hard range −200..1000; default and slider unchanged). Below −100 % an edge crosses the opposite one and the source flips (CPU and GPU) | +| 2026-11-17 | minor | CC Power Pin: Expansion (Top, Left, Right, Bottom) takes After Effects' minimum of −200 % (hard range −200..1000; defaults and sliders unchanged). When two opposite sides add up to less than −100 % the source rectangle flips (CPU and GPU) | | 2026-11-12 | minor | Parameters take After Effects' recorded valid ranges (hard range; defaults and sliders unchanged): Levels (Individual Controls) levels −10000..10000 and Gamma from 0; 4-Color Gradient Blend to 10000 and Jitter to 500 %; Change Color Hue Transform ±1800°; Noise HLS (and Auto) amounts to 1000 % and Grain Size from 0; Grid Border to 2000; Venetian Blinds Width 1..32000 and Feather to 32000; Radial Wipe Feather to 32000; Scatter Amount to 1000; Beam thicknesses to 4000; Transform Scale ±30000 %; Turbulent Displace Random Seed to 100000. A test checks every mapped parameter's range against the recorded table (CPU and GPU) | | 2026-10-19 | minor | Glow (original colours): bright pass per channel, 8 × (value − threshold + 0.061), measured against After Effects 2026 (CPU and GPU) | | 2026-10-19 | minor | Glow (colour channels): the glow covers the layer's blurred alpha, blur σ = 0.384 × radius, measured against After Effects 2026 renders (CPU and GPU) | From f98c3e9ba2da86ced94a34f7c9bf1a1fe7489d33 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:09:38 +0530 Subject: [PATCH 24/78] #3467: Radial Blur Zoom past 200 stays on its side of the centre MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Zoom spreads its 32 samples over scales 1 ± Amount / 200 about the centre. Past Amount 200, which the range now allows, that reaches below 0 and samples the layer mirrored through the centre: at 1000 a layer white on the left and black on the right turned the right half 35 % grey. raster::radial_blur_zoom_scale keeps the old scales up to 200 exactly and spreads the samples evenly from the centre to 1 + Amount / 200 beyond. The CPU and GPU paths both take their samples from it. Work per pixel stays at 32 samples at any Amount. --- crates/effects/src/misc.rs | 20 +++++++++++ crates/gpu/src/fx_generate.rs | 8 ++--- crates/gpu/src/tests/fx_generate.rs | 3 ++ crates/raster/src/blur.rs | 53 ++++++++++++++++++++++++++--- crates/raster/src/lib.rs | 5 ++- docs/effects-parity.md | 1 + 6 files changed, 81 insertions(+), 9 deletions(-) diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index 168dd6110..ea196fc11 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -1148,6 +1148,26 @@ mod tests { } } + /// Amount takes After Effects' valid range up to 1000 (#3467), Zoom 1000 a spread of 10. + /// Zoom samples along the ray from the centre through the pixel, never past the centre: on a + /// layer white left of the centre and black right of it, the right half stays black (scales + /// below 0 sampled the white half mirrored through the centre). Both Antialiasing settings. + #[test] + fn radial_blur_zoom_at_the_largest_amount_stays_on_its_side_of_the_centre() { + let mut img = effectcraft_raster::Image::filled(64, 32, [0.0, 0.0, 0.0, 1.0]); + img.rows_mut().for_each(|(_, row)| row.iter_mut().take(32).for_each(|px| *px = [1.0, 1.0, 1.0, 1.0])); + for aa in 0..2 { + let vals = [("amount", num(1000.0)), ("type", Value::Enum(1)), ("center", Value::Vec2([32.5, 16.5])), ("antialiasing", Value::Enum(aa))]; + let o = run_fx("ec.blur.radial", &vals, img.clone(), 0.0, EffectEnv::default()); + for y in 0..32 { + for x in 33..64 { + let p = o.img.get(x, y); + assert!(p[0].abs() < 1e-5 && (p[3] - 1.0).abs() < 1e-5, "aa {aa} ({x}, {y}): {p:?}"); + } + } + } + } + /// Spin and Zoom at both ends of Amount (0..1000) and both Antialiasing settings give finite /// colours over an opaque layer and keep it opaque (#3467). #[test] diff --git a/crates/gpu/src/fx_generate.rs b/crates/gpu/src/fx_generate.rs index 2dda38f45..6e9594f60 100644 --- a/crates/gpu/src/fx_generate.rs +++ b/crates/gpu/src/fx_generate.rs @@ -100,14 +100,14 @@ fn radial_blur(e: &mut Enc, ctx: &EffectCtx, b: GBuf) -> Option { if amount.abs() < 1e-6 { return Some(b); } - let n = 32usize; + // The CPU's samples (`raster::radial_blur`). + let n = effectcraft_raster::RADIAL_BLUR_SAMPLES; let mut data = Vec::with_capacity(2 * n); for i in 0..n { - let t = i as f64 / (n - 1) as f64 - 0.5; if zoom { - data.push((1.0 + t * amount) as f32); + data.push(effectcraft_raster::radial_blur_zoom_scale(i, amount) as f32); } else { - let (s, c) = (t * amount).to_radians().sin_cos(); + let (s, c) = effectcraft_raster::radial_blur_spin_angle(i, amount).to_radians().sin_cos(); data.extend([s as f32, c as f32]); } } diff --git a/crates/gpu/src/tests/fx_generate.rs b/crates/gpu/src/tests/fx_generate.rs index f8482b5ab..02ec75b11 100644 --- a/crates/gpu/src/tests/fx_generate.rs +++ b/crates/gpu/src/tests/fx_generate.rs @@ -24,6 +24,9 @@ fn radial_blur() { effect_case("ec.blur.radial", &[("amount", n(12.0))]); effect_case("ec.blur.radial", &[("amount", n(30.0)), ("type", e(1)), ("center", pt(20.3, 14.7))]); effect_case("ec.blur.radial", &[("amount", n(-45.0)), ("center", pt(50.0, 30.0))]); + // Amount's largest value, 1000 (#3467): Spin over ±500°, Zoom from the centre outwards. + effect_case("ec.blur.radial", &[("amount", n(1000.0)), ("center", pt(20.3, 14.7))]); + effect_case("ec.blur.radial", &[("amount", n(1000.0)), ("type", e(1)), ("center", pt(20.3, 14.7)), ("antialiasing", e(1))]); } #[test] diff --git a/crates/raster/src/blur.rs b/crates/raster/src/blur.rs index 76e51f865..751e0f5d0 100644 --- a/crates/raster/src/blur.rs +++ b/crates/raster/src/blur.rs @@ -300,24 +300,49 @@ pub fn directional_blur(img: &Image, angle_deg: f64, length: f64) -> Image { out } +/// Samples [`radial_blur`] averages per pixel at every amount, so the work per pixel stays the +/// same up to Radial Blur's largest Amount (1000). The GPU path takes the same count. +pub const RADIAL_BLUR_SAMPLES: usize = 32; + +/// Where sample `i` of [`RADIAL_BLUR_SAMPLES`] lies in the blur's spread, from −0.5 to 0.5. +fn radial_blur_t(i: usize) -> f64 { + i as f64 / (RADIAL_BLUR_SAMPLES - 1) as f64 - 0.5 +} + +/// Spin sample `i`'s rotation in degrees for a spin of `amount` degrees. +pub fn radial_blur_spin_angle(i: usize, amount: f64) -> f64 { + radial_blur_t(i) * amount +} + +/// Zoom sample `i`'s scale about the centre for a zoom of `amount` (a fraction of the distance +/// to the centre): evenly over `1 ± amount / 2`. Past a spread of 2 (Radial Blur's Amount 200) +/// that would reach below 0 and sample the point mirrored through the centre, so the samples +/// spread evenly from the centre (0) to `1 + amount / 2` instead (#3467). +pub fn radial_blur_zoom_scale(i: usize, amount: f64) -> f64 { + let t = radial_blur_t(i); + if amount.abs() <= 2.0 { + return 1.0 + t * amount; + } + (t + 0.5) * (1.0 + amount.abs() / 2.0) +} + /// Radial blur around `center`: `spin` (degrees) or zoom (`amount` as a fraction of distance). pub fn radial_blur(img: &Image, center: (f64, f64), amount: f64, zoom: bool) -> Image { if amount.abs() < 1e-6 { return img.clone(); } - let n = 32usize; + let n = RADIAL_BLUR_SAMPLES; let mut out = Image::new(img.width, img.height); out.rows_mut().for_each(|(y, row)| { for (x, px) in row.iter_mut().enumerate() { let (vx, vy) = (x as f64 + 0.5 - center.0, y as f64 + 0.5 - center.1); let mut acc = [0.0f32; 4]; for i in 0..n { - let t = i as f64 / (n - 1) as f64 - 0.5; let (sx, sy) = if zoom { - let k = 1.0 + t * amount; + let k = radial_blur_zoom_scale(i, amount); (center.0 + vx * k, center.1 + vy * k) } else { - let (s, c) = (t * amount).to_radians().sin_cos(); + let (s, c) = radial_blur_spin_angle(i, amount).to_radians().sin_cos(); (center.0 + vx * c - vy * s, center.1 + vx * s + vy * c) }; // Samples outside the image repeat its edge: After Effects' Radial Blur keeps a @@ -337,6 +362,26 @@ pub fn radial_blur(img: &Image, center: (f64, f64), amount: f64, zoom: bool) -> mod tests { use super::*; + /// Zoom spreads up to 2 keep `1 ± spread / 2` exactly as before (#3467); wider ones run + /// from the centre (scale 0) out to `1 + spread / 2`, evenly and never below 0. + #[test] + fn radial_blur_zoom_scales_never_cross_the_centre() { + let n = RADIAL_BLUR_SAMPLES; + for amount in [0.2, 1.0, 2.0, -1.5] { + for i in 0..n { + let t = i as f64 / (n - 1) as f64 - 0.5; + assert_eq!(radial_blur_zoom_scale(i, amount), 1.0 + t * amount, "amount {amount} sample {i}"); + } + } + for amount in [2.5, 10.0, -10.0] { + let k: Vec = (0..n).map(|i| radial_blur_zoom_scale(i, amount)).collect(); + assert_eq!(k[0], 0.0, "amount {amount}"); + assert!((k[n - 1] - (1.0 + amount.abs() / 2.0)).abs() < 1e-12, "amount {amount}: {k:?}"); + let step = k[n - 1] / (n - 1) as f64; + assert!(k.windows(2).all(|w| (w[1] - w[0] - step).abs() < 1e-12), "amount {amount}: {k:?}"); + } + } + /// The sampled Gaussian pass as it was (one pixel at a time, bounds-checked taps): the /// row-wise passes must match it to the bit. fn gauss_pass_per_pixel(img: &Image, sigma: f64, vertical: bool, repeat: bool) -> Image { diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index e18a24c63..852065db4 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -17,7 +17,10 @@ pub mod yuv; use effectcraft_color::{BlendMode, blend_pixel}; use rayon::prelude::*; -pub use blur::{box_blur, directional_blur, gaussian_blur, gaussian_blur_exact, gaussian_is_exact, radial_blur}; +pub use blur::{ + RADIAL_BLUR_SAMPLES, box_blur, directional_blur, gaussian_blur, gaussian_blur_exact, gaussian_is_exact, radial_blur, radial_blur_spin_angle, + radial_blur_zoom_scale, +}; pub use channels3d::AuxChannels; pub use warp::{Sampling, WarpOpts, accumulate_warp, composite_warp, composite_warp_changed, composite_warp_reference, resample}; diff --git a/docs/effects-parity.md b/docs/effects-parity.md index b07c624f8..9d6ca232f 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -64,6 +64,7 @@ the GPU is performance, not parity. | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | Radial Blur: Amount takes After Effects' valid range 0..1000 (slider and default unchanged); Zoom past 200 spreads its samples from the centre outwards instead of sampling the layer mirrored through the centre (CPU and GPU) | | 2026-11-12 | minor | Parameters take After Effects' recorded valid ranges (hard range; defaults and sliders unchanged): Levels (Individual Controls) levels −10000..10000 and Gamma from 0; 4-Color Gradient Blend to 10000 and Jitter to 500 %; Change Color Hue Transform ±1800°; Noise HLS (and Auto) amounts to 1000 % and Grain Size from 0; Grid Border to 2000; Venetian Blinds Width 1..32000 and Feather to 32000; Radial Wipe Feather to 32000; Scatter Amount to 1000; Beam thicknesses to 4000; Transform Scale ±30000 %; Turbulent Displace Random Seed to 100000. A test checks every mapped parameter's range against the recorded table (CPU and GPU) | | 2026-10-19 | minor | Glow (original colours): bright pass per channel, 8 × (value − threshold + 0.061), measured against After Effects 2026 (CPU and GPU) | | 2026-10-19 | minor | Glow (colour channels): the glow covers the layer's blurred alpha, blur σ = 0.384 × radius, measured against After Effects 2026 renders (CPU and GPU) | From ec1294a1d28f38574d0d44b480aa8846c8114b7d Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:10:16 +0530 Subject: [PATCH 25/78] #3486: Fractal Noise: Sub Scaling takes After Effects' 10..10000 After Effects records Sub Scaling's valid range as 10..10000 (slider 25..100), but the hard range stopped at 100, so prop.set and the value editors clamped 200 to 100. The CPU renderer and the GPU pointwise path also capped the ratio at 1, so a value above 100 rendered as 100 even once stored. Widen the hard range for Fractal and Turbulent Noise (they share the parameter; slider and default unchanged) and take the ratio from one sub_scaling_ratio (0.1..100) on the CPU and both GPU paths. Above 100 each octave is larger than the last. Tests: the range and that 200 and 10000 render differently from 100; finite output at both ends with Complexity 20, Perspective Offset, Turbulence Factor 10 and a huge offset; CPU/GPU parity at 200 and 10000 on the pointwise and fxn_fractal paths; prop.set, undo/redo and save/reopen keep 10 and 10000 (engine range table). The .aep range guard no longer lists the parameter. --- crates/aep/src/export/fx_defs.rs | 1 - crates/effects/src/lib.rs | 2 +- crates/effects/src/noise3.rs | 57 ++++++++++++++++++++++-- crates/engine/src/tests/effect_ranges.rs | 2 + crates/gpu/src/effects.rs | 2 +- crates/gpu/src/tests/fx_noise.rs | 18 ++++++++ docs/effects-parity.md | 1 + 7 files changed, 77 insertions(+), 6 deletions(-) diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index 338e00fc5..fa2047739 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -736,7 +736,6 @@ mod tests { ("ec.time.pixelmotionblur", "shutterAngle", 3481), ("ec.time.pixelmotionblur", "shutterSamples", 3482), ("ec.noise.fractal", "subSettings/subInfluence", 3485), - ("ec.noise.fractal", "subSettings/subScaling", 3486), ("ec.distort.ccpowerpin", "expandTop", 3492), ("ec.distort.ccpowerpin", "expandLeft", 3492), ("ec.distort.ccpowerpin", "expandRight", 3492), diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 7f0f9cf51..155755dea 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -112,7 +112,7 @@ pub use transition::{GridWipe, place_layer}; // effectcraft-gpu fx_noise. pub use keying2::{InnerOuterPlan, inner_outer_plan}; pub use noise::remove_grain_level; -pub use noise3::{FractalGpu, NOISE_CELL, OCTAVE_SCALE_MAX, fractal_gpu}; +pub use noise3::{FractalGpu, NOISE_CELL, OCTAVE_SCALE_MAX, fractal_gpu, sub_scaling_ratio}; pub use stylize3::{BumpLight, HexTile, bump_layer_id}; pub use textfx::{TextLayer, text_layer}; pub use time_fx::{PixelMotion, TimewarpPlan, TwStep, pmb_plan, posterized_time, time_frames, timewarp_crop, timewarp_plan}; diff --git a/crates/effects/src/noise3.rs b/crates/effects/src/noise3.rs index ae76d756a..c12ebaa1c 100644 --- a/crates/effects/src/noise3.rs +++ b/crates/effects/src/noise3.rs @@ -65,6 +65,12 @@ pub const NOISE_SOFT_LINEAR: u32 = 2; /// correlation length), not 100 px. pub const NOISE_CELL: f64 = 2.0 / 3.0; +/// Sub Scaling (percent, After Effects' valid 10..10000) as the size ratio of each octave to the +/// one before it. Above 1 each octave is larger than the last. +pub fn sub_scaling_ratio(percent: f64) -> f64 { + (percent / 100.0).clamp(0.1, 100.0) +} + /// Bound on an octave's frequency and on its Perspective Offset depth (and their inverses). /// Unbounded, at Sub Scaling 10000 and Complexity 20 they would reach 100^±19, and Perspective /// Offset or Turbulence Factor multiplying the offset by the depth overflowed to infinity (NaN @@ -109,7 +115,7 @@ fn params(turbulent: bool) -> Vec { p("transform/perspectiveOffset", "Perspective Offset", Value::Bool(false), ParamUi::Checkbox), p("complexity", "Complexity", num(6.0), slider(1.0, 20.0, 1.0, 10.0, 1)), p("subSettings/subInfluence", "Sub Influence (%)", num(70.0), slider(0.0, 100.0, 25.0, 100.0, 1)), - p("subSettings/subScaling", "Sub Scaling", num(56.0), slider(10.0, 100.0, 25.0, 100.0, 1)), + p("subSettings/subScaling", "Sub Scaling", num(56.0), slider(10.0, 10000.0, 25.0, 100.0, 1)), ]; if !turbulent { v.extend([ @@ -217,7 +223,8 @@ pub(crate) struct Fractal { pub perspective: bool, pub octaves: f32, pub influence: f32, - /// Sub Scaling as a fraction (each layer is this much smaller). + /// Sub Scaling as a size ratio ([`sub_scaling_ratio`]: each octave is this much the size of the + /// one before). pub sub_scaling: f32, pub sub_rotation: f32, /// Sub Offset in pixels. @@ -269,7 +276,7 @@ impl Fractal { perspective: pr.b("transform/perspectiveOffset"), octaves: pr.f("complexity").clamp(1.0, 20.0) as f32, influence: (pr.f("subSettings/subInfluence") as f32 / 100.0).clamp(0.0, 1.0), - sub_scaling: (pr.f("subSettings/subScaling") as f32 / 100.0).clamp(0.1, 1.0), + sub_scaling: sub_scaling_ratio(pr.f("subSettings/subScaling")) as f32, sub_rotation: (pr.f("subSettings/subRotation") as f32).to_radians(), sub_offset: [(so[0] * b.scale) as f32, (so[1] * b.scale) as f32], center_subscale: pr.b("subSettings/centerSubscale"), @@ -709,6 +716,50 @@ mod tests { assert_ne!(t0, t1); } + /// #3486: Sub Scaling takes After Effects' 10..10000 for both effects (the slider still shows + /// 25..100), and the renderer uses values above 100 instead of capping them there. + #[test] + fn sub_scaling_takes_the_after_effects_range() { + for id in ["ec.noise.fractal", "ec.noise.turbulent"] { + let ui = &crate::find(id).unwrap().params.iter().find(|p| p.id == "subSettings/subScaling").unwrap().ui; + assert!( + matches!(ui, ParamUi::Slider { min, max, slider_min, slider_max, .. } + if *min == 10.0 && *max == 10000.0 && *slider_min == 25.0 && *slider_max == 100.0), + "{id}: {ui:?}" + ); + let at = |v: f64| run(id, &[("subSettings/subScaling", num(v))]); + assert_ne!(at(100.0), at(200.0), "{id}: 200 renders as 100"); + assert_ne!(at(200.0), at(10000.0), "{id}: 10000 renders as 200"); + } + } + + /// #3486: above 100 %, each octave is larger than the last, so its scale grows as Sub + /// Scaling^octave (100^19 at Complexity 20). Perspective Offset and Turbulence Factor multiply + /// the offset by that, which overflowed to infinity and drew NaN, also for a huge offset. At + /// 10 % the lattice coordinates pass the i32 range, whose neighbour index overflowed. + #[test] + fn extreme_sub_scaling_stays_finite() { + for id in ["ec.noise.fractal", "ec.noise.turbulent"] { + for sub in [10.0, 100.0, 9999.0, 10000.0] { + for (perspective, offset) in [(false, [-3000.0, 2500.0]), (true, [-3000.0, 2500.0]), (true, [1e17, -1e17])] { + let mut vals = vec![ + ("subSettings/subScaling", num(sub)), + ("complexity", num(20.0)), + ("transform/perspectiveOffset", Value::Bool(perspective)), + ("transform/offset", Value::Vec2(offset)), + ("evolution", num(200.0)), + ("blendingMode", Value::Enum(BLEND_NONE)), + ]; + if id == "ec.noise.turbulent" { + vals.push(("evolutionOptions/turbulenceFactor", num(10.0))); + } + let img = run(id, &vals); + assert!(img.data.iter().flatten().all(|c| c.is_finite()), "{id} sub {sub} perspective {perspective} offset {offset:?}: non-finite output"); + } + } + } + } + /// Turbulent Basic Fractal Noise drawn alone at `w` × `h`. fn turbulent_basic(w: u32, h: u32, vals: &[(&str, Value)]) -> Image { let mut all = vec![("fractalType", Value::Enum(2)), ("blendingMode", Value::Enum(BLEND_NONE))]; diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index 7deaaa911..9a5789506 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -60,6 +60,8 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3471, "ec.distort.transform", "scaleHeight", -30000.0, 30000.0), (3471, "ec.distort.transform", "scaleWidth", -30000.0, 30000.0), (3470, "ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 0.0, 100000.0), + (3486, "ec.noise.fractal", "subSettings/subScaling", 10.0, 10000.0), + (3486, "ec.noise.turbulent", "subSettings/subScaling", 10.0, 10000.0), ]; fn path(effect: &str, param: &str) -> String { diff --git a/crates/gpu/src/effects.rs b/crates/gpu/src/effects.rs index 5f204d1c4..4f85c6193 100644 --- a/crates/gpu/src/effects.rs +++ b/crates/gpu/src/effects.rs @@ -592,7 +592,7 @@ fn pointwise(e: &mut Enc, id: &str, ctx: &EffectCtx, b: GBuf) -> Option { let (ox, oy) = b.to_px(pr.v2("transform/offset")); let s = f("transform/scale"); let (sw, sh) = if pr.b("transform/uniformScaling") { (s, s) } else { (f("transform/scaleWidth"), f("transform/scaleHeight")) }; - let sub = (f("subSettings/subScaling") / 100.0).clamp(0.1, 1.0); + let sub = effectcraft_effects::sub_scaling_ratio(f("subSettings/subScaling")); p.u[0] = [10, kind, octaves.ceil() as u32, f("evolutionOptions/seed") as u32 ^ 0x51ed]; p.u[1] = [pr.b("invert") as u32, pr.e("overflow"), mode, 0]; p.f[0] = [ diff --git a/crates/gpu/src/tests/fx_noise.rs b/crates/gpu/src/tests/fx_noise.rs index 006128c73..1bfdd9e56 100644 --- a/crates/gpu/src/tests/fx_noise.rs +++ b/crates/gpu/src/tests/fx_noise.rs @@ -136,6 +136,24 @@ fn turbulent_noise() { effect_case("ec.noise.turbulent", &[("fractalType", e(7)), ("noiseType", e(0)), ("transform/perspectiveOffset", on()), ("opacity", n(70.0))]); } +/// #3486: Sub Scaling above 100 % on both GPU paths (the `pointwise` kernel for the plain +/// settings, `fxn_fractal` for Perspective Offset and Turbulent Noise), up to After Effects' +/// 10000 at the highest Complexity. +#[test] +fn fractal_noise_sub_scaling_above_100() { + for sub in [200.0, 10000.0] { + effect_case("ec.noise.fractal", &[("subSettings/subScaling", n(sub)), ("complexity", n(20.0))]); + effect_case( + "ec.noise.fractal", + &[("subSettings/subScaling", n(sub)), ("complexity", n(20.0)), ("transform/perspectiveOffset", on()), ("evolution", n(90.0))], + ); + effect_case( + "ec.noise.turbulent", + &[("subSettings/subScaling", n(sub)), ("complexity", n(20.0)), ("evolution", n(120.0)), ("evolutionOptions/turbulenceFactor", n(10.0))], + ); + } +} + #[test] fn fractal_noise_other_modes() { effect_case("ec.noise.fractal", &[("noiseType", e(3)), ("fractalType", e(4)), ("blendingMode", e(3))]); diff --git a/docs/effects-parity.md b/docs/effects-parity.md index b07c624f8..e8962cfac 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -64,6 +64,7 @@ the GPU is performance, not parity. | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | Fractal and Turbulent Noise: Sub Scaling takes After Effects' 10..10000 (slider and default unchanged), and above 100 each octave is larger than the last instead of being capped at 100; octave scales stay finite at Complexity 20 (CPU and GPU) | | 2026-11-12 | minor | Parameters take After Effects' recorded valid ranges (hard range; defaults and sliders unchanged): Levels (Individual Controls) levels −10000..10000 and Gamma from 0; 4-Color Gradient Blend to 10000 and Jitter to 500 %; Change Color Hue Transform ±1800°; Noise HLS (and Auto) amounts to 1000 % and Grain Size from 0; Grid Border to 2000; Venetian Blinds Width 1..32000 and Feather to 32000; Radial Wipe Feather to 32000; Scatter Amount to 1000; Beam thicknesses to 4000; Transform Scale ±30000 %; Turbulent Displace Random Seed to 100000. A test checks every mapped parameter's range against the recorded table (CPU and GPU) | | 2026-10-19 | minor | Glow (original colours): bright pass per channel, 8 × (value − threshold + 0.061), measured against After Effects 2026 (CPU and GPU) | | 2026-10-19 | minor | Glow (colour channels): the glow covers the layer's blurred alpha, blur σ = 0.384 × radius, measured against After Effects 2026 renders (CPU and GPU) | From 9b47fcf92fd895092919eaa78bde480288662684 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:10:22 +0530 Subject: [PATCH 26/78] #3585: Up and Down select the previous and next effect in Effect Controls With an effect header selected in a focused, on-screen Effect Controls, plain Down / Up now select the next / previous effect in the stacking order (After Effects), going on from the lowest / highest selected one and stopping at the last / first without nudging the layer. It is a selection change only: no undo step, no document or time change. The arrows reuse the Left / Right collapse path and now act on the layer the panel shows, so a locked panel's effects answer to them too. Modified arrows, hidden panels, text fields, menus, dialogs, viewer text editing and parameter-only selections keep their existing behaviour. --- crates/ui-egui/src/menus/shortcuts.rs | 2 +- crates/ui-egui/src/panels/effect_controls.rs | 2 +- .../src/panels/effect_controls/panel.rs | 53 ++++-- crates/ui-egui/tests/it/ui_effect_controls.rs | 162 ++++++++++++++++++ 4 files changed, 198 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/menus/shortcuts.rs b/crates/ui-egui/src/menus/shortcuts.rs index a573a2f6d..ff48f4d45 100644 --- a/crates/ui-egui/src/menus/shortcuts.rs +++ b/crates/ui-egui/src/menus/shortcuts.rs @@ -403,7 +403,7 @@ fn handle_shortcuts_impl(app: &mut EffectcraftApp, ctx: &egui::Context, tab_only if app.dialog.is_some() { continue; } - if !mods.any() && crate::panels::effect_controls::handle_disclosure_key(app, key) { + if !mods.any() && crate::panels::effect_controls::handle_arrow_key(app, key) { ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, key)); continue; } diff --git a/crates/ui-egui/src/panels/effect_controls.rs b/crates/ui-egui/src/panels/effect_controls.rs index 4c297f9e6..0b2ee437b 100644 --- a/crates/ui-egui/src/panels/effect_controls.rs +++ b/crates/ui-egui/src/panels/effect_controls.rs @@ -43,7 +43,7 @@ mod viewer; pub use common::{choose_files_after_apply, reveal_applied, set_lock}; pub(crate) use common::{gesture_key, scope_lock, shown_layer_id}; -pub(crate) use panel::handle_disclosure_key; +pub(crate) use panel::handle_arrow_key; pub use panel::{show, start_rename}; pub(crate) use rows::toggle_pick; pub use viewer::viewer_hook; diff --git a/crates/ui-egui/src/panels/effect_controls/panel.rs b/crates/ui-egui/src/panels/effect_controls/panel.rs index ac11bc7a2..5c06dec61 100644 --- a/crates/ui-egui/src/panels/effect_controls/panel.rs +++ b/crates/ui-egui/src/panels/effect_controls/panel.rs @@ -1,39 +1,54 @@ -use super::common::{Actions, PARAM_NAME_X, ROW, effect_active, prune_lock, shown_layer}; +use super::common::{Actions, PARAM_NAME_X, ROW, effect_active, prune_lock, shown_layer, shown_layer_id}; use super::editors::{curves_editor, editor_height, histogram_only, levels_editor, object_matte_editor, roto_editor, warp_editor}; use super::rows::{FxScope, group_rows, toggle_closed}; use super::{Align2, Color32, EffectcraftApp, EvalCtx, GroupKind, Icon, Layer, PropGroup, Rect, Sense, Stroke, Tokens, json, pos2, vec2, widgets}; use crate::dock::{PanelKind, WorkspaceExt as _}; -/// Plain Right / Left Arrow expand / collapse the selected effects, as in After Effects, before -/// the arrows' layer nudge runs. Only while Effect Controls has the focus and is on screen: the -/// front tab of its frame, drawn last frame (a maximized frame hides every other frame and every -/// floating window), not behind Home. With no effect header selected the arrows still nudge. -pub(crate) fn handle_disclosure_key(app: &mut EffectcraftApp, key: egui::Key) -> bool { +/// Plain arrows in Effect Controls, as in After Effects, before their layer nudge runs: Right / +/// Left expand / collapse the selected effects, and Down / Up select the next / previous effect +/// in the stacking order, from the lowest / highest selected one, stopping at the last / first. +/// Only while Effect Controls has the focus and is on screen: the front tab of its frame, drawn +/// last frame (a maximized frame hides every other frame and every floating window), not behind +/// Home. Only the effect headers selected on the layer the panel shows (the locked one when it is +/// locked) count: with none the arrows still nudge. +pub(crate) fn handle_arrow_key(app: &mut EffectcraftApp, key: egui::Key) -> bool { + use egui::Key::{ArrowDown, ArrowLeft, ArrowRight, ArrowUp}; let panel = PanelKind::EffectControls; if app.ui.focused != panel || app.ui.start_screen || app.session.state.text_edit.is_some() || !app.ui.dock.is_visible(panel) || !app.dock_rects.iter().any(|(p, _)| *p == panel) - || !matches!(key, egui::Key::ArrowLeft | egui::Key::ArrowRight) + || !matches!(key, ArrowLeft | ArrowRight | ArrowUp | ArrowDown) { return false; } - let Some(comp) = app.session.active_comp() else { return false }; - let Some(layer) = app.session.state.selected_layers.first().and_then(|id| comp.layer(*id)) else { return false }; - let Some(effects) = layer.effects() else { return false }; - let mut handled = false; - for g in effects.groups() { - if matches!(&g.kind, GroupKind::Effect { .. }) && app.session.state.selected_props.contains(&(layer.id, g.uid)) { - if key == egui::Key::ArrowLeft { - app.ui.fx_closed.insert(g.uid); - } else { - app.ui.fx_closed.remove(&g.uid); + let Some(layer_id) = shown_layer_id(app) else { return false }; + let Some(effects) = app.session.active_comp().and_then(|c| c.layer(layer_id)).and_then(|l| l.effects()) else { return false }; + let headers: Vec = effects.groups().filter(|g| matches!(&g.kind, GroupKind::Effect { .. })).map(|g| g.uid).collect(); + let selected = &app.session.state.selected_props; + let picked: Vec = headers.iter().enumerate().filter(|(_, u)| selected.contains(&(layer_id, **u))).map(|(i, _)| i).collect(); + let (Some(&top), Some(&bottom)) = (picked.first(), picked.last()) else { return false }; + match key { + ArrowUp | ArrowDown => { + // Clamped at the ends, where the key still doesn't nudge the layer. + let to = if key == ArrowUp { top.saturating_sub(1) } else { bottom.saturating_add(1).min(headers.len().saturating_sub(1)) }; + if let Some(&uid) = headers.get(to) { + // A selection, as a click on the header makes it: no undo step. + app.session.state.selected_props = vec![(layer_id, uid)]; + } + } + _ => { + for uid in picked.iter().filter_map(|i| headers.get(*i)) { + if key == ArrowLeft { + app.ui.fx_closed.insert(*uid); + } else { + app.ui.fx_closed.remove(uid); + } } - handled = true; } } - handled + true } // --------------------------------------------------------------------------------------------- diff --git a/crates/ui-egui/tests/it/ui_effect_controls.rs b/crates/ui-egui/tests/it/ui_effect_controls.rs index bfeea16aa..88f705f89 100644 --- a/crates/ui-egui/tests/it/ui_effect_controls.rs +++ b/crates/ui-egui/tests/it/ui_effect_controls.rs @@ -264,6 +264,168 @@ fn effect_header_arrows_leave_viewer_text_editing_alone() { assert_eq!(h.state().ui.fx_closed.iter().copied().collect::>(), vec![fx], "with the edit over, Left collapses the effect"); } +/// The x and y of `lid`'s Position, which the arrows' layer nudge moves. +fn position(h: &Harness<'_, EffectcraftApp>, lid: LayerId) -> [f64; 2] { + let p = layer(&h.state().session, lid.0).props.prop("transform/position").unwrap().value.as_vec3(); + [p[0], p[1]] +} + +/// #3585: plain Down / Up select the next / previous effect, a collapsed one too, and stop at the +/// last / first one without nudging the layer. Only the selection changes: not the document, the +/// time, the history or what is open. +#[test] +fn effect_header_down_and_up_select_the_next_and_previous_effect() { + let (mut h, lid, [(first, _), (second, _), (third, _)]) = header_arrow_harness(); + let at = rect_of(&h, &format!("effectControls.effect.{first}.name")).center(); + click(&mut h, at); + assert_eq!(h.state().session.state.selected_props, vec![(lid, first)]); + h.state_mut().ui.fx_closed.insert(second); + let project = serde_json::to_value(&h.state().session.project).unwrap(); + let time = h.state().session.time(); + let history = (h.state().session.history.undo.len(), h.state().session.history.redo.len()); + let closed = h.state().ui.fx_closed.clone(); + let (down, up) = (egui::Key::ArrowDown, egui::Key::ArrowUp); + for (key, want) in [(down, second), (down, third), (down, third), (up, second), (up, first), (up, first)] { + header_arrow_key(&mut h, key, egui::Modifiers::NONE); + assert_eq!(h.state().session.state.selected_props, vec![(lid, want)], "{key:?}"); + assert_eq!(serde_json::to_value(&h.state().session.project).unwrap(), project, "{key:?}: the layer is not nudged"); + assert_eq!(h.state().session.time(), time, "{key:?}"); + assert_eq!((h.state().session.history.undo.len(), h.state().session.history.redo.len()), history, "{key:?}: no undo step"); + assert_eq!(h.state().ui.fx_closed, closed, "{key:?}: nothing opens or closes"); + assert_eq!(h.state().ui.focused, PanelKind::EffectControls); + } +} + +/// #3585: with several effects selected, Down goes on from the lowest one and Up from the highest, +/// leaving one effect selected. Headers of other layers, stale ids and parameters don't count. +#[test] +fn effect_header_down_and_up_go_on_from_the_ends_of_a_multiple_selection() { + let (mut h, lid, [(first, _), (second, prop), (third, _)]) = header_arrow_harness(); + for (picked, key, want) in [ + (vec![(lid, second), (lid, first)], egui::Key::ArrowDown, third), + (vec![(lid, third), (lid, second)], egui::Key::ArrowUp, first), + (vec![(lid, first), (lid, third)], egui::Key::ArrowDown, third), + (vec![(lid, first), (lid, third)], egui::Key::ArrowUp, first), + (vec![(LayerId(0), first), (lid, u64::MAX), (lid, prop), (lid, second)], egui::Key::ArrowDown, third), + ] { + h.state_mut().session.state.selected_props = picked.clone(); + header_arrow_key(&mut h, key, egui::Modifiers::NONE); + assert_eq!(h.state().session.state.selected_props, vec![(lid, want)], "{picked:?} {key:?}"); + } + // A shift-click range, picked from the third effect up to the first, as a user would. + let at = rect_of(&h, &format!("effectControls.effect.{third}.name")).center(); + click(&mut h, at); + let at = rect_of(&h, &format!("effectControls.effect.{first}.name")).center(); + h.event(egui::Event::ModifiersChanged(egui::Modifiers::SHIFT)); + click(&mut h, at); + h.event(egui::Event::ModifiersChanged(Default::default())); + h.step(); + assert_eq!(h.state().session.state.selected_props.len(), 3, "the range is selected"); + header_arrow_key(&mut h, egui::Key::ArrowUp, egui::Modifiers::NONE); + assert_eq!(h.state().session.state.selected_props, vec![(lid, first)]); +} + +/// #3585: without an effect header selected on the panel's layer, or with the panel or the +/// keyboard elsewhere, plain Up / Down keep nudging the layer (or go to whoever owns the keys), +/// and the effect selection stays. +#[test] +fn effect_header_down_and_up_leave_the_nudge_and_other_keyboard_owners_alone() { + let (mut h, lid, [(first, _), (second, prop), _]) = header_arrow_harness(); + // A parameter, a stale header and another layer's header: the layer moves down, then up. + let picked = vec![(lid, prop), (lid, u64::MAX), (LayerId(0), first)]; + h.state_mut().session.state.selected_props = picked.clone(); + let y = position(&h, lid)[1]; + header_arrow_key(&mut h, egui::Key::ArrowDown, egui::Modifiers::NONE); + // (One pixel at the viewer's magnification.) + let step = position(&h, lid)[1] - y; + assert!(step > 0.0, "Down still nudges the layer"); + header_arrow_key(&mut h, egui::Key::ArrowUp, egui::Modifiers::NONE); + assert!((position(&h, lid)[1] - y).abs() < 1e-6, "Up still nudges the layer"); + assert_eq!(h.state().session.state.selected_props, picked); + + // With an effect selected: Shift nudges ten pixels, Cmd/Ctrl keeps its own meaning. + h.state_mut().session.state.selected_props = vec![(lid, second)]; + header_arrow_key(&mut h, egui::Key::ArrowDown, egui::Modifiers::SHIFT); + assert!((position(&h, lid)[1] - (y + 10.0 * step)).abs() < 1e-6, "Shift+Down nudges ten pixels"); + header_arrow_key(&mut h, egui::Key::ArrowUp, egui::Modifiers::SHIFT); + assert!((position(&h, lid)[1] - y).abs() < 1e-6); + header_arrow_key(&mut h, egui::Key::ArrowDown, egui::Modifiers::COMMAND); + assert_eq!(h.state().session.state.selected_props, vec![(lid, second)], "Cmd/Ctrl+Down keeps the effect selection"); + + // Another panel, a dialog, the context menu and the rename field own the arrows. + let stays = |h: &mut Harness<'_, EffectcraftApp>, why: &str| { + for key in [egui::Key::ArrowDown, egui::Key::ArrowUp] { + header_arrow_key(h, key, egui::Modifiers::NONE); + assert_eq!(h.state().session.state.selected_props, vec![(lid, second)], "{why}: {key:?}"); + } + }; + h.state_mut().ui.focused = PanelKind::Composition; + stays(&mut h, "another panel"); + h.state_mut().ui.focused = PanelKind::EffectControls; + h.state_mut().dialog = Some(effectcraft_ui_egui::Dialog::About); + stays(&mut h, "a dialog"); + h.state_mut().dialog = None; + h.run_steps(3); + let at = rect_of(&h, &format!("effectControls.effect.{second}.name")).center(); + h.event(egui::Event::PointerMoved(at)); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }); + h.step(); + } + h.run_steps(2); + assert!(egui::Popup::is_any_open(&h.ctx), "the effect context menu is open"); + stays(&mut h, "the context menu"); + header_arrow_key(&mut h, egui::Key::Escape, egui::Modifiers::NONE); + h.run_steps(3); + double_click(&mut h, at); + h.run_steps(3); + assert!(h.state().auto.find(&format!("effectControls.effect.{second}.nameEdit")).is_some(), "the rename field is open"); + stays(&mut h, "the rename field"); + assert!(h.state().auto.find(&format!("effectControls.effect.{second}.nameEdit")).is_some()); +} + +/// #3585: a hidden Effect Controls (closed, under a maximized frame, behind Home) with the focus +/// left on it doesn't take Up / Down: they nudge the layer. +#[test] +fn effect_header_down_and_up_ignore_a_hidden_panel() { + for hidden in ["closed", "maximized", "home"] { + let (mut h, lid, [(fx, _), _, _]) = header_arrow_harness(); + h.state_mut().session.state.selected_props = vec![(lid, fx)]; + match hidden { + "closed" => h.state_mut().close_panel(PanelKind::EffectControls), + "maximized" => h.state_mut().toggle_maximize(PanelKind::Composition), + _ => h.state_mut().ui.start_screen = true, + } + h.run_steps(2); + assert_eq!(h.state().ui.focused, PanelKind::EffectControls, "{hidden}: stale focus is preserved"); + let y = position(&h, lid)[1]; + header_arrow_key(&mut h, egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_eq!(h.state().session.state.selected_props, vec![(lid, fx)], "{hidden}"); + assert!(position(&h, lid)[1] > y, "{hidden}: Down still nudges the layer"); + } +} + +/// #3585: locked to a layer that isn't selected, Effect Controls' arrows act on the effects it +/// shows: Down / Up select among them and Left / Right close and open them. +#[test] +fn effect_header_arrows_act_on_the_locked_layer() { + let (mut h, lid, [(first, _), (second, _), _]) = header_arrow_harness(); + let comp = h.state().session.active_comp_id().unwrap().0; + let other = h.state_mut().session.execute("layer.newSolid", json!({"name": "Other", "color": "#202020"})).unwrap()["layer"].as_u64().unwrap(); + h.state_mut().ui.effect_controls_lock = Some(effectcraft_ui_egui::state::EffectControlsLock { comp, layer: lid.0 }); + h.state_mut().session.state.selected_layers = vec![LayerId(other)]; + h.state_mut().session.state.selected_props = vec![(lid, first)]; + h.state_mut().ui.focused = PanelKind::EffectControls; + h.run_steps(3); + assert!(shows_effect(&h, first), "the locked panel shows the first layer"); + header_arrow_key(&mut h, egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_eq!(h.state().session.state.selected_props, vec![(lid, second)]); + header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::NONE); + assert_eq!(h.state().ui.fx_closed.iter().copied().collect::>(), vec![second], "Left closes the locked layer's effect"); + header_arrow_key(&mut h, egui::Key::ArrowRight, egui::Modifiers::NONE); + assert!(h.state().ui.fx_closed.is_empty()); +} + #[test] fn effect_controls_widgets_register_automation_ids() { let (app, x) = app(); From 4d318a5347bd2608870ea2dcd2e91183b319e100 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:11:18 +0530 Subject: [PATCH 27/78] #3585: scroll the effect Up / Down picks into view Effect Controls scrolls its list so the header Down / Up selected is in view, as a long effect stack would otherwise move the selection off screen. The key handler leaves the effect to reveal for the panel's next pass, which knows where the header is laid out. --- crates/ui-egui/src/menus/shortcuts.rs | 2 +- .../src/panels/effect_controls/panel.rs | 25 +++++++++++++- crates/ui-egui/tests/it/ui_effect_controls.rs | 34 +++++++++++++++++++ 3 files changed, 59 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/menus/shortcuts.rs b/crates/ui-egui/src/menus/shortcuts.rs index ff48f4d45..eaca5568a 100644 --- a/crates/ui-egui/src/menus/shortcuts.rs +++ b/crates/ui-egui/src/menus/shortcuts.rs @@ -403,7 +403,7 @@ fn handle_shortcuts_impl(app: &mut EffectcraftApp, ctx: &egui::Context, tab_only if app.dialog.is_some() { continue; } - if !mods.any() && crate::panels::effect_controls::handle_arrow_key(app, key) { + if !mods.any() && crate::panels::effect_controls::handle_arrow_key(app, ctx, key) { ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, key)); continue; } diff --git a/crates/ui-egui/src/panels/effect_controls/panel.rs b/crates/ui-egui/src/panels/effect_controls/panel.rs index 5c06dec61..f89a6eac0 100644 --- a/crates/ui-egui/src/panels/effect_controls/panel.rs +++ b/crates/ui-egui/src/panels/effect_controls/panel.rs @@ -11,7 +11,7 @@ use crate::dock::{PanelKind, WorkspaceExt as _}; /// last frame (a maximized frame hides every other frame and every floating window), not behind /// Home. Only the effect headers selected on the layer the panel shows (the locked one when it is /// locked) count: with none the arrows still nudge. -pub(crate) fn handle_arrow_key(app: &mut EffectcraftApp, key: egui::Key) -> bool { +pub(crate) fn handle_arrow_key(app: &mut EffectcraftApp, ctx: &egui::Context, key: egui::Key) -> bool { use egui::Key::{ArrowDown, ArrowLeft, ArrowRight, ArrowUp}; let panel = PanelKind::EffectControls; if app.ui.focused != panel @@ -36,6 +36,7 @@ pub(crate) fn handle_arrow_key(app: &mut EffectcraftApp, key: egui::Key) -> bool if let Some(&uid) = headers.get(to) { // A selection, as a click on the header makes it: no undo step. app.session.state.selected_props = vec![(layer_id, uid)]; + reveal_effect(ctx, uid); } } _ => { @@ -51,6 +52,17 @@ pub(crate) fn handle_arrow_key(app: &mut EffectcraftApp, key: egui::Key) -> bool true } +/// The effect header the next Effect Controls pass scrolls into view. +fn reveal_id() -> egui::Id { + egui::Id::unique("ec-reveal") +} + +/// Scroll Effect Controls so effect `uid`'s header is in view, once it has been laid out. +fn reveal_effect(ctx: &egui::Context, uid: u64) { + ctx.data_mut(|d| d.insert_temp(reveal_id(), uid)); + ctx.request_repaint(); +} + // --------------------------------------------------------------------------------------------- /// Open the rename field on effect `uid` (Enter with the effect selected). It takes the keyboard, @@ -449,7 +461,18 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { actions.extend(crate::menus::menu_contents(app, ui, "Effect")); }); let content_h = y + scroll.offset - body.min.y; + let offset = scroll.offset; scroll.end(ui, &mut app.auto, "effectControls.scroll", content_h, &t); + // Up / Down picked an effect: bring its header into view from the next pass (after `end`, + // which stores this pass's offset). + if let Some(uid) = ctx.data_mut(|d| d.remove_temp::(reveal_id())) + && let Some(&(_, top)) = tops.iter().find(|(u, _)| *u == uid) + { + // (With the 4-point gap above the first header.) + let top = top - body.min.y + offset; + widgets::PanelScroll::reveal(&ctx, egui::Id::unique("ec-scroll"), top - 4.0, top + ROW + 2.0, body.height()); + ctx.request_repaint(); + } drop_payload(ui, rect, &p, &t, layer.id.0, &mut actions); if ui.input(|i| i.pointer.primary_down()) && actions.iter().any(|(id, _)| id == "prop.set") { app.ui.viewer.property_interacting = true; diff --git a/crates/ui-egui/tests/it/ui_effect_controls.rs b/crates/ui-egui/tests/it/ui_effect_controls.rs index 88f705f89..49de1f24c 100644 --- a/crates/ui-egui/tests/it/ui_effect_controls.rs +++ b/crates/ui-egui/tests/it/ui_effect_controls.rs @@ -426,6 +426,40 @@ fn effect_header_arrows_act_on_the_locked_layer() { assert!(h.state().ui.fx_closed.is_empty()); } +/// #3585: a long effect list scrolls so the effect Down / Up picks stays in view. +#[test] +fn effect_header_down_and_up_scroll_the_picked_effect_into_view() { + let mut s = Session::default(); + s.execute("comp.new", json!({"name": "Long", "width": 32, "height": 18, "frameRate": 30, "duration": 2})).unwrap(); + let lid = s.execute("layer.newSolid", json!({"name": "Controls", "color": "#40b080"})).unwrap()["layer"].as_u64().unwrap(); + let fx: Vec = + (0..16).map(|_| s.execute("effect.apply", json!({"layers": [lid], "effect": "Point Control"})).unwrap()["effects"][0].as_u64().unwrap()).collect(); + s.state.selected_props = vec![(LayerId(lid), fx[0])]; + let mut app = EffectcraftApp::new(s); + app.show_panel(PanelKind::EffectControls); + app.toggle_maximize(PanelKind::EffectControls); + app.ui.focused = PanelKind::EffectControls; + let mut h = Harness::builder().with_size(egui::vec2(800.0, 300.0)).with_step_dt(1.0 / 60.0).build_eframe(|_| app); + h.run_steps(4); + let panel = rect_of(&h, "panel.EffectControls"); + let last = fx[fx.len() - 1]; + assert!(!panel.contains_rect(rect_of(&h, &format!("effectControls.effect.{last}"))), "the last effect starts out of view"); + for _ in 1..fx.len() { + header_arrow_key(&mut h, egui::Key::ArrowDown, egui::Modifiers::NONE); + h.run_steps(2); + let (_, uid) = h.state().session.state.selected_props[0]; + assert!(panel.contains_rect(rect_of(&h, &format!("effectControls.effect.{uid}"))), "Down keeps effect {uid} in view"); + } + assert_eq!(h.state().session.state.selected_props, vec![(LayerId(lid), last)]); + for _ in 1..fx.len() { + header_arrow_key(&mut h, egui::Key::ArrowUp, egui::Modifiers::NONE); + h.run_steps(2); + let (_, uid) = h.state().session.state.selected_props[0]; + assert!(panel.contains_rect(rect_of(&h, &format!("effectControls.effect.{uid}"))), "Up keeps effect {uid} in view"); + } + assert_eq!(h.state().session.state.selected_props, vec![(LayerId(lid), fx[0])]); +} + #[test] fn effect_controls_widgets_register_automation_ids() { let (app, x) = app(); From 2e17ed1d832a49e2f01beb7c510114561f92fa05 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:12:25 +0530 Subject: [PATCH 28/78] #3469: Turbulent Displace Amount takes After Effects' valid range The hard range was -1000..1000, so prop.set and the Effect Controls and Timeline editors clamped Amount values After Effects accepts. The recorded ADBE Turbulent Displace definition allows -10000..10000 (plain units, no conversion). The default and the -200..200 slider are unchanged. The .aep range guard no longer lists the parameter as narrower, and the engine range test covers both ends through prop.set, undo/redo, save and reopen, and projects saved with the old range. --- crates/aep/src/export/fx_defs.rs | 1 - crates/effects/src/distort2.rs | 12 +++++++++++- crates/engine/src/tests/effect_ranges.rs | 1 + docs/effects-parity.md | 1 + 4 files changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index 338e00fc5..527ef62f8 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -732,7 +732,6 @@ mod tests { ("ec.blur.sharpen", "amount", 3466), ("ec.blur.radial", "amount", 3467), ("ec.blur.ccradial", "amount", 3468), - ("ec.distort.turbulentdisplace", "amount", 3469), ("ec.time.pixelmotionblur", "shutterAngle", 3481), ("ec.time.pixelmotionblur", "shutterSamples", 3482), ("ec.noise.fractal", "subSettings/subInfluence", 3485), diff --git a/crates/effects/src/distort2.rs b/crates/effects/src/distort2.rs index 611cb6dcf..4d0e5d7ec 100644 --- a/crates/effects/src/distort2.rs +++ b/crates/effects/src/distort2.rs @@ -736,7 +736,7 @@ pub fn specs() -> Vec { "Turbulent Displace", vec![ p("displacement", "Displacement", Value::Enum(0), popup(&TURBULENT_KINDS)), - p("amount", "Amount", num(50.0), slider(-1000.0, 1000.0, -200.0, 200.0, 1)), + p("amount", "Amount", num(50.0), slider(-10000.0, 10000.0, -200.0, 200.0, 1)), p("size", "Size", num(100.0), slider(2.0, 4000.0, 2.0, 400.0, 1)), p("offset", "Offset (Turbulence)", pt(0.5, 0.5), ParamUi::Point), p("complexity", "Complexity", num(1.0), slider(1.0, 10.0, 1.0, 10.0, 1)), @@ -1010,6 +1010,16 @@ mod tests { assert!(max_diff(&run("ec.distort.turbulentdisplace", &[], img.clone()).img, &img) > 1e-3); } + /// #3469: Amount's hard range is After Effects' recorded valid range, -10000..10000; the + /// slider keeps its -200..200 scrub range. + #[test] + fn turbulent_displace_amount_takes_the_after_effects_range() { + let spec = crate::find("ec.distort.turbulentdisplace").unwrap(); + let amount = spec.params.iter().find(|p| p.id == "amount").unwrap(); + let ParamUi::Slider { min, max, slider_min, slider_max, .. } = amount.ui else { panic!("{:?}", amount.ui) }; + assert_eq!((min, max, slider_min, slider_max), (-10000.0, 10000.0, -200.0, 200.0)); + } + #[test] fn griddler_default_is_identity() { let img = test_img(32, 24); diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index 7deaaa911..5436d4f32 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -60,6 +60,7 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3471, "ec.distort.transform", "scaleHeight", -30000.0, 30000.0), (3471, "ec.distort.transform", "scaleWidth", -30000.0, 30000.0), (3470, "ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 0.0, 100000.0), + (3469, "ec.distort.turbulentdisplace", "amount", -10000.0, 10000.0), ]; fn path(effect: &str, param: &str) -> String { diff --git a/docs/effects-parity.md b/docs/effects-parity.md index b07c624f8..f2c827432 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -64,6 +64,7 @@ the GPU is performance, not parity. | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | Turbulent Displace: Amount takes After Effects' recorded valid range, −10000..10000 (default and the −200..200 slider unchanged) | | 2026-11-12 | minor | Parameters take After Effects' recorded valid ranges (hard range; defaults and sliders unchanged): Levels (Individual Controls) levels −10000..10000 and Gamma from 0; 4-Color Gradient Blend to 10000 and Jitter to 500 %; Change Color Hue Transform ±1800°; Noise HLS (and Auto) amounts to 1000 % and Grain Size from 0; Grid Border to 2000; Venetian Blinds Width 1..32000 and Feather to 32000; Radial Wipe Feather to 32000; Scatter Amount to 1000; Beam thicknesses to 4000; Transform Scale ±30000 %; Turbulent Displace Random Seed to 100000. A test checks every mapped parameter's range against the recorded table (CPU and GPU) | | 2026-10-19 | minor | Glow (original colours): bright pass per channel, 8 × (value − threshold + 0.061), measured against After Effects 2026 (CPU and GPU) | | 2026-10-19 | minor | Glow (colour channels): the glow covers the layer's blurred alpha, blur σ = 0.384 × radius, measured against After Effects 2026 renders (CPU and GPU) | From 040fe61b84ad59548cc1bf876c6260443b88b2b7 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:13:10 +0530 Subject: [PATCH 29/78] #3469: Turbulent Displace stays finite at any Amount Expressions are not clamped to the hard range. Padding computed amount.abs().ceil() as u32 + 1, which overflowed (a panic in debug builds) from about 4.3e9 on both the CPU and GPU paths, a NaN Amount filled the layer with NaN, and an infinite one sent infinite coordinates to the samplers' integer pixel positions. turbulent_amount_px, shared by both paths, skips a zero or NaN Amount and bounds the rest to 2^24 px. Values inside the hard range are unchanged. Tests cover both ends of the range with every displacement kind, pinning and Resize Layer (finite, padding within budget), Amounts past it, and CPU/GPU agreement at -10000, 10000 and infinity. --- crates/effects/src/distort2.rs | 59 ++++++++++++++++++++++++++++-- crates/effects/src/lib.rs | 2 +- crates/gpu/src/fx_distort.rs | 5 +-- crates/gpu/src/tests/fx_distort.rs | 8 ++++ docs/effects-parity.md | 2 +- 5 files changed, 68 insertions(+), 8 deletions(-) diff --git a/crates/effects/src/distort2.rs b/crates/effects/src/distort2.rs index 4d0e5d7ec..ed04c3493 100644 --- a/crates/effects/src/distort2.rs +++ b/crates/effects/src/distort2.rs @@ -85,11 +85,24 @@ const TURBULENT_PINNING: [&str; 15] = [ "Pin Bottom Locked", ]; +/// The largest Amount, in buffer pixels, Turbulent Displace displaces by: 2^24, exact in f32. +/// Only an expression gets past the -10000..10000 hard range. At this bound nearly every sample +/// already lands far outside any buffer, and the padding and the CPU and GPU samplers' integer +/// pixel positions (the gradient kinds move up to 2.5 × Amount) stay in range. +const TURBULENT_MAX_AMOUNT_PX: f64 = 16_777_216.0; + +/// Turbulent Displace's Amount at `scale`, in buffer pixels, bounded to +/// ±[`TURBULENT_MAX_AMOUNT_PX`]; `None` when nothing moves (zero, or not a number). Shared with +/// the GPU path. +pub fn turbulent_amount_px(ctx: &EffectCtx, scale: f64) -> Option { + let amount = ctx.params.f("amount") * scale; + (amount.abs() >= 1e-9).then(|| amount.clamp(-TURBULENT_MAX_AMOUNT_PX, TURBULENT_MAX_AMOUNT_PX)) +} + fn turbulent_displace(ctx: &EffectCtx, mut b: Buf) -> Buf { - let amount = ctx.params.f("amount") * b.scale; - if amount.abs() < 1e-9 { + let Some(amount) = turbulent_amount_px(ctx, b.scale) else { return b; - } + }; // TURBULENT_KINDS order: the "Smoother" variants (3, 4, 5) use a gentler octave falloff. let kind = ctx.params.e("displacement"); let size = (ctx.params.f("size") * b.scale).max(1.0); @@ -1020,6 +1033,46 @@ mod tests { assert_eq!((min, max, slider_min, slider_max), (-10000.0, 10000.0, -200.0, 200.0)); } + /// #3469: at either end of Amount's range, with every displacement kind, resized or not and + /// pinned or not, the output stays finite, in its alpha range and within the padding budget. + #[test] + fn turbulent_displace_extreme_amounts_stay_finite_and_bounded() { + let img = test_img(32, 24); + // Resize Layer grows the buffer to the padding budget (16 Mpx here), so it runs with two + // kinds; the rest stay layer-sized. + let cases = (0..9).flat_map(|kind| [(kind, 0, 0.0), (kind, 1, 0.0), (kind, 8, 0.0)]).chain([(0, 3, 1.0), (4, 14, 1.0)]); + for amount in [-10000.0, 10000.0] { + for (kind, pin, resize) in cases.clone() { + let set = [("amount", num(amount)), ("displacement", Value::Enum(kind)), ("pinning", Value::Enum(pin)), ("resizeLayer", num(resize))]; + let o = run("ec.distort.turbulentdisplace", &set, img.clone()); + let what = format!("amount {amount} kind {kind} pinning {pin} resize {resize}"); + assert!(o.img.data.iter().all(|p| p.iter().all(|v| v.is_finite()) && (0.0..=1.0 + 1e-5).contains(&p[3])), "{what}"); + let area = u64::from(o.img.width) * u64::from(o.img.height); + assert!(area <= 16_777_216, "{what}: {}x{}", o.img.width, o.img.height); + } + } + } + + /// #3469: an Amount past the hard range, which only an expression produces, renders without + /// overflowing the padding or the sampler's pixel positions and stays finite (a plain, a + /// gradient and the cross kind; unpinned, pinned and locked); one that is not a number leaves + /// the layer as it is. + #[test] + fn turbulent_displace_unbounded_amounts_do_not_crash() { + let img = test_img(32, 24); + let cases = [0, 1, 8].into_iter().flat_map(|kind| [(kind, 0, 0.0), (kind, 1, 0.0), (kind, 11, 0.0)]).chain([(0, 1, 1.0)]); + for amount in [1e12, -1e300, f64::MAX, f64::INFINITY, f64::NEG_INFINITY] { + for (kind, pin, resize) in cases.clone() { + let set = [("amount", num(amount)), ("displacement", Value::Enum(kind)), ("pinning", Value::Enum(pin)), ("resizeLayer", num(resize))]; + let o = run("ec.distort.turbulentdisplace", &set, img.clone()); + assert!(o.img.data.iter().all(|p| p.iter().all(|v| v.is_finite())), "{amount} kind {kind} pinning {pin} resize {resize}"); + } + } + for resize in [0.0, 1.0] { + assert_eq!(run("ec.distort.turbulentdisplace", &[("amount", num(f64::NAN)), ("resizeLayer", num(resize))], img.clone()).img, img); + } + } + #[test] fn griddler_default_is_identity() { let img = test_img(32, 24); diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 5da2035ac..1e1003e7e 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -84,7 +84,7 @@ pub use color_fx::{COLORAMA_PRESETS, ColoramaPalette}; pub use color2::{Curve, auto_correct_settings, color_link_mode, color_link_sample, equalize_tables, luma_clip_points, shadow_highlight_amounts}; pub use color3::OffsetCurve; pub use distort::{transform_grow, transform_matrix_px, transform_shutter}; -pub use distort2::{MAGNIFY_MODES, bezier_grid, parse_mesh}; +pub use distort2::{MAGNIFY_MODES, bezier_grid, parse_mesh, turbulent_amount_px}; pub use distort3::{RESHAPE_POINTS, ReshapeSetup, SmearSetup, cc_smear_pad, reshape_setup, smear_setup, warp_inverse_map}; pub use distort4::liquify_mesh; use effectcraft_keyframe::Value; diff --git a/crates/gpu/src/fx_distort.rs b/crates/gpu/src/fx_distort.rs index 510f91e8c..cc25d3106 100644 --- a/crates/gpu/src/fx_distort.rs +++ b/crates/gpu/src/fx_distort.rs @@ -172,10 +172,9 @@ fn cc_lens(e: &mut Enc, ctx: &EffectCtx, b: GBuf) -> Option { } fn turbulent(e: &mut Enc, ctx: &EffectCtx, mut b: GBuf) -> Option { - let amount = ctx.params.f("amount") * b.scale; - if amount.abs() < 1e-9 { + let Some(amount) = effectcraft_effects::turbulent_amount_px(ctx, b.scale) else { return Some(b); - } + }; let kind = ctx.params.e("displacement"); let size = (ctx.params.f("size") * b.scale).max(1.0); if ctx.params.b("resizeLayer") && !ctx.adjustment { diff --git a/crates/gpu/src/tests/fx_distort.rs b/crates/gpu/src/tests/fx_distort.rs index 6fc18f3c9..e5e3ceca9 100644 --- a/crates/gpu/src/tests/fx_distort.rs +++ b/crates/gpu/src/tests/fx_distort.rs @@ -57,6 +57,14 @@ fn turbulent_displace_and_cc_lens() { ], ); effect_case("ec.distort.turbulentdisplace", &[("displacement", e(8)), ("size", n(15.0)), ("pinning", e(6))]); + // #3469: both ends of After Effects' Amount range, resized and pinned, and an expression's + // Amount past it. + effect_case("ec.distort.turbulentdisplace", &[("size", n(30.0)), ("amount", n(10000.0))]); + effect_case( + "ec.distort.turbulentdisplace", + &[("displacement", e(1)), ("size", n(25.0)), ("amount", n(-10000.0)), ("pinning", e(1)), ("resizeLayer", on())], + ); + effect_case("ec.distort.turbulentdisplace", &[("displacement", e(7)), ("amount", n(f64::INFINITY)), ("pinning", e(2))]); // #943: Evolution moves the pattern at a constant rate on both paths, including steps of a // few degrees and angles past a whole revolution, where an eased evolution axis diverges. for evolution in [10.0, 37.0, 400.0, 725.5] { diff --git a/docs/effects-parity.md b/docs/effects-parity.md index f2c827432..c438eedbb 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -64,7 +64,7 @@ the GPU is performance, not parity. | Date | Change | Summary | |---|---|---| -| 2026-11-17 | minor | Turbulent Displace: Amount takes After Effects' recorded valid range, −10000..10000 (default and the −200..200 slider unchanged) | +| 2026-11-17 | minor | Turbulent Displace: Amount takes After Effects' recorded valid range, −10000..10000 (default and the −200..200 slider unchanged). Past it (an expression's value) the displacement is bounded to 2^24 px and a NaN Amount leaves the layer unchanged, so padding and sampling stay finite (CPU and GPU) | | 2026-11-12 | minor | Parameters take After Effects' recorded valid ranges (hard range; defaults and sliders unchanged): Levels (Individual Controls) levels −10000..10000 and Gamma from 0; 4-Color Gradient Blend to 10000 and Jitter to 500 %; Change Color Hue Transform ±1800°; Noise HLS (and Auto) amounts to 1000 % and Grain Size from 0; Grid Border to 2000; Venetian Blinds Width 1..32000 and Feather to 32000; Radial Wipe Feather to 32000; Scatter Amount to 1000; Beam thicknesses to 4000; Transform Scale ±30000 %; Turbulent Displace Random Seed to 100000. A test checks every mapped parameter's range against the recorded table (CPU and GPU) | | 2026-10-19 | minor | Glow (original colours): bright pass per channel, 8 × (value − threshold + 0.061), measured against After Effects 2026 (CPU and GPU) | | 2026-10-19 | minor | Glow (colour channels): the glow covers the layer's blurred alpha, blur σ = 0.384 × radius, measured against After Effects 2026 renders (CPU and GPU) | From 4cf774134000e34f837f54584465161736da210d Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:14:01 +0530 Subject: [PATCH 30/78] #3469: Turbulent Displace locked pinning on a sub-pixel layer Locked pinning clamped samples to lx + 0.5 .. lx + lw - 0.5. On a layer under a buffer pixel across (a 1-pixel layer at half resolution) the bounds cross and f64::clamp panics. They now meet at the layer's centre there and are unchanged otherwise. --- crates/effects/src/distort2.rs | 21 ++++++++++++++++++++- docs/effects-parity.md | 2 +- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/effects/src/distort2.rs b/crates/effects/src/distort2.rs index ed04c3493..8ca2f2d72 100644 --- a/crates/effects/src/distort2.rs +++ b/crates/effects/src/distort2.rs @@ -123,6 +123,10 @@ fn turbulent_displace(ctx: &EffectCtx, mut b: Buf) -> Buf { let falloff = if (3..=5).contains(&kind) { 0.3 } else { 0.5 }; let (lx, ly, lw, lh) = layer_rect(ctx, &b); let edge = (lw.min(lh) * if locked { 0.25 } else { 0.1 }).max(1.0); + // Locked: samples stay between the outermost pixel centres, or at the centre of a layer under + // a pixel across (half resolution), whose bounds would otherwise cross. + let (ix, iy) = (0.5f64.min(lw * 0.5), 0.5f64.min(lh * 0.5)); + let lock = (lx + ix, lx + lw - ix, ly + iy, ly + lh - iy); let seed = (ctx.seed ^ 0x7d15).wrapping_add((ctx.params.f("evolutionOptions/randomSeed") as i64 as u32).wrapping_mul(0x9e37_79b9)); let n = |u: f64, v: f64, s: u32| { let s = seed.wrapping_add(s); @@ -169,7 +173,7 @@ fn turbulent_displace(ctx: &EffectCtx, mut b: Buf) -> Buf { }; let (sx, sy) = (x + dx * k, y + dy * k); if locked { - return Some((sx.clamp(lx + 0.5, lx + lw - 0.5), sy.clamp(ly + 0.5, ly + lh - 0.5))); + return Some((sx.clamp(lock.0, lock.1), sy.clamp(lock.2, lock.3))); } Some((sx, sy)) }); @@ -1073,6 +1077,21 @@ mod tests { } } + /// #3469: a locked pinning on a layer under a buffer pixel across (a 1-pixel layer at half + /// resolution) keeps samples inside it without inverted clamp bounds, at any Amount. + #[test] + fn turbulent_displace_locked_pinning_on_a_subpixel_layer_does_not_crash() { + let spec = crate::find("ec.distort.turbulentdisplace").unwrap(); + for amount in [-10000.0, 50.0, 10000.0] { + let mut params = Params { values: spec.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect() }; + params.values.insert("amount".into(), num(amount)); + params.values.insert("pinning".into(), Value::Enum(8)); + let ctx = EffectCtx { params: ¶ms, time: 0.5, layer_size: [1.0, 1.0], seed: 3, adjustment: false, env: Default::default() }; + let o = crate::apply(spec, &ctx, Buf { img: test_img(1, 1), offset: [0.0, 0.0], scale: 0.5 }); + assert!(o.img.data.iter().all(|p| p.iter().all(|v| v.is_finite())), "{amount}"); + } + } + #[test] fn griddler_default_is_identity() { let img = test_img(32, 24); diff --git a/docs/effects-parity.md b/docs/effects-parity.md index c438eedbb..d109da598 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -64,7 +64,7 @@ the GPU is performance, not parity. | Date | Change | Summary | |---|---|---| -| 2026-11-17 | minor | Turbulent Displace: Amount takes After Effects' recorded valid range, −10000..10000 (default and the −200..200 slider unchanged). Past it (an expression's value) the displacement is bounded to 2^24 px and a NaN Amount leaves the layer unchanged, so padding and sampling stay finite (CPU and GPU) | +| 2026-11-17 | minor | Turbulent Displace: Amount takes After Effects' recorded valid range, −10000..10000 (default and the −200..200 slider unchanged). Past it (an expression's value) the displacement is bounded to 2^24 px and a NaN Amount leaves the layer unchanged, so padding and sampling stay finite (CPU and GPU). Locked pinning on a layer under a pixel across no longer crashes | | 2026-11-12 | minor | Parameters take After Effects' recorded valid ranges (hard range; defaults and sliders unchanged): Levels (Individual Controls) levels −10000..10000 and Gamma from 0; 4-Color Gradient Blend to 10000 and Jitter to 500 %; Change Color Hue Transform ±1800°; Noise HLS (and Auto) amounts to 1000 % and Grain Size from 0; Grid Border to 2000; Venetian Blinds Width 1..32000 and Feather to 32000; Radial Wipe Feather to 32000; Scatter Amount to 1000; Beam thicknesses to 4000; Transform Scale ±30000 %; Turbulent Displace Random Seed to 100000. A test checks every mapped parameter's range against the recorded table (CPU and GPU) | | 2026-10-19 | minor | Glow (original colours): bright pass per channel, 8 × (value − threshold + 0.061), measured against After Effects 2026 (CPU and GPU) | | 2026-10-19 | minor | Glow (colour channels): the glow covers the layer's blurred alpha, blur σ = 0.384 × radius, measured against After Effects 2026 renders (CPU and GPU) | From 300fc48f1ed525cea854d329f003f2abef4699d3 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:14:33 +0530 Subject: [PATCH 31/78] #3466: test Sharpen Amount clamps just outside 0..4000 prop.set of 4001 and -1 stores 4000 and 0, and undo/redo around the clamped set restore the values. --- crates/engine/src/tests/effect_ranges.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index f2ad2112e..b1c93ccb5 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -162,6 +162,23 @@ fn projects_saved_with_the_narrower_ranges_open_with_the_new_ones() { } } +/// #3466: Sharpen Amount clamps just outside After Effects' 0..4000, and an undo after a +/// clamped set restores the value from before it. +#[test] +fn sharpen_amount_clamps_outside_the_after_effects_range() { + let (mut s, l, _) = session(); + let (e, p) = ("ec.blur.sharpen", "amount"); + for (v, want) in [(4001.0, 4000.0), (-1.0, 0.0)] { + set(&mut s, l, e, p, 1000.0); + assert_eq!(set(&mut s, l, e, p, v), json!(want), "{v}: prop.set reply"); + assert_eq!(read(&mut s, l, e, p), want, "{v}"); + assert!(s.undo()); + assert_eq!(read(&mut s, l, e, p), 1000.0, "{v}: undo"); + assert!(s.redo()); + assert_eq!(read(&mut s, l, e, p), want, "{v}: redo"); + } +} + /// The property at `path` (`group/param`) in an effect instance. fn prop_mut<'a>(g: &'a mut PropGroup, path: &str) -> Option<&'a mut effectcraft_project::Property> { match path.split_once('/') { From d5e74c880fd779fef635a01993eafaed70f7b0b6 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:15:51 +0530 Subject: [PATCH 32/78] #3467: Radial Blur docs say the wide Zoom shape is unmeasured The spin helper's name gives its unit (degrees), the zoom helper's doc uses |amount| as the code does, and the parity row and tests say what is and is not checked against After Effects. --- crates/effects/src/misc.rs | 6 ++++-- crates/gpu/src/fx_generate.rs | 2 +- crates/raster/src/blur.rs | 7 ++++--- crates/raster/src/lib.rs | 2 +- docs/effects-parity.md | 2 +- 5 files changed, 11 insertions(+), 8 deletions(-) diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index ea196fc11..69a30505a 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -1151,7 +1151,8 @@ mod tests { /// Amount takes After Effects' valid range up to 1000 (#3467), Zoom 1000 a spread of 10. /// Zoom samples along the ray from the centre through the pixel, never past the centre: on a /// layer white left of the centre and black right of it, the right half stays black (scales - /// below 0 sampled the white half mirrored through the centre). Both Antialiasing settings. + /// below 0 sampled the white half mirrored through the centre). Both Antialiasing settings (the + /// renderer does not read it yet; the test keeps both covered). #[test] fn radial_blur_zoom_at_the_largest_amount_stays_on_its_side_of_the_centre() { let mut img = effectcraft_raster::Image::filled(64, 32, [0.0, 0.0, 0.0, 1.0]); @@ -1169,7 +1170,8 @@ mod tests { } /// Spin and Zoom at both ends of Amount (0..1000) and both Antialiasing settings give finite - /// colours over an opaque layer and keep it opaque (#3467). + /// colours over an opaque layer and keep it opaque (#3467). It guards the newly accepted + /// values; it passed before the Zoom fix too. #[test] fn radial_blur_is_finite_across_the_amount_range() { let mut img = effectcraft_raster::Image::new(48, 40); diff --git a/crates/gpu/src/fx_generate.rs b/crates/gpu/src/fx_generate.rs index 6e9594f60..8833e4d46 100644 --- a/crates/gpu/src/fx_generate.rs +++ b/crates/gpu/src/fx_generate.rs @@ -107,7 +107,7 @@ fn radial_blur(e: &mut Enc, ctx: &EffectCtx, b: GBuf) -> Option { if zoom { data.push(effectcraft_raster::radial_blur_zoom_scale(i, amount) as f32); } else { - let (s, c) = effectcraft_raster::radial_blur_spin_angle(i, amount).to_radians().sin_cos(); + let (s, c) = effectcraft_raster::radial_blur_spin_degrees(i, amount).to_radians().sin_cos(); data.extend([s as f32, c as f32]); } } diff --git a/crates/raster/src/blur.rs b/crates/raster/src/blur.rs index 751e0f5d0..9c9e7ec34 100644 --- a/crates/raster/src/blur.rs +++ b/crates/raster/src/blur.rs @@ -310,14 +310,15 @@ fn radial_blur_t(i: usize) -> f64 { } /// Spin sample `i`'s rotation in degrees for a spin of `amount` degrees. -pub fn radial_blur_spin_angle(i: usize, amount: f64) -> f64 { +pub fn radial_blur_spin_degrees(i: usize, amount: f64) -> f64 { radial_blur_t(i) * amount } /// Zoom sample `i`'s scale about the centre for a zoom of `amount` (a fraction of the distance /// to the centre): evenly over `1 ± amount / 2`. Past a spread of 2 (Radial Blur's Amount 200) /// that would reach below 0 and sample the point mirrored through the centre, so the samples -/// spread evenly from the centre (0) to `1 + amount / 2` instead (#3467). +/// spread evenly from the centre (0) to `1 + |amount| / 2` instead (#3467). That wider shape is +/// EffectCraft's; After Effects has not been measured past Amount 200. pub fn radial_blur_zoom_scale(i: usize, amount: f64) -> f64 { let t = radial_blur_t(i); if amount.abs() <= 2.0 { @@ -342,7 +343,7 @@ pub fn radial_blur(img: &Image, center: (f64, f64), amount: f64, zoom: bool) -> let k = radial_blur_zoom_scale(i, amount); (center.0 + vx * k, center.1 + vy * k) } else { - let (s, c) = radial_blur_spin_angle(i, amount).to_radians().sin_cos(); + let (s, c) = radial_blur_spin_degrees(i, amount).to_radians().sin_cos(); (center.0 + vx * c - vy * s, center.1 + vx * s + vy * c) }; // Samples outside the image repeat its edge: After Effects' Radial Blur keeps a diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 852065db4..58feead1a 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -18,7 +18,7 @@ use effectcraft_color::{BlendMode, blend_pixel}; use rayon::prelude::*; pub use blur::{ - RADIAL_BLUR_SAMPLES, box_blur, directional_blur, gaussian_blur, gaussian_blur_exact, gaussian_is_exact, radial_blur, radial_blur_spin_angle, + RADIAL_BLUR_SAMPLES, box_blur, directional_blur, gaussian_blur, gaussian_blur_exact, gaussian_is_exact, radial_blur, radial_blur_spin_degrees, radial_blur_zoom_scale, }; pub use channels3d::AuxChannels; diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 9d6ca232f..1ef31c413 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -64,7 +64,7 @@ the GPU is performance, not parity. | Date | Change | Summary | |---|---|---| -| 2026-11-17 | minor | Radial Blur: Amount takes After Effects' valid range 0..1000 (slider and default unchanged); Zoom past 200 spreads its samples from the centre outwards instead of sampling the layer mirrored through the centre (CPU and GPU) | +| 2026-11-17 | minor | Radial Blur: Amount takes After Effects' valid range 0..1000 (slider and default unchanged); Zoom past 200 spreads its samples from the centre outwards instead of sampling the layer mirrored through the centre (CPU and GPU; not yet measured against After Effects past Amount 200) | | 2026-11-12 | minor | Parameters take After Effects' recorded valid ranges (hard range; defaults and sliders unchanged): Levels (Individual Controls) levels −10000..10000 and Gamma from 0; 4-Color Gradient Blend to 10000 and Jitter to 500 %; Change Color Hue Transform ±1800°; Noise HLS (and Auto) amounts to 1000 % and Grain Size from 0; Grid Border to 2000; Venetian Blinds Width 1..32000 and Feather to 32000; Radial Wipe Feather to 32000; Scatter Amount to 1000; Beam thicknesses to 4000; Transform Scale ±30000 %; Turbulent Displace Random Seed to 100000. A test checks every mapped parameter's range against the recorded table (CPU and GPU) | | 2026-10-19 | minor | Glow (original colours): bright pass per channel, 8 × (value − threshold + 0.061), measured against After Effects 2026 (CPU and GPU) | | 2026-10-19 | minor | Glow (colour channels): the glow covers the layer's blurred alpha, blur σ = 0.384 × radius, measured against After Effects 2026 renders (CPU and GPU) | From 14d58661902f31a26b688a205a9a45fa34e28b03 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:17:48 +0530 Subject: [PATCH 33/78] #3585: say where the gap revealed above an effect header comes from --- crates/ui-egui/src/panels/effect_controls/panel.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/effect_controls/panel.rs b/crates/ui-egui/src/panels/effect_controls/panel.rs index f89a6eac0..5ced41673 100644 --- a/crates/ui-egui/src/panels/effect_controls/panel.rs +++ b/crates/ui-egui/src/panels/effect_controls/panel.rs @@ -468,7 +468,7 @@ pub fn show(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect) { if let Some(uid) = ctx.data_mut(|d| d.remove_temp::(reveal_id())) && let Some(&(_, top)) = tops.iter().find(|(u, _)| *u == uid) { - // (With the 4-point gap above the first header.) + // (With the 4-point gap above it: the panel starts with one and every effect ends with one.) let top = top - body.min.y + offset; widgets::PanelScroll::reveal(&ctx, egui::Id::unique("ec-scroll"), top - 4.0, top + ROW + 2.0, body.height()); ctx.request_repaint(); From a62564b567befbf3d0f9410cfb553454d5d610b0 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:19:44 +0530 Subject: [PATCH 34/78] #3469: locked pinning clamps without f64::clamp The sub-pixel bounds lx + ix and lx + lw - ix round separately, so at third resolution they can still cross by an ulp and f64::clamp panics; a NaN layer size panicked too. max/min equals clamp whenever the bounds are ordered and cannot panic. The test now covers half and third resolution at fractional offsets and a NaN layer size. The parity note says Amount, not the displacement, is bounded to 2^24 px. --- crates/effects/src/distort2.rs | 19 ++++++++++++------- docs/effects-parity.md | 2 +- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/crates/effects/src/distort2.rs b/crates/effects/src/distort2.rs index 8ca2f2d72..24ffa3ab6 100644 --- a/crates/effects/src/distort2.rs +++ b/crates/effects/src/distort2.rs @@ -124,7 +124,8 @@ fn turbulent_displace(ctx: &EffectCtx, mut b: Buf) -> Buf { let (lx, ly, lw, lh) = layer_rect(ctx, &b); let edge = (lw.min(lh) * if locked { 0.25 } else { 0.1 }).max(1.0); // Locked: samples stay between the outermost pixel centres, or at the centre of a layer under - // a pixel across (half resolution), whose bounds would otherwise cross. + // a pixel across (a reduced resolution). Its bounds may still differ by rounding, so the + // clamp is max/min, which `f64::clamp` would panic on. let (ix, iy) = (0.5f64.min(lw * 0.5), 0.5f64.min(lh * 0.5)); let lock = (lx + ix, lx + lw - ix, ly + iy, ly + lh - iy); let seed = (ctx.seed ^ 0x7d15).wrapping_add((ctx.params.f("evolutionOptions/randomSeed") as i64 as u32).wrapping_mul(0x9e37_79b9)); @@ -173,7 +174,7 @@ fn turbulent_displace(ctx: &EffectCtx, mut b: Buf) -> Buf { }; let (sx, sy) = (x + dx * k, y + dy * k); if locked { - return Some((sx.clamp(lock.0, lock.1), sy.clamp(lock.2, lock.3))); + return Some((sx.max(lock.0).min(lock.1), sy.max(lock.2).min(lock.3))); } Some((sx, sy)) }); @@ -1077,8 +1078,9 @@ mod tests { } } - /// #3469: a locked pinning on a layer under a buffer pixel across (a 1-pixel layer at half - /// resolution) keeps samples inside it without inverted clamp bounds, at any Amount. + /// #3469: a locked pinning on a layer under a buffer pixel across (a 1-pixel layer at half or + /// third resolution, anywhere in the buffer) keeps samples inside it without its rounded + /// bounds crossing, at any Amount. #[test] fn turbulent_displace_locked_pinning_on_a_subpixel_layer_does_not_crash() { let spec = crate::find("ec.distort.turbulentdisplace").unwrap(); @@ -1086,9 +1088,12 @@ mod tests { let mut params = Params { values: spec.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect() }; params.values.insert("amount".into(), num(amount)); params.values.insert("pinning".into(), Value::Enum(8)); - let ctx = EffectCtx { params: ¶ms, time: 0.5, layer_size: [1.0, 1.0], seed: 3, adjustment: false, env: Default::default() }; - let o = crate::apply(spec, &ctx, Buf { img: test_img(1, 1), offset: [0.0, 0.0], scale: 0.5 }); - assert!(o.img.data.iter().all(|p| p.iter().all(|v| v.is_finite())), "{amount}"); + for (size, scale, offset) in [(1.0, 0.5, 0.0), (1.0, 1.0 / 3.0, -8.0), (1.0, 1.0 / 3.0, 7.0), (0.9, 1.0, -8.0), (f64::NAN, 1.0, 0.0)] { + let ctx = EffectCtx { params: ¶ms, time: 0.5, layer_size: [size, size], seed: 3, adjustment: false, env: Default::default() }; + let o = crate::apply(spec, &ctx, Buf { img: test_img(2, 2), offset: [offset, offset], scale }); + // A layer size that is not a number only has to render without panicking. + assert!(size.is_nan() || o.img.data.iter().all(|p| p.iter().all(|v| v.is_finite())), "{amount} {size} {scale} {offset}"); + } } } diff --git a/docs/effects-parity.md b/docs/effects-parity.md index d109da598..870a1ca49 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -64,7 +64,7 @@ the GPU is performance, not parity. | Date | Change | Summary | |---|---|---| -| 2026-11-17 | minor | Turbulent Displace: Amount takes After Effects' recorded valid range, −10000..10000 (default and the −200..200 slider unchanged). Past it (an expression's value) the displacement is bounded to 2^24 px and a NaN Amount leaves the layer unchanged, so padding and sampling stay finite (CPU and GPU). Locked pinning on a layer under a pixel across no longer crashes | +| 2026-11-17 | minor | Turbulent Displace: Amount takes After Effects' recorded valid range, −10000..10000 (default and the −200..200 slider unchanged). Past it (an expression's value) Amount is bounded to 2^24 px and a NaN Amount leaves the layer unchanged, so padding and sampling stay finite (CPU and GPU). Locked pinning on a layer under a pixel across no longer crashes | | 2026-11-12 | minor | Parameters take After Effects' recorded valid ranges (hard range; defaults and sliders unchanged): Levels (Individual Controls) levels −10000..10000 and Gamma from 0; 4-Color Gradient Blend to 10000 and Jitter to 500 %; Change Color Hue Transform ±1800°; Noise HLS (and Auto) amounts to 1000 % and Grain Size from 0; Grid Border to 2000; Venetian Blinds Width 1..32000 and Feather to 32000; Radial Wipe Feather to 32000; Scatter Amount to 1000; Beam thicknesses to 4000; Transform Scale ±30000 %; Turbulent Displace Random Seed to 100000. A test checks every mapped parameter's range against the recorded table (CPU and GPU) | | 2026-10-19 | minor | Glow (original colours): bright pass per channel, 8 × (value − threshold + 0.061), measured against After Effects 2026 (CPU and GPU) | | 2026-10-19 | minor | Glow (colour channels): the glow covers the layer's blurred alpha, blur σ = 0.384 × radius, measured against After Effects 2026 renders (CPU and GPU) | From e60d6ac706ff3aa65c2b1529059b87f1077274f0 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:22:07 +0530 Subject: [PATCH 35/78] #3486: review: the octave test checks the bound; clearer bound comment The octave test asserts both values stay within OCTAVE_SCALE_MAX (it passed with the bound removed). The comment names Perspective Offset as what multiplies the offset by the depth, and says why an octave at the bound has no detail. --- crates/effects/src/noise3.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/effects/src/noise3.rs b/crates/effects/src/noise3.rs index c12ebaa1c..ee0c8103c 100644 --- a/crates/effects/src/noise3.rs +++ b/crates/effects/src/noise3.rs @@ -73,10 +73,10 @@ pub fn sub_scaling_ratio(percent: f64) -> f64 { /// Bound on an octave's frequency and on its Perspective Offset depth (and their inverses). /// Unbounded, at Sub Scaling 10000 and Complexity 20 they would reach 100^±19, and Perspective -/// Offset or Turbulence Factor multiplying the offset by the depth overflowed to infinity (NaN -/// noise, #3486). Sub Scaling 10..100 never reaches the bound (10^19 at most). Both stay each -/// other's inverse inside it, so an octave's offset in lattice cells is unchanged; an octave this -/// far out is a constant (or sub-pixel noise) across any layer either way. +/// Offset multiplying the offset by the depth (and by Turbulence Factor's drift) overflowed to +/// infinity (NaN noise, #3486). Sub Scaling 10..100 never reaches the bound (10^19 at most). Both +/// stay each other's inverse inside it, so an octave's offset in lattice cells is unchanged; at a +/// frequency of 1e-20 an octave spans under 1e-12 cells of any layer, so it has no detail either way. pub const OCTAVE_SCALE_MAX: f32 = 1e20; /// Bound on an octave's scaled Offset Turbulence in pixels, so a huge offset times the depth stays @@ -532,7 +532,8 @@ mod tests { for _ in 0..19 { (f, depth) = next_octave(f, depth, s); (f0, d0) = (f0 / s, d0 * s); - assert!(f.is_finite() && depth.is_finite() && f > 0.0 && depth > 0.0, "{s}: {f} {depth}"); + let lo = 1.0 / OCTAVE_SCALE_MAX; + assert!((lo..=OCTAVE_SCALE_MAX).contains(&f) && (lo..=OCTAVE_SCALE_MAX).contains(&depth), "{s}: {f} {depth}"); assert!((f * depth - 1.0).abs() < 1e-3, "{s}: {f} × {depth}"); if s <= 1.0 { assert_eq!((f, depth), (f0, d0), "{s}"); From 89030900074f47eacf96fdbb82e41aed7eec662f Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:08:36 +0530 Subject: [PATCH 36/78] #3464: Drop Shadow: keep the whole blur when the padding budget cuts the margin Drop Shadow pads its buffer by Distance + 1.5 x Softness, but the pixel budget (#2261) cuts that margin for a large Softness: from about 870 on a 1080p layer. The box passes then dropped what they spread past the edge, so the shadow came out too faint: at the centre of a 64 x 48 layer, 0.11 of the Gaussian at Softness 8000. With a cut margin the CPU now blurs as if the buffer went on with transparency (the Gaussian is unchanged, sigma = Softness / 2). The GPU hands that case to the CPU and keeps every margin that fits, so those results are unchanged. Measured on an M-series Mac: 1080p at Softness 30000 takes 0.10 s, and a 4096 x 4096 layer (an 8192 x 8192 buffer) takes 0.99 s on the CPU. The pad is computed once for both paths (drop_shadow_pad) and saturates instead of overflowing on a huge Softness. --- crates/effects/src/lib.rs | 4 ++-- crates/effects/src/misc.rs | 44 +++++++++++++++++++++++++++++++++++--- crates/gpu/src/effects.rs | 6 +++++- crates/gpu/src/tests.rs | 33 ++++++++++++++++++++++++++++ 4 files changed, 81 insertions(+), 6 deletions(-) diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 5da2035ac..13bd8bf93 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -92,8 +92,8 @@ use effectcraft_project::build::Ids; use effectcraft_project::{GroupKind, ParamUi, PropGroup, Property}; pub use effectcraft_raster::{AuxChannels, Image}; pub use misc::{ - GLOW_GAIN, GLOW_KNEE, INVERT_ALPHA, INVERT_CHANNELS, glow_ab_t, glow_operation, glow_sigma, linear_wipe_axis, linear_wipe_sigma, radial_wipe_sigma, - radial_wipe_wedge, venetian_cover, venetian_origin, + GLOW_GAIN, GLOW_KNEE, INVERT_ALPHA, INVERT_CHANNELS, drop_shadow_pad, glow_ab_t, glow_operation, glow_sigma, linear_wipe_axis, linear_wipe_sigma, + radial_wipe_sigma, radial_wipe_wedge, venetian_cover, venetian_origin, }; pub use sim::particle_state; pub use sim3::{PgBlit, PgPlan, playground_plan, playground_state}; diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index 9c7131657..7e5f5c1c6 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -3,7 +3,7 @@ use effectcraft_color::luminance; use effectcraft_keyframe::Value; use effectcraft_project::ParamUi; -use effectcraft_raster::{Image, gaussian_blur, hash_noise}; +use effectcraft_raster::{Image, gaussian_blur, gaussian_blur_unbounded, hash_noise}; use rayon::prelude::*; use crate::{Buf, EffectCtx, EffectSpec, col, num, p, popup, slider}; @@ -283,6 +283,12 @@ fn glow(ctx: &EffectCtx, mut b: Buf) -> Buf { b } +/// The margin Drop Shadow asks for around a layer: its Distance and its blur's reach (three +/// boxes of radius about σ = Softness / 2), both in buffer pixels. Shared with the GPU path. +pub fn drop_shadow_pad(dist: f64, soft: f64) -> u32 { + ((dist + soft * 1.5).ceil() as u32).saturating_add(2) +} + fn drop_shadow(ctx: &EffectCtx, mut b: Buf) -> Buf { let color = ctx.params.color("color"); let opacity = ctx.params.f("opacity") as f32 / 100.0; @@ -290,9 +296,17 @@ fn drop_shadow(ctx: &EffectCtx, mut b: Buf) -> Buf { let dist = ctx.params.f("distance") * b.scale; let soft = ctx.params.f("softness") * b.scale; let only = ctx.params.b("shadowOnly"); - let pad = (dist + soft * 1.5).ceil() as u32 + 2; + let pad = drop_shadow_pad(dist, soft); + // Whether the buffer holds the whole blur. The pixel budget (#2261) cuts the margin of a + // large Softness (After Effects' range reaches 30000, #3464); the blur then goes on past the + // buffer's edge rather than dropping what reaches it, which would leave the shadow far too + // faint. An adjustment layer's buffer is the composition, as before. + let mut holds_blur = true; if !ctx.adjustment { + let (w0, h0) = (b.img.width, b.img.height); b.pad(pad); + let need = pad.saturating_mul(2); + holds_blur = b.img.width.saturating_sub(w0) >= need && b.img.height.saturating_sub(h0) >= need; } let (dx, dy) = (dir.sin() * dist, -dir.cos() * dist); let mut sh = Image::new(b.img.width, b.img.height); @@ -304,7 +318,7 @@ fn drop_shadow(ctx: &EffectCtx, mut b: Buf) -> Buf { } }); if soft > 0.0 { - sh = gaussian_blur(&sh, soft / 2.0, soft / 2.0, false); + sh = if holds_blur { gaussian_blur(&sh, soft / 2.0, soft / 2.0, false) } else { gaussian_blur_unbounded(&sh, soft / 2.0, soft / 2.0) }; } if !only { sh.data.par_iter_mut().zip(b.img.data.par_iter()).for_each(|(s, o)| { @@ -1036,6 +1050,30 @@ mod tests { assert_ne!(row(2.0), row(2.4)); } + /// #3464: past the padding budget (#2261) the shadow keeps its whole blur (σ = Softness / 2) + /// up to the buffer's edge. A 64 × 48 layer's shadow at its centre is the Gaussian's share + /// of the layer, less the 6 % three boxes' peak is under a Gaussian's; dropping what the + /// boxes spread past the buffer left it at 0.2 of that at 8000 and 0.001 at 30000. + #[test] + fn drop_shadow_keeps_its_blur_past_the_padding_budget() { + let (w, h) = (64u32, 48u32); + for softness in [500.0, 4000.0, 8000.0, 30000.0] { + let layer = effectcraft_raster::Image::filled(w, h, [1.0, 1.0, 1.0, 1.0]); + let vals = [("softness", num(softness)), ("opacity", num(100.0)), ("distance", num(0.0)), ("shadowOnly", Value::Bool(true))]; + let out = run_fx("ec.perspective.dropshadow", &vals, layer, 0.0, EffectEnv::default()); + assert!(out.img.data.iter().flatten().all(|v| v.is_finite()), "softness {softness}"); + let sigma = softness / 2.0; + let share = |len: u32| { + let sum: f64 = (0..len).map(|i| (-((f64::from(i) + 0.5 - f64::from(len) / 2.0) / sigma).powi(2) / 2.0).exp()).sum(); + sum / (sigma * (2.0 * std::f64::consts::PI).sqrt()) + }; + let want = share(w) * share(h); + let at = |v: f64, half: u32| (v + f64::from(half)) as i64; + let got = f64::from(out.img.get(at(out.offset[0], w / 2), at(out.offset[1], h / 2))[3]); + assert!((0.85..1.02).contains(&(got / want)), "softness {softness}: centre alpha {got}, Gaussian {want}"); + } + } + #[test] fn fractional_box_blur_radius_is_continuous() { let row = |v| blurred_row("ec.blur.fastbox", "radius", v); diff --git a/crates/gpu/src/effects.rs b/crates/gpu/src/effects.rs index fd5a97c38..8bbae69c4 100644 --- a/crates/gpu/src/effects.rs +++ b/crates/gpu/src/effects.rs @@ -411,8 +411,12 @@ fn drop_shadow(e: &mut Enc, ctx: &EffectCtx, mut b: GBuf) -> Option { let dist = ctx.params.f("distance") * b.scale; let soft = ctx.params.f("softness") * b.scale; let only = ctx.params.b("shadowOnly"); - let pad = (dist + soft * 1.5).ceil() as u32 + 2; + let pad = effectcraft_effects::drop_shadow_pad(dist, soft); if !ctx.adjustment { + // A margin cut to the pixel budget: the CPU blurs on past the buffer's edge (#3464). + if soft > 0.0 && effectcraft_effects::pad_within_budget(b.img.width, b.img.height, pad) < pad { + return None; + } b.pad(e, pad)?; } let (dx, dy) = (dir.sin() * dist, -dir.cos() * dist); diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 1d2782262..0959aa4de 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -760,6 +760,39 @@ fn box_blur_horizontal_rows_match_cpu_beyond_256() { } } +/// #3464: Drop Shadow's Softness reaches 30000. While the padded buffer holds the blur the GPU +/// runs it (1000, the old maximum, on a 70 × 44 layer); once the pixel budget cuts the padding +/// the CPU blurs past the buffer's edge, so the GPU hands the effect over and the render still +/// matches, with and without Shadow Only. +#[test] +fn drop_shadow_large_softness_matches_cpu() { + effect_case("ec.perspective.dropshadow", &[("distance", n(6.0)), ("softness", n(1000.0)), ("opacity", n(100.0))]); + let Some(g) = gpu() else { return }; + for only in [false, true] { + let vals = [("distance", n(6.0)), ("softness", n(30000.0)), ("opacity", n(100.0)), ("shadowOnly", Value::Bool(only))]; + let spec = effectcraft_effects::find("ec.perspective.dropshadow").unwrap(); + let mut params = effectcraft_effects::Params { + values: spec.params.iter().map(|ps| (ps.id.to_string(), effectcraft_effects::default_value(ps, [70.0, 44.0]))).collect(), + }; + for (k, v) in &vals { + params.values.insert(k.to_string(), v.clone()); + } + let ctx = effectcraft_effects::EffectCtx { params: ¶ms, time: 0.0, layer_size: [70.0, 44.0], seed: 11, adjustment: false, env: Default::default() }; + let buf = effectcraft_effects::Buf { img: pattern(7, 70, 44), offset: [0.0, 0.0], scale: 1.0 }; + let step = effectcraft_render::FxStep { spec, ctx }; + assert!(effectcraft_render::Accelerator::effects(g, &[step], &buf, None).is_none(), "the GPU hands a cut margin to the CPU"); + for depth in [BitDepth::Bpc8, BitDepth::Bpc32] { + let mut s = Scene::new(depth); + let bg = s.solid([0.15, 0.1, 0.2], 97, 61); + s.push(bg); + let mut l = s.footage(70, 44); + s.effect(&mut l, "ec.perspective.dropshadow", &vals); + s.push(l); + check(&format!("drop shadow 30000 only {only} {depth:?}"), compare_at(&s, opts(), Tick::ZERO), 0.0); + } + } +} + #[test] fn gpu_effects_match_cpu() { // Sigma 3 px and up and even radii, so the half-scale pass stays on the GPU too (#1939). From f149b65c579d796c46ddfd0b975a7c1a7eb6a311 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:11:46 +0530 Subject: [PATCH 37/78] #3464: Drop Shadow: Softness takes After Effects' range Softness took 0..1000, so prop.set and the value editors clamped values After Effects accepts: its recorded definition for ADBE Drop Shadow allows 0..30000 in the same pixels (the .aep mapping is plain). The hard range is now 0..30000; the default (0) and the slider (0..250) are unchanged. Projects saved with the old range take the new one on open. The .aep range guard loses its allow-list row, and the engine test sets both ends through prop.set, undo / redo, save / reopen and an old project. Keyframe text keeps no unit for it (only 0..100 sliders read as percent). --- crates/aep/src/export/fx_defs.rs | 1 - crates/effects/src/misc.rs | 10 +++++++++- crates/engine/src/tests/effect_ranges.rs | 1 + docs/effects-parity.md | 1 + 4 files changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index 338e00fc5..dd67bd493 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -727,7 +727,6 @@ mod tests { ("ec.blur.channel", "blueBlurriness", 3462), ("ec.blur.channel", "alphaBlurriness", 3462), ("ec.obsolete.gaussianlegacy", "blurriness", 3463), - ("ec.perspective.dropshadow", "softness", 3464), ("ec.blur.compound", "maximumBlur", 3465), ("ec.blur.sharpen", "amount", 3466), ("ec.blur.radial", "amount", 3467), diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index 7e5f5c1c6..f56310ece 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -885,7 +885,7 @@ pub fn specs() -> Vec { p("opacity", "Opacity", num(50.0), slider(0.0, 100.0, 0.0, 100.0, 0)), p("direction", "Direction", num(135.0), ParamUi::Angle), p("distance", "Distance", num(5.0), slider(0.0, 32000.0, 0.0, 120.0, 1)), - p("softness", "Softness", num(0.0), slider(0.0, 1000.0, 0.0, 250.0, 1)), + p("softness", "Softness", num(0.0), slider(0.0, 30000.0, 0.0, 250.0, 1)), p("shadowOnly", "Shadow Only", Value::Bool(false), ParamUi::Checkbox), ], drop_shadow, @@ -1050,6 +1050,14 @@ mod tests { assert_ne!(row(2.0), row(2.4)); } + /// #3464: Softness takes After Effects' valid range, 0..30000; the slider still shows 0..250. + #[test] + fn drop_shadow_softness_takes_the_after_effects_range() { + let spec = crate::find("ec.perspective.dropshadow").unwrap(); + let ui = &spec.params.iter().find(|p| p.id == "softness").unwrap().ui; + assert_eq!(*ui, slider(0.0, 30000.0, 0.0, 250.0, 1)); + } + /// #3464: past the padding budget (#2261) the shadow keeps its whole blur (σ = Softness / 2) /// up to the buffer's edge. A 64 × 48 layer's shadow at its centre is the Gaussian's share /// of the layer, less the 6 % three boxes' peak is under a Gaussian's; dropping what the diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index 7deaaa911..1e2eb5fac 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -60,6 +60,7 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3471, "ec.distort.transform", "scaleHeight", -30000.0, 30000.0), (3471, "ec.distort.transform", "scaleWidth", -30000.0, 30000.0), (3470, "ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 0.0, 100000.0), + (3464, "ec.perspective.dropshadow", "softness", 0.0, 30000.0), ]; fn path(effect: &str, param: &str) -> String { diff --git a/docs/effects-parity.md b/docs/effects-parity.md index b07c624f8..a7f1d6afb 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -64,6 +64,7 @@ the GPU is performance, not parity. | Date | Change | Summary | |---|---|---| +| 2026-11-17 | minor | Drop Shadow: Softness takes After Effects' recorded valid range, 0..30000 (default and 0..250 slider unchanged). Past the padding budget the shadow keeps its blur (σ = Softness / 2) and is cut at the buffer's edge (CPU and GPU) | | 2026-11-12 | minor | Parameters take After Effects' recorded valid ranges (hard range; defaults and sliders unchanged): Levels (Individual Controls) levels −10000..10000 and Gamma from 0; 4-Color Gradient Blend to 10000 and Jitter to 500 %; Change Color Hue Transform ±1800°; Noise HLS (and Auto) amounts to 1000 % and Grain Size from 0; Grid Border to 2000; Venetian Blinds Width 1..32000 and Feather to 32000; Radial Wipe Feather to 32000; Scatter Amount to 1000; Beam thicknesses to 4000; Transform Scale ±30000 %; Turbulent Displace Random Seed to 100000. A test checks every mapped parameter's range against the recorded table (CPU and GPU) | | 2026-10-19 | minor | Glow (original colours): bright pass per channel, 8 × (value − threshold + 0.061), measured against After Effects 2026 (CPU and GPU) | | 2026-10-19 | minor | Glow (colour channels): the glow covers the layer's blurred alpha, blur σ = 0.384 × radius, measured against After Effects 2026 renders (CPU and GPU) | From 0bd722b1a5365b5ab54c4f8ac2609b936d9b5936 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:24:11 +0530 Subject: [PATCH 38/78] #3464: raster: unbounded blur skips zero radii and caps sigma A zero-radius box is an identity, but as a difference of prefix sums it kept their rounding error; those boxes are now left out (one to three boxes, of the matching prefix-sum order). A sigma above 1e7 blurs as 1e7, wider than any buffer, so box_radii's i64 arithmetic can't overflow on a huge or infinite sigma. --- crates/raster/src/blur.rs | 109 +++++++++++++++++++++++--------------- 1 file changed, 66 insertions(+), 43 deletions(-) diff --git a/crates/raster/src/blur.rs b/crates/raster/src/blur.rs index e8e98281a..6ca4aa174 100644 --- a/crates/raster/src/blur.rs +++ b/crates/raster/src/blur.rs @@ -194,14 +194,14 @@ pub fn gaussian_blur_unbounded(img: &Image, sigma_x: f64, sigma_y: f64) -> Image return out; } if let Some(r) = unbounded_radii(sigma_x) { - out.data.par_chunks_mut(w).for_each(|row| boxes_unbounded(row, r)); + out.data.par_chunks_mut(w).for_each(|row| boxes_unbounded(row, &r)); } if let Some(r) = unbounded_radii(sigma_y) { let cols: Vec> = (0..w) .into_par_iter() .map(|x| { let mut col: Vec = out.data.iter().skip(x).step_by(w).copied().collect(); - boxes_unbounded(&mut col, r); + boxes_unbounded(&mut col, &r); col }) .collect(); @@ -216,65 +216,71 @@ pub fn gaussian_blur_unbounded(img: &Image, sigma_x: f64, sigma_y: f64) -> Image out } -/// [`gaussian_blur`]'s three box radii for `sigma`, or `None` where it doesn't blur (and for -/// a sigma that isn't finite). -fn unbounded_radii(sigma: f64) -> Option<[i64; 3]> { - if !(sigma > 0.05 && sigma.is_finite()) { +/// Above this sigma (pixels) [`gaussian_blur_unbounded`] blurs as if it were this: far wider +/// than any buffer ([`crate::MAX_PADDED_SIDE`]), and small enough for [`box_radii`]'s `i64` +/// arithmetic (which overflows near 9e8). +const UNBOUNDED_SIGMA_MAX: f64 = 1e7; + +/// [`gaussian_blur`]'s box radii for `sigma` without the zero ones (each an identity), or +/// `None` where it doesn't blur (and for a sigma that isn't a number). +fn unbounded_radii(sigma: f64) -> Option> { + if sigma.is_nan() || sigma <= 0.05 { return None; } - match box_radii(sigma, 3).as_slice() { - &[a, b, c] => Some([a, b, c].map(|r| i64::try_from(r).unwrap_or(i64::MAX / 8))), - _ => None, - } + let radii: Vec = box_radii(sigma.min(UNBOUNDED_SIGMA_MAX), 3).into_iter().filter_map(|r| i64::try_from(r).ok()).filter(|&r| r > 0).collect(); + (!radii.is_empty()).then_some(radii) } -/// Three transparent-edged box passes of radii `r` over `line`, as if it went on with zeros. +/// Transparent-edged box passes of radii `r` (one to three, none zero) over `line`, as if it +/// went on with zeros. /// -/// One box is a difference of prefix sums, `(S(x + r) − S(x − r − 1)) / (2r + 1)`, so three are -/// eight signed terms of the third prefix sum `S3`. Past the line's ends the prefix sums are -/// polynomials: `S3(m) = 0` before it, and after it, `j = m − n + 1` steps on, -/// `S3(m) = S3(n − 1) + j·S2(n − 1) + T·j(j + 1)/2` with `T` the line's total. The sums are -/// `f64`: the eight terms cancel to a value `(2r + 1)³` times smaller. -fn boxes_unbounded(line: &mut [Px], r: [i64; 3]) { - let n = line.len(); +/// One box is a difference of prefix sums, `(S(x + r) − S(x − r − 1)) / (2r + 1)`, so `k` boxes +/// are `2^k` signed terms of the `k`-th prefix sum `Sk`. Before the line every `Sk` is 0; past +/// it, `j = m − n + 1` steps on with `T` the line's total, they are polynomials: +/// `S1(m) = T`, `S2(m) = S2(n − 1) + j·T`, `S3(m) = S3(n − 1) + j·S2(n − 1) + T·j(j + 1)/2`. +/// The sums are `f64`. `Sk` grows like `n^k`, so the cancelling terms leave a rounding error +/// near `ε·n^k / (2r + 1)^k` of the values: under 1e-8 for any line a blur too wide for its +/// buffer runs on. +fn boxes_unbounded(line: &mut [Px], r: &[i64]) { + let (n, k) = (line.len(), r.len()); let Ok(n_i) = i64::try_from(n) else { return }; - if n == 0 { + if n == 0 || !(1..=3).contains(&k) { return; } - let mut s3 = Vec::with_capacity(n); - let (mut s1, mut s2, mut acc) = ([0.0f64; 4], [0.0f64; 4], [0.0f64; 4]); + // sums[o] = the (o + 1)-th prefix sum so far. + let mut sums = [[0.0f64; 4]; 3]; + let mut sk = Vec::with_capacity(n); for p in line.iter() { for c in 0..4 { - s1[c] += f64::from(p[c]); - s2[c] += s1[c]; - acc[c] += s2[c]; + sums[0][c] += f64::from(p[c]); + sums[1][c] += sums[0][c]; + sums[2][c] += sums[1][c]; } - s3.push(acc); + sk.push(sums[k - 1]); } - let (total, s2_end, s3_end) = (s1, s2, acc); let at = |m: i64| -> [f64; 4] { if m < 0 { return [0.0; 4]; } - if let Some(v) = usize::try_from(m).ok().and_then(|i| s3.get(i)) { + if let Some(v) = usize::try_from(m).ok().and_then(|i| sk.get(i)) { return *v; } let j = (m - n_i + 1) as f64; - std::array::from_fn(|c| s3_end[c] + j * s2_end[c] + total[c] * j * (j + 1.0) / 2.0) + std::array::from_fn(|c| match k { + 1 => sums[0][c], + 2 => sums[1][c] + j * sums[0][c], + _ => sums[2][c] + j * sums[1][c] + sums[0][c] * j * (j + 1.0) / 2.0, + }) }; - // The eight shifts and signs: each box adds `S(x + r)` and subtracts `S(x − r − 1)`. - let mut terms = [(0i64, 1.0f64); 8]; - for (k, t) in terms.iter_mut().enumerate() { - for (b, &ri) in r.iter().enumerate() { - if k >> b & 1 == 0 { - t.0 = t.0.saturating_add(ri); - } else { - t.0 = t.0.saturating_sub(ri.saturating_add(1)); - t.1 = -t.1; - } - } - } - let norm: f64 = r.iter().map(|&ri| (2 * ri + 1) as f64).product(); + // The shifts and signs: each box adds `S(x + r)` and subtracts `S(x − r − 1)`. + let terms: Vec<(i64, f64)> = (0..1usize << k) + .map(|bits| { + r.iter().enumerate().fold((0i64, 1.0f64), |(shift, sign), (b, &ri)| { + if bits >> b & 1 == 0 { (shift.saturating_add(ri), sign) } else { (shift.saturating_sub(ri.saturating_add(1)), -sign) } + }) + }) + .collect(); + let norm: f64 = r.iter().map(|&ri| 2.0 * ri as f64 + 1.0).product(); for (x, o) in (0i64..).zip(line.iter_mut()) { let mut v = [0.0f64; 4]; for &(shift, sign) in &terms { @@ -626,6 +632,20 @@ mod tests { assert!(r.iter().all(|&v| (7..=10).contains(&v)), "{r:?}"); } + /// #3464: a sigma past any buffer, or infinite, blurs as the widest one does: finite, no + /// overflow in the radii. A NaN sigma leaves the axis alone. + #[test] + fn unbounded_gaussian_takes_any_sigma() { + let mut img = Image::new(9, 7); + img.set(4, 3, [1.0, 0.5, 0.25, 1.0]); + let wide = gaussian_blur_unbounded(&img, 1e7, 1e7); + for (sx, sy) in [(f64::INFINITY, f64::INFINITY), (1e300, 1e12)] { + assert_eq!(gaussian_blur_unbounded(&img, sx, sy).data, wide.data, "σ ({sx}, {sy})"); + } + assert!(wide.data.iter().flatten().all(|v| v.is_finite())); + assert_eq!(gaussian_blur_unbounded(&img, f64::NAN, f64::NAN).data, img.data); + } + /// #3464: [`gaussian_blur_unbounded`] is [`gaussian_blur`] on the image padded with enough /// transparency to hold every pass, cropped back: what a pass spreads past the edge comes /// back in the passes after it. Sigmas far wider than the image too, along each axis. @@ -644,8 +664,11 @@ mod tests { (pattern(23, 17), 0.0, 6.0, 1e-4), (pattern(23, 17), 7.5, 3.2, 1e-4), (pattern(23, 17), 60.0, 45.0, 1e-4), - // The reference's f32 running sums drift over its 90 000-pixel line (by 1.5e-4 of - // the value against an f64 evaluation, which this matches to 1e-9). + // Zero radii (an identity) and one non-zero box among them. + (pattern(23, 17), 0.5, 0.0, 1e-6), + (pattern(23, 17), 0.0, 1.1, 1e-5), + // The reference's f32 running sums drift over its 90 000-pixel line (by about 1.5e-4 + // of the value). (pattern(40, 1), 15000.0, 0.0, 1e-3), (pattern(1, 40), 0.0, 15000.0, 1e-3), ]; From cec04744f34947165df1b7fe2748f72da686f567 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:24:11 +0530 Subject: [PATCH 39/78] #3464: Drop Shadow: test a huge Softness; say what the GPU test checks A Softness far past the range (an expression can set one) overflowed the padding's u32 before drop_shadow_pad saturated it; the new test panicked there in a debug build and renders a finite shadow now. The GPU test's comment and the parity row now say that a cut margin renders on the CPU, and the CPU test quotes the measured 0.11 at Softness 8000. --- crates/effects/src/misc.rs | 13 ++++++++++++- crates/gpu/src/tests.rs | 6 +++--- docs/effects-parity.md | 2 +- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index f56310ece..660cee46a 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -1058,10 +1058,21 @@ mod tests { assert_eq!(*ui, slider(0.0, 30000.0, 0.0, 250.0, 1)); } + /// #3464: a Softness far past the range (an expression can set one) used to overflow the + /// padding's `u32` (a panic in debug builds). It renders, finite. + #[test] + fn drop_shadow_takes_a_huge_softness() { + for softness in [1e12, f64::INFINITY] { + let layer = effectcraft_raster::Image::filled(8, 8, [1.0, 1.0, 1.0, 1.0]); + let out = run_fx("ec.perspective.dropshadow", &[("softness", num(softness))], layer, 0.0, EffectEnv::default()); + assert!(out.img.data.iter().flatten().all(|v| v.is_finite()), "softness {softness}"); + } + } + /// #3464: past the padding budget (#2261) the shadow keeps its whole blur (σ = Softness / 2) /// up to the buffer's edge. A 64 × 48 layer's shadow at its centre is the Gaussian's share /// of the layer, less the 6 % three boxes' peak is under a Gaussian's; dropping what the - /// boxes spread past the buffer left it at 0.2 of that at 8000 and 0.001 at 30000. + /// boxes spread past the buffer left it at 0.11 of that at 8000. #[test] fn drop_shadow_keeps_its_blur_past_the_padding_budget() { let (w, h) = (64u32, 48u32); diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 0959aa4de..09bc226c7 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -761,9 +761,9 @@ fn box_blur_horizontal_rows_match_cpu_beyond_256() { } /// #3464: Drop Shadow's Softness reaches 30000. While the padded buffer holds the blur the GPU -/// runs it (1000, the old maximum, on a 70 × 44 layer); once the pixel budget cuts the padding -/// the CPU blurs past the buffer's edge, so the GPU hands the effect over and the render still -/// matches, with and without Shadow Only. +/// runs it and matches the CPU (1000, the old maximum, on a 70 × 44 layer). Once the pixel +/// budget cuts the padding only the CPU blurs past the buffer's edge, so the GPU declines the +/// effect; the render then takes it on the CPU at 8 and 32 bpc, with and without Shadow Only. #[test] fn drop_shadow_large_softness_matches_cpu() { effect_case("ec.perspective.dropshadow", &[("distance", n(6.0)), ("softness", n(1000.0)), ("opacity", n(100.0))]); diff --git a/docs/effects-parity.md b/docs/effects-parity.md index a7f1d6afb..9ab7601bd 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -64,7 +64,7 @@ the GPU is performance, not parity. | Date | Change | Summary | |---|---|---| -| 2026-11-17 | minor | Drop Shadow: Softness takes After Effects' recorded valid range, 0..30000 (default and 0..250 slider unchanged). Past the padding budget the shadow keeps its blur (σ = Softness / 2) and is cut at the buffer's edge (CPU and GPU) | +| 2026-11-17 | minor | Drop Shadow: Softness takes After Effects' recorded valid range, 0..30000 (default and 0..250 slider unchanged). Where the padding budget cuts the margin, the shadow keeps its full blur (σ = Softness / 2) up to the buffer's edge, where it is cut; that case renders on the CPU | | 2026-11-12 | minor | Parameters take After Effects' recorded valid ranges (hard range; defaults and sliders unchanged): Levels (Individual Controls) levels −10000..10000 and Gamma from 0; 4-Color Gradient Blend to 10000 and Jitter to 500 %; Change Color Hue Transform ±1800°; Noise HLS (and Auto) amounts to 1000 % and Grain Size from 0; Grid Border to 2000; Venetian Blinds Width 1..32000 and Feather to 32000; Radial Wipe Feather to 32000; Scatter Amount to 1000; Beam thicknesses to 4000; Transform Scale ±30000 %; Turbulent Displace Random Seed to 100000. A test checks every mapped parameter's range against the recorded table (CPU and GPU) | | 2026-10-19 | minor | Glow (original colours): bright pass per channel, 8 × (value − threshold + 0.061), measured against After Effects 2026 (CPU and GPU) | | 2026-10-19 | minor | Glow (colour channels): the glow covers the layer's blurred alpha, blur σ = 0.384 × radius, measured against After Effects 2026 renders (CPU and GPU) | From 969286ae7615bb4c1fc13ad7768b8f2a8074bace Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 16:52:08 +0530 Subject: [PATCH 40/78] #3460: review: name the open follow-up for SLIDERS_0_24, use the shared pixel budget in the test The table holds only Gaussian Blur's row; the ranges changed since 0.24.1 by other work are tracked in #3815. The 30000 render test checks the buffer against crate::pixel_budget instead of a copied constant. --- crates/effects/src/misc.rs | 2 +- crates/engine/src/analysis/frames_key/legacy.rs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index 11a273888..08c2c5a73 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -1044,7 +1044,7 @@ mod tests { for repeat in [false, true] { let out = run_fx("ec.blur.gaussian", &[("blurriness", num(30000.0)), ("repeatEdge", Value::Bool(repeat))], edge(), 0.0, EffectEnv::default()); let (w, h) = (out.img.width, out.img.height); - assert!(u64::from(w) * u64::from(h) <= 16_777_216, "repeat {repeat}: {w} x {h}"); + assert!(f64::from(w) * f64::from(h) <= crate::pixel_budget(40.0, 8.0), "repeat {repeat}: {w} x {h}"); assert!(out.img.data.iter().flatten().all(|v| v.is_finite()), "repeat {repeat}"); if repeat { assert_eq!((w, h), (40, 8)); diff --git a/crates/engine/src/analysis/frames_key/legacy.rs b/crates/engine/src/analysis/frames_key/legacy.rs index 4b1b090a5..f3403b309 100644 --- a/crates/engine/src/analysis/frames_key/legacy.rs +++ b/crates/engine/src/analysis/frames_key/legacy.rs @@ -47,11 +47,12 @@ pub(crate) fn input_key_of(mut s: String, layer: &Layer, uid: Uid) -> String { format!("{:016x}", fnv(&s)) } -/// The slider ranges 0.22–0.24 gave effect parameters whose range has changed since, as +/// Slider ranges as 0.22–0.24 gave them, for parameters whose range has changed since, as /// (effect, parameter path, [min, max, slider min, slider max], decimals). Those releases hashed /// each effect's UI hints into the Roto Brush Input Key, and opening a project replaces an /// instance's hints with the current ones, so [`effect_text`] puts these back. A range change /// above a Roto Brush would otherwise drop the analysis such a key kept: add a row with it. +/// Not every range changed since 0.24.1 has its row yet (#3815). #[rustfmt::skip] const SLIDERS_0_24: &[(&str, &str, [f64; 4], u8)] = &[ ("ec.blur.gaussian", "blurriness", [0.0, 3000.0, 0.0, 50.0], 1), From ae2d595d9df799e8e8ed4545e38385fb809bbeca Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 17:25:47 +0530 Subject: [PATCH 41/78] fix(effects): exercise the wrapped combined cube row count --- crates/effects/src/utility.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/effects/src/utility.rs b/crates/effects/src/utility.rs index b38ded8db..171b9cc8e 100644 --- a/crates/effects/src/utility.rs +++ b/crates/effects/src/utility.rs @@ -483,7 +483,7 @@ mod tests { // A hostile size must be rejected, not overflow `n3^3` or `n1 + n3^3`. assert!(parse_cube("LUT_3D_SIZE 4294967296\n0 0 0\n").is_none()); assert!(parse_cube(&format!("LUT_3D_SIZE {}\n0 0 0\n", usize::MAX)).is_none()); - assert!(parse_cube(&format!("LUT_1D_SIZE {}\nLUT_3D_SIZE 2\n0 0 0\n", usize::MAX)).is_none()); + assert!(parse_cube(&format!("LUT_1D_SIZE {}\nLUT_3D_SIZE 2\n{}", usize::MAX, "0 0 0\n".repeat(7))).is_none()); let img = test_img(); let out = run("ec.utility.applylut", &[("lut", Value::Str("LUT_3D_SIZE 3\n0 0 0\n".into()))], img.clone()); assert_eq!(out.img, img); From 1eb4f39808e7f3e2855e787d69ffad528b576b3b Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 17:27:22 +0530 Subject: [PATCH 42/78] fix(effects): bound cube data row collection --- crates/effects/src/utility.rs | 38 ++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/effects/src/utility.rs b/crates/effects/src/utility.rs index 171b9cc8e..ff8ff208d 100644 --- a/crates/effects/src/utility.rs +++ b/crates/effects/src/utility.rs @@ -169,6 +169,10 @@ pub struct Lut { pub dmax: [f32; 3], } +// Cube LUT Specification 1.0 §§6–7 permits at most 65,536 1D rows and a 256³ +// lattice. Allow their sum for combined shaper + 3D files, regardless of header order. +const MAX_CUBE_ROWS: usize = 65_536 + 256 * 256 * 256; + /// Parse `.cube` text (TITLE, LUT_1D_SIZE, LUT_3D_SIZE, DOMAIN_MIN/MAX, data red-fastest). pub fn parse_cube(text: &str) -> Option { let mut lut = Lut { n1: 0, d1: vec![], n3: 0, d3: vec![], dmin: [0.0; 3], dmax: [1.0; 3] }; @@ -212,7 +216,14 @@ pub fn parse_cube(text: &str) -> Option { lut.dmax = [hi; 3]; } k if k.starts_with(|c: char| c.is_ascii_alphabetic()) => continue, - _ => rows.push(three(&mut it)?), + _ => { + if rows.len() == MAX_CUBE_ROWS { + return None; + } + let row = three(&mut it)?; + rows.try_reserve(1).ok()?; + rows.push(row); + } } } if lut.n3 > 256 { @@ -223,8 +234,8 @@ pub fn parse_cube(text: &str) -> Option { if (lut.n1 == 0 && lut.n3 == 0) || lut.n1 == 1 || lut.n3 == 1 || Some(rows.len()) != need1.checked_add(need3) { return None; } - lut.d1 = rows[..need1].to_vec(); - lut.d3 = rows[need1..].to_vec(); + lut.d1 = rows.get(..need1)?.to_vec(); + lut.d3 = rows.get(need1..)?.to_vec(); Some(lut) } @@ -491,6 +502,27 @@ mod tests { assert_eq!(out.img, img); } + #[test] + fn cube_accepts_maximum_1d_shaper_with_3d_table() { + let text = format!("LUT_1D_SIZE 65536\nLUT_3D_SIZE 2\n{}", "0 0 0\n".repeat(65_536 + 8)); + let lut = parse_cube(&text).unwrap(); + assert_eq!(lut.d1.len(), 65_536); + assert_eq!(lut.d3.len(), 8); + // Keep the parser's existing tolerance for headers following data. + let text = format!("{}LUT_1D_SIZE 2\nLUT_3D_SIZE 2\n", "0 0 0\n".repeat(10)); + let lut = parse_cube(&text).unwrap(); + assert_eq!(lut.d1, vec![[0.0; 3]; 2]); + assert_eq!(lut.d3, vec![[0.0; 3]; 8]); + } + + #[test] + fn cube_row_collection_is_bounded() { + // Beyond the largest 3D table plus the largest 1D shaper in Cube LUT 1.0. + let count = 256 * 256 * 256 + 65_536 + 1; + let text = format!("LUT_1D_SIZE {count}\n{}", "0 0 0\n".repeat(count)); + assert!(parse_cube(&text).is_none()); + } + #[test] fn one_d_lut_with_domain() { let lut = parse_cube("LUT_1D_SIZE 2\nDOMAIN_MIN 0 0 0\nDOMAIN_MAX 2 2 2\n1 1 1\n0 0 0\n").unwrap(); From ce0c4c8a75a953cfe6806a199db345c99ec61417 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 17:30:44 +0530 Subject: [PATCH 43/78] #3464: Drop Shadow: blur before moving when the margin is cut With the padding cut to its budget, a Distance larger than what's left of the margin moved the layer out of the buffer before the blur, so the blur had nothing to spread back in: a 64 x 48 layer moved 3000 px at Softness 8000 left no shadow at all. The cut-margin path now samples only the fraction of the move and lets the blur move the rest: raster::gaussian_blur_unbounded_at evaluates the transparent-edged blur of the image at a whole-pixel shift, through a window the size of the buffer, so content outside the window still reaches into it. Margins that fit are unchanged. The blur's intermediate rows are freed before the output is allocated, so it holds at most three buffers at once. On an M-series Mac a 4096 x 4096 layer at Softness 30000 takes 0.51 s, and 1080p 0.13 s. --- crates/effects/src/misc.rs | 62 ++++++++++++++---- crates/raster/src/blur.rs | 130 +++++++++++++++++++++++++------------ crates/raster/src/lib.rs | 2 +- 3 files changed, 137 insertions(+), 57 deletions(-) diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index 660cee46a..c0568a970 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -3,7 +3,7 @@ use effectcraft_color::luminance; use effectcraft_keyframe::Value; use effectcraft_project::ParamUi; -use effectcraft_raster::{Image, gaussian_blur, gaussian_blur_unbounded, hash_noise}; +use effectcraft_raster::{Image, gaussian_blur, gaussian_blur_unbounded_at, hash_noise}; use rayon::prelude::*; use crate::{Buf, EffectCtx, EffectSpec, col, num, p, popup, slider}; @@ -298,9 +298,10 @@ fn drop_shadow(ctx: &EffectCtx, mut b: Buf) -> Buf { let only = ctx.params.b("shadowOnly"); let pad = drop_shadow_pad(dist, soft); // Whether the buffer holds the whole blur. The pixel budget (#2261) cuts the margin of a - // large Softness (After Effects' range reaches 30000, #3464); the blur then goes on past the - // buffer's edge rather than dropping what reaches it, which would leave the shadow far too - // faint. An adjustment layer's buffer is the composition, as before. + // large Softness (After Effects' range reaches 30000, #3464); the shadow is then blurred + // before it is moved, as if the buffer went on with transparency, rather than dropping what + // the move or the blur takes past the buffer's edge, which would leave it far too faint or + // gone. An adjustment layer's buffer is the composition, as before. let mut holds_blur = true; if !ctx.adjustment { let (w0, h0) = (b.img.width, b.img.height); @@ -309,17 +310,27 @@ fn drop_shadow(ctx: &EffectCtx, mut b: Buf) -> Buf { holds_blur = b.img.width.saturating_sub(w0) >= need && b.img.height.saturating_sub(h0) >= need; } let (dx, dy) = (dir.sin() * dist, -dir.cos() * dist); - let mut sh = Image::new(b.img.width, b.img.height); let src = &b.img; - sh.rows_mut().for_each(|(y, row)| { - for (x, px) in row.iter_mut().enumerate() { - let a = src.sample_bilinear(x as f64 + 0.5 - dx, y as f64 + 0.5 - dy)[3] * opacity * color[3]; - *px = [color[0] * a, color[1] * a, color[2] * a, a]; - } - }); - if soft > 0.0 { - sh = if holds_blur { gaussian_blur(&sh, soft / 2.0, soft / 2.0, false) } else { gaussian_blur_unbounded(&sh, soft / 2.0, soft / 2.0) }; - } + let shadow = |sh: &mut Image, (dx, dy): (f64, f64)| { + sh.rows_mut().for_each(|(y, row)| { + for (x, px) in row.iter_mut().enumerate() { + let a = src.sample_bilinear(x as f64 + 0.5 - dx, y as f64 + 0.5 - dy)[3] * opacity * color[3]; + *px = [color[0] * a, color[1] * a, color[2] * a, a]; + } + }); + }; + let mut sh = if soft > 0.0 && !holds_blur { + // Only the fraction of the move is sampled (into one more column and row); the blur + // moves the rest. + let (ix, iy) = (dx.floor(), dy.floor()); + let mut near = Image::new(src.width.saturating_add(1), src.height.saturating_add(1)); + shadow(&mut near, (dx - ix, dy - iy)); + gaussian_blur_unbounded_at(&near, soft / 2.0, soft / 2.0, [ix as i64, iy as i64], src.width, src.height) + } else { + let mut sh = Image::new(src.width, src.height); + shadow(&mut sh, (dx, dy)); + if soft > 0.0 { gaussian_blur(&sh, soft / 2.0, soft / 2.0, false) } else { sh } + }; if !only { sh.data.par_iter_mut().zip(b.img.data.par_iter()).for_each(|(s, o)| { let k = 1.0 - o[3]; @@ -1069,6 +1080,29 @@ mod tests { } } + /// #3464: with the margin cut, a Distance that takes the whole layer past the buffer's edge + /// still leaves the shadow's blur inside it. A 64 × 48 layer moved 3000 px right, Softness + /// 8000: at the layer's centre the shadow is the Gaussian's share there (it was 0 when the + /// layer was moved out of the buffer before the blur). + #[test] + fn drop_shadow_moved_past_a_cut_margin_keeps_its_blur() { + let (w, h, dist, softness) = (64u32, 48u32, 3000.0, 8000.0); + let layer = effectcraft_raster::Image::filled(w, h, [1.0, 1.0, 1.0, 1.0]); + let vals = [("softness", num(softness)), ("opacity", num(100.0)), ("distance", num(dist)), ("direction", num(90.0)), ("shadowOnly", Value::Bool(true))]; + let out = run_fx("ec.perspective.dropshadow", &vals, layer, 0.0, EffectEnv::default()); + assert!(out.offset[0] + f64::from(w) + dist > f64::from(out.img.width), "the move takes the layer past the buffer"); + let sigma = softness / 2.0; + // The Gaussian's share of a `len`-pixel side, at `d` pixels from its centre. + let share = |len: u32, d: f64| { + let sum: f64 = (0..len).map(|i| (-((f64::from(i) + 0.5 - f64::from(len) / 2.0 + d) / sigma).powi(2) / 2.0).exp()).sum(); + sum / (sigma * (2.0 * std::f64::consts::PI).sqrt()) + }; + let want = share(w, dist) * share(h, 0.0); + let at = |v: f64, half: u32| (v + f64::from(half)) as i64; + let got = f64::from(out.img.get(at(out.offset[0], w / 2), at(out.offset[1], h / 2))[3]); + assert!((0.85..1.1).contains(&(got / want)), "centre alpha {got}, Gaussian {want}"); + } + /// #3464: past the padding budget (#2261) the shadow keeps its whole blur (σ = Softness / 2) /// up to the buffer's edge. A 64 × 48 layer's shadow at its centre is the Gaussian's share /// of the layer, less the 6 % three boxes' peak is under a Gaussian's; dropping what the diff --git a/crates/raster/src/blur.rs b/crates/raster/src/blur.rs index 6ca4aa174..cc6fe35df 100644 --- a/crates/raster/src/blur.rs +++ b/crates/raster/src/blur.rs @@ -188,31 +188,42 @@ pub fn gaussian_blur(img: &Image, sigma_x: f64, sigma_y: f64, repeat: bool) -> I /// padding cut to its pixel budget), which [`gaussian_blur`] leaves far too faint once the /// boxes are wider than the buffer. A line costs O(length) whatever the sigma. pub fn gaussian_blur_unbounded(img: &Image, sigma_x: f64, sigma_y: f64) -> Image { - let (w, h) = (img.width as usize, img.height as usize); - let mut out = img.clone(); - if w == 0 || h == 0 { - return out; + gaussian_blur_unbounded_at(img, sigma_x, sigma_y, [0, 0], img.width, img.height) +} + +/// [`gaussian_blur_unbounded`] of `img` moved by `shift` pixels, seen through a `width` × +/// `height` window at the origin: output `(x, y)` is the blurred plane at +/// `(x − shift[0], y − shift[1])`. Nothing is cut before the blur, so the tails of content +/// that lands outside the window still reach into it. +pub fn gaussian_blur_unbounded_at(img: &Image, sigma_x: f64, sigma_y: f64, shift: [i64; 2], width: u32, height: u32) -> Image { + let (w, h, ow, oh) = (img.width as usize, img.height as usize, width as usize, height as usize); + if w == 0 || h == 0 || ow == 0 || oh == 0 { + return Image::new(width, height); } - if let Some(r) = unbounded_radii(sigma_x) { - out.data.par_chunks_mut(w).for_each(|row| boxes_unbounded(row, &r)); - } - if let Some(r) = unbounded_radii(sigma_y) { - let cols: Vec> = (0..w) - .into_par_iter() - .map(|x| { - let mut col: Vec = out.data.iter().skip(x).step_by(w).copied().collect(); - boxes_unbounded(&mut col, &r); - col - }) - .collect(); - out.data.par_chunks_mut(w).enumerate().for_each(|(y, row)| { - for (o, col) in row.iter_mut().zip(&cols) { - if let Some(v) = col.get(y) { - *o = *v; - } + let (rx, ry) = (unbounded_radii(sigma_x).unwrap_or_default(), unbounded_radii(sigma_y).unwrap_or_default()); + // Horizontal: each source row into a row of the window's width. + let mut rows = vec![[0.0f32; 4]; ow.saturating_mul(h)]; + rows.par_chunks_mut(ow).zip(img.data.par_chunks(w)).for_each(|(o, src)| boxes_unbounded(src, &rx, shift[0], o)); + // Vertical: each of those columns into a column of the window's height. + let cols: Vec> = (0..ow) + .into_par_iter() + .map(|x| { + let col: Vec = rows.iter().skip(x).step_by(ow).copied().collect(); + let mut o = vec![[0.0f32; 4]; oh]; + boxes_unbounded(&col, &ry, shift[1], &mut o); + o + }) + .collect(); + // At most three buffers at once: the rows go before the output comes. + drop(rows); + let mut out = Image::new(width, height); + out.data.par_chunks_mut(ow).enumerate().for_each(|(y, row)| { + for (o, col) in row.iter_mut().zip(&cols) { + if let Some(v) = col.get(y) { + *o = *v; } - }); - } + } + }); out } @@ -231,32 +242,36 @@ fn unbounded_radii(sigma: f64) -> Option> { (!radii.is_empty()).then_some(radii) } -/// Transparent-edged box passes of radii `r` (one to three, none zero) over `line`, as if it -/// went on with zeros. +/// Transparent-edged box passes of radii `r` (up to three, none zero) over `line`, as if it +/// went on with zeros, moved by `shift`: `out[x]` is the blurred line at `x − shift`. /// /// One box is a difference of prefix sums, `(S(x + r) − S(x − r − 1)) / (2r + 1)`, so `k` boxes -/// are `2^k` signed terms of the `k`-th prefix sum `Sk`. Before the line every `Sk` is 0; past -/// it, `j = m − n + 1` steps on with `T` the line's total, they are polynomials: -/// `S1(m) = T`, `S2(m) = S2(n − 1) + j·T`, `S3(m) = S3(n − 1) + j·S2(n − 1) + T·j(j + 1)/2`. -/// The sums are `f64`. `Sk` grows like `n^k`, so the cancelling terms leave a rounding error -/// near `ε·n^k / (2r + 1)^k` of the values: under 1e-8 for any line a blur too wide for its -/// buffer runs on. -fn boxes_unbounded(line: &mut [Px], r: &[i64]) { +/// are `2^k` signed terms of the `k`-th prefix sum `Sk` (`S0` is the line). Before the line +/// every `Sk` is 0; past it, `j = m − n + 1` steps on with `T` the line's total, they are +/// polynomials: `S0(m) = 0`, `S1(m) = T`, `S2(m) = S2(n − 1) + j·T`, +/// `S3(m) = S3(n − 1) + j·S2(n − 1) + T·j(j + 1)/2`. The sums are `f64`. `Sk` grows like `n^k`, +/// so the cancelling terms leave a rounding error near `ε·n^k / (2r + 1)^k` of the values: +/// under 1e-8 for any line a blur too wide for its buffer runs on. +fn boxes_unbounded(line: &[Px], r: &[i64], shift: i64, out: &mut [Px]) { let (n, k) = (line.len(), r.len()); let Ok(n_i) = i64::try_from(n) else { return }; - if n == 0 || !(1..=3).contains(&k) { + if n == 0 || k > 3 { return; } // sums[o] = the (o + 1)-th prefix sum so far. let mut sums = [[0.0f64; 4]; 3]; let mut sk = Vec::with_capacity(n); - for p in line.iter() { + for p in line { + let v = p.map(f64::from); for c in 0..4 { - sums[0][c] += f64::from(p[c]); + sums[0][c] += v[c]; sums[1][c] += sums[0][c]; sums[2][c] += sums[1][c]; } - sk.push(sums[k - 1]); + sk.push(match k { + 0 => v, + _ => sums[k - 1], + }); } let at = |m: i64| -> [f64; 4] { if m < 0 { @@ -267,24 +282,25 @@ fn boxes_unbounded(line: &mut [Px], r: &[i64]) { } let j = (m - n_i + 1) as f64; std::array::from_fn(|c| match k { + 0 => 0.0, 1 => sums[0][c], 2 => sums[1][c] + j * sums[0][c], _ => sums[2][c] + j * sums[1][c] + sums[0][c] * j * (j + 1.0) / 2.0, }) }; - // The shifts and signs: each box adds `S(x + r)` and subtracts `S(x − r − 1)`. + // The offsets and signs: each box adds `S(x + r)` and subtracts `S(x − r − 1)`. let terms: Vec<(i64, f64)> = (0..1usize << k) .map(|bits| { - r.iter().enumerate().fold((0i64, 1.0f64), |(shift, sign), (b, &ri)| { - if bits >> b & 1 == 0 { (shift.saturating_add(ri), sign) } else { (shift.saturating_sub(ri.saturating_add(1)), -sign) } + r.iter().enumerate().fold((0i64.saturating_sub(shift), 1.0f64), |(at, sign), (b, &ri)| { + if bits >> b & 1 == 0 { (at.saturating_add(ri), sign) } else { (at.saturating_sub(ri.saturating_add(1)), -sign) } }) }) .collect(); let norm: f64 = r.iter().map(|&ri| 2.0 * ri as f64 + 1.0).product(); - for (x, o) in (0i64..).zip(line.iter_mut()) { + for (x, o) in (0i64..).zip(out.iter_mut()) { let mut v = [0.0f64; 4]; - for &(shift, sign) in &terms { - let s = at(x.saturating_add(shift)); + for &(offset, sign) in &terms { + let s = at(x.saturating_add(offset)); for c in 0..4 { v[c] += sign * s[c]; } @@ -632,6 +648,36 @@ mod tests { assert!(r.iter().all(|&v| (7..=10).contains(&v)), "{r:?}"); } + /// #3464: moving the image before [`gaussian_blur_unbounded`] and blurring it moved with + /// [`gaussian_blur_unbounded_at`] agree, also when the move puts all of it outside the window + /// (its tails still reach in) and along an axis that isn't blurred. + #[test] + fn unbounded_gaussian_at_a_shift_matches_blurring_the_moved_image() { + let mut img = Image::new(6, 5); + for (i, p) in img.data.iter_mut().enumerate() { + let v = ((i * 37) % 11) as f32 / 11.0; + *p = [v, 0.5 * v, 1.0 - v, 1.0]; + } + let (ow, oh) = (14u32, 9u32); + for (sx, sy, shift) in [(3.0, 2.0, [4i64, 2i64]), (5.0, 0.0, [-3, 1]), (12.0, 12.0, [-20, 16]), (8.0, 8.0, [25, -12])] { + let got = gaussian_blur_unbounded_at(&img, sx, sy, shift, ow, oh); + // The moved image in a canvas large enough to hold it and the window, blurred. + let off = [40i64, 40i64]; + let mut canvas = Image::new(100, 100); + for y in 0..img.height { + for x in 0..img.width { + let (cx, cy) = (i64::from(x) + shift[0] + off[0], i64::from(y) + shift[1] + off[1]); + canvas.set(cx as u32, cy as u32, img.get(i64::from(x), i64::from(y))); + } + } + let want = gaussian_blur_unbounded(&canvas, sx, sy).crop(off[0], off[1], ow, oh); + assert!(got.data.iter().flatten().any(|v| *v > 1e-4), "{shift:?}: something reaches the window"); + for (a, b) in got.data.iter().flatten().zip(want.data.iter().flatten()) { + assert!((a - b).abs() <= 1e-5, "σ ({sx}, {sy}) {shift:?}: {a} vs {b}"); + } + } + } + /// #3464: a sigma past any buffer, or infinite, blurs as the widest one does: finite, no /// overflow in the radii. A NaN sigma leaves the axis alone. #[test] diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index b94874944..900416808 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -17,7 +17,7 @@ pub mod yuv; use effectcraft_color::{BlendMode, blend_pixel}; use rayon::prelude::*; -pub use blur::{box_blur, directional_blur, gaussian_blur, gaussian_blur_exact, gaussian_blur_unbounded, gaussian_is_exact, radial_blur}; +pub use blur::{box_blur, directional_blur, gaussian_blur, gaussian_blur_exact, gaussian_blur_unbounded, gaussian_blur_unbounded_at, gaussian_is_exact, radial_blur}; pub use channels3d::AuxChannels; pub use warp::{Sampling, WarpOpts, accumulate_warp, composite_warp, composite_warp_changed, composite_warp_reference, resample}; From 1654633bcf1819a1db4cba14e6f11b25c979cb37 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 17:33:35 +0530 Subject: [PATCH 44/78] fix(effects): test the cube row bound without a huge input --- crates/effects/src/utility.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/effects/src/utility.rs b/crates/effects/src/utility.rs index 72f07cde9..b99de477b 100644 --- a/crates/effects/src/utility.rs +++ b/crates/effects/src/utility.rs @@ -222,6 +222,10 @@ const MAX_CUBE_ROWS: usize = 65_536 + 256 * 256 * 256; /// Parse `.cube` text (TITLE, LUT_1D_SIZE, LUT_3D_SIZE, DOMAIN_MIN/MAX, data red-fastest). pub fn parse_cube(text: &str) -> Option { + parse_cube_limited(text, MAX_CUBE_ROWS) +} + +fn parse_cube_limited(text: &str, max_rows: usize) -> Option { let mut lut = Lut { n1: 0, d1: vec![], n3: 0, d3: vec![], dmin: [0.0; 3], dmax: [1.0; 3] }; let mut rows: Vec<[f32; 3]> = Vec::new(); let three = |it: &mut std::str::SplitWhitespace| -> Option<[f32; 3]> { @@ -264,10 +268,11 @@ pub fn parse_cube(text: &str) -> Option { } k if k.starts_with(|c: char| c.is_ascii_alphabetic()) => continue, _ => { - if rows.len() == MAX_CUBE_ROWS { + if rows.len() == max_rows { return None; } let row = three(&mut it)?; + // Make buffer growth fallible before push can allocate. rows.try_reserve(1).ok()?; rows.push(row); } @@ -719,10 +724,11 @@ mod tests { #[test] fn cube_row_collection_is_bounded() { - // Beyond the largest 3D table plus the largest 1D shaper in Cube LUT 1.0. - let count = 256 * 256 * 256 + 65_536 + 1; - let text = format!("LUT_1D_SIZE {count}\n{}", "0 0 0\n".repeat(count)); - assert!(parse_cube(&text).is_none()); + assert_eq!(MAX_CUBE_ROWS, 65_536 + 256 * 256 * 256); + let text = "LUT_1D_SIZE 2\n0 0 0\n1 1 1\n"; + let lut = parse_cube_limited(text, 2).unwrap(); + assert_eq!(lut.d1, vec![[0.0; 3], [1.0; 3]]); + assert!(parse_cube_limited("LUT_1D_SIZE 3\n0 0 0\n0.5 0.5 0.5\n1 1 1\n", 2).is_none()); } #[test] From 44663c5e9f1f9bb4798d490c59da6ffa0f48b8c7 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 17:58:30 +0530 Subject: [PATCH 45/78] #3464: raster: an unbounded blur is exactly 0 where it doesn't reach Outside the boxes' combined reach of the moved line the result is 0, but boxes_unbounded still evaluated the prefix-sum polynomials there, and far past the line their cancelling terms left a rounding residue (about 5 for a one-pixel line moved a billion pixels). Those positions are now 0 without evaluating anything. Also wraps the raster re-export line rustfmt asks for. --- crates/raster/src/blur.rs | 21 +++++++++++++++++++++ crates/raster/src/lib.rs | 4 +++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/raster/src/blur.rs b/crates/raster/src/blur.rs index cc6fe35df..489b32755 100644 --- a/crates/raster/src/blur.rs +++ b/crates/raster/src/blur.rs @@ -297,7 +297,15 @@ fn boxes_unbounded(line: &[Px], r: &[i64], shift: i64, out: &mut [Px]) { }) .collect(); let norm: f64 = r.iter().map(|&ri| 2.0 * ri as f64 + 1.0).product(); + // The boxes read the line within `reach` of `x − shift`. Outside that the result is 0, and + // the polynomials far past the line would only cancel to their rounding error. + let reach = r.iter().fold(0i64, |s, &ri| s.saturating_add(ri)); for (x, o) in (0i64..).zip(out.iter_mut()) { + let c = x.saturating_sub(shift); + if c.saturating_add(reach) < 0 || c.saturating_sub(reach) >= n_i { + *o = [0.0; 4]; + continue; + } let mut v = [0.0f64; 4]; for &(offset, sign) in &terms { let s = at(x.saturating_add(offset)); @@ -678,6 +686,19 @@ mod tests { } } + /// #3464: a window the blur doesn't reach stays exactly transparent, however far the move + /// (far past the line, the cancelling polynomials left a rounding residue of about 5). + #[test] + fn unbounded_gaussian_at_a_far_shift_is_exactly_transparent() { + let img = Image::filled(1, 1, [1.0, 1.0, 1.0, 1.0]); + for shift in [[-1_000_000_030i64, 0i64], [0, 1_000_000_030], [i64::MIN, i64::MAX]] { + let out = gaussian_blur_unbounded_at(&img, 1.5, 1.5, shift, 4, 3); + assert!(out.data.iter().flatten().all(|v| *v == 0.0), "{shift:?}"); + } + // Next to the window the tail still reaches in. + assert!(gaussian_blur_unbounded_at(&img, 1.5, 1.5, [-1, 0], 4, 3).get(0, 0)[3] > 0.0); + } + /// #3464: a sigma past any buffer, or infinite, blurs as the widest one does: finite, no /// overflow in the radii. A NaN sigma leaves the axis alone. #[test] diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 900416808..1708f40f6 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -17,7 +17,9 @@ pub mod yuv; use effectcraft_color::{BlendMode, blend_pixel}; use rayon::prelude::*; -pub use blur::{box_blur, directional_blur, gaussian_blur, gaussian_blur_exact, gaussian_blur_unbounded, gaussian_blur_unbounded_at, gaussian_is_exact, radial_blur}; +pub use blur::{ + box_blur, directional_blur, gaussian_blur, gaussian_blur_exact, gaussian_blur_unbounded, gaussian_blur_unbounded_at, gaussian_is_exact, radial_blur, +}; pub use channels3d::AuxChannels; pub use warp::{Sampling, WarpOpts, accumulate_warp, composite_warp, composite_warp_changed, composite_warp_reference, resample}; From d550d3d476e83b0b1987522d0cfee99128c138c4 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 22:09:04 +0530 Subject: [PATCH 46/78] #3830: regression tests for hostile .3dl meshes and row-less .spi3d lattices --- crates/effects/src/ocio/tests.rs | 34 ++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/effects/src/ocio/tests.rs b/crates/effects/src/ocio/tests.rs index d40d3b046..3952a8ab3 100644 --- a/crates/effects/src/ocio/tests.rs +++ b/crates/effects/src/ocio/tests.rs @@ -547,3 +547,37 @@ fn an_ocio_transform_file_is_read_again_once_it_changes() { assert!(Arc::ptr_eq(&inline, &load_file(BLACK).unwrap())); std::fs::remove_dir_all(&dir).unwrap(); } + +#[test] +fn a_3dl_with_a_hostile_mesh_is_refused_without_overflow() { + // #3830: 2 642 246³ is past usize::MAX, so cubing the mesh length overflowed. + let huge = "0 ".repeat(2_642_246) + "\n0 0 0\n"; + assert!(parse_file(&huge, "3dl").is_none()); + // A mesh longer than any lattice the readers accept, and a mesh whose rows run out. + let long = (0..130).map(|i| i.to_string()).collect::>().join(" ") + "\n0 0 0\n"; + assert!(parse_file(&long, "3dl").is_none()); + let short = (0..17).map(|i| (i * 64).to_string()).collect::>().join(" ") + "\n0 0 0\n1 1 1\n"; + assert!(parse_file(&short, "3dl").is_none()); + // A normal small table still loads. + let mut ok = String::from("0 511 1023\n"); + for k in 0..27 { + ok += &format!("{} {} {}\n", k * 30, k * 30, k * 30); + } + assert!(matches!(parse_file(&ok, "3dl"), Some(FileXform::Lut { lut, .. }) if lut.n3 == 3 && lut.d3.len() == 27)); +} + +#[test] +fn a_spi3d_without_its_rows_is_refused_before_the_lattice_is_reserved() { + // #3831: a header-only 129³ claim must not reach the reader that reserves the whole lattice. + let empty = "SPILUT 1.0\n3 3\n129 129 129\n"; + assert!(!lut::spi3d_rows_present(empty)); + assert!(!lut::spi3d_rows_present("SPILUT 1.0\n3 3\n2 2 2\n0 0 0 1 1 1\n")); + assert!(!lut::spi3d_rows_present("SPILUT 1.0\n3 3\n99999999999 2 2\n")); + assert!(parse_spi3d(empty).is_none()); + let mut ok = String::from("SPILUT 1.0\n3 3\n2 2 2\n"); + for i in 0..8 { + ok += &format!("{} {} {} 0 0 0\n", i & 1, (i >> 1) & 1, i >> 2); + } + assert!(lut::spi3d_rows_present(&ok)); + assert!(parse_spi3d(&ok).is_some_and(|l| l.n3 == 2 && l.d3.len() == 8)); +} From a65a1f746ff41305f395801d6d4ae130b36797c0 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 22:11:34 +0530 Subject: [PATCH 47/78] #3830: cap the .3dl mesh and rows and cube with checked math; #3831: refuse a .spi3d short of its rows before the lattice is reserved --- crates/effects/src/ocio/lut.rs | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/effects/src/ocio/lut.rs b/crates/effects/src/ocio/lut.rs index 4618a4da0..fc16da0ea 100644 --- a/crates/effects/src/ocio/lut.rs +++ b/crates/effects/src/ocio/lut.rs @@ -32,10 +32,24 @@ pub fn parse_spi1d(text: &str) -> Option { /// Parse a Sony Imageworks `.spi3d` lattice: `SPILUT 1.0`, `3 3`, the sizes, then one /// `r g b R G B` line per lattice point (indices, then the colour). pub fn parse_spi3d(text: &str) -> Option { + if !spi3d_rows_present(text) { + return None; + } let value = craft_cms::sony_lut::parse_spi3d(text)?; Some(Lut { n1: 0, d1: vec![], n3: value.size, d3: value.values, dmin: [0.0; 3], dmax: [1.0; 3] }) } +/// Whether a `.spi3d` file has at least as many rows as its header's lattice claims. The shared +/// reader reserves the whole lattice before it reads a row, so a short file is turned away +/// first (#3831). Counting stops at the claimed volume; nothing is allocated. +pub(super) fn spi3d_rows_present(text: &str) -> bool { + let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty()).skip(2); + let Some(n) = lines.next().and_then(|l| l.split_whitespace().next()?.parse::().ok()) else { + return false; + }; + n.checked_pow(3).is_some_and(|count| lines.take(count).count() == count) +} + /// Parse an Autodesk `.3dl` lattice (integers, blue fastest; an optional input-mesh line). pub fn parse_3dl(text: &str) -> Option { let mut mesh: Option> = None; @@ -56,8 +70,15 @@ pub fn parse_3dl(text: &str) -> Option { } let v: Vec = l.split_whitespace().filter_map(|t| t.parse().ok()).collect(); if v.len() > 3 && mesh.is_none() && rows.is_empty() { + // The mesh length is the lattice side: refuse one no lattice reader accepts (#3830). + if v.len() > MAX_LATTICE { + return None; + } mesh = Some(v); } else if v.len() == 3 { + if rows.len() >= MAX_LATTICE.pow(3) { + return None; + } rows.push([v[0], v[1], v[2]]); } else { return None; @@ -75,7 +96,7 @@ pub fn parse_3dl(text: &str) -> Option { Some(m) => m.len(), None => (rows.len() as f64).cbrt().round() as usize, }; - if n < 2 || rows.len() != n * n * n { + if !(2..=MAX_LATTICE).contains(&n) || n.checked_pow(3) != Some(rows.len()) { return None; } let maxv = rows.iter().flat_map(|r| r.iter()).fold(0.0f64, |m, &v| m.max(v)); @@ -92,7 +113,7 @@ pub fn parse_3dl(text: &str) -> Option { Some(Lut { n1: 0, d1: vec![], n3: n, d3, dmin: [0.0; 3], dmax: [1.0; 3] }) } -/// Largest lattice side the lattice readers accept (`.spi3d`, `.csp`). +/// Largest lattice side the lattice readers accept (`.spi3d`, `.csp`, `.3dl`). const MAX_LATTICE: usize = 129; /// Most entries of a 1D table (interpolated by index, so capped like the lattices: 2²⁴). const MAX_1D: usize = 1 << 24; From 6232bed5562da9676cf223cba9ae66fafccc8703 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 22:20:14 +0530 Subject: [PATCH 48/78] #3830: stop collecting a .3dl line's numbers past the mesh limit --- crates/effects/src/ocio/lut.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/effects/src/ocio/lut.rs b/crates/effects/src/ocio/lut.rs index fc16da0ea..f3622e990 100644 --- a/crates/effects/src/ocio/lut.rs +++ b/crates/effects/src/ocio/lut.rs @@ -68,7 +68,7 @@ pub fn parse_3dl(text: &str) -> Option { } continue; } - let v: Vec = l.split_whitespace().filter_map(|t| t.parse().ok()).collect(); + let v: Vec = l.split_whitespace().filter_map(|t| t.parse().ok()).take(MAX_LATTICE + 1).collect(); if v.len() > 3 && mesh.is_none() && rows.is_empty() { // The mesh length is the lattice side: refuse one no lattice reader accepts (#3830). if v.len() > MAX_LATTICE { From 104875a89755d973bea5468cb351344bcd3ceb9b Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Tue, 17 Nov 2026 22:28:16 +0530 Subject: [PATCH 49/78] #3830: read only the three .3dl Mesh header tokens it uses --- crates/effects/src/ocio/lut.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/effects/src/ocio/lut.rs b/crates/effects/src/ocio/lut.rs index f3622e990..f7ae08986 100644 --- a/crates/effects/src/ocio/lut.rs +++ b/crates/effects/src/ocio/lut.rs @@ -62,7 +62,7 @@ pub fn parse_3dl(text: &str) -> Option { } if l.starts_with(|c: char| c.is_ascii_alphabetic()) { // "Mesh " (Lustre header); other keywords are ignored. - let t: Vec<&str> = l.split_whitespace().collect(); + let t: Vec<&str> = l.split_whitespace().take(3).collect(); if t[0].eq_ignore_ascii_case("mesh") && t.len() >= 3 { out_bits = t[2].parse().ok(); } From a1c1288b136b33480c88791509327b74c0e5e421 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 05:59:44 +0100 Subject: [PATCH 50/78] #3779: pin bounded PSD placement fixes and test app boundaries --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/psd/src/tests/opt.rs | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 39fce1ec6..ed67e2422 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1449,7 +1449,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=30cad49e958caa58ebd04eb1d459ab616a07c63f#30cad49e958caa58ebd04eb1d459ab616a07c63f" +source = "git+https://github.com/storytold/craft-libs?rev=f8d869c1e70d1df8109a951c3a30eb2e0aecd54c#f8d869c1e70d1df8109a951c3a30eb2e0aecd54c" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 029ad4992..097fb8389 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "30cad49e958caa58ebd04eb1d459ab616a07c63f" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f8d869c1e70d1df8109a951c3a30eb2e0aecd54c" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } diff --git a/crates/psd/src/tests/opt.rs b/crates/psd/src/tests/opt.rs index f48b6123b..3f351a7ab 100644 --- a/crates/psd/src/tests/opt.rs +++ b/crates/psd/src/tests/opt.rs @@ -716,3 +716,38 @@ fn identifier_and_index_references_preserve_non_null_classes_exactly() { assert_eq!(out, bytes); } } +#[test] +fn shared_descriptor_nesting_preserves_the_application_boundary() { + use craft_psd::descriptor::{Descriptor as Shared, Value}; + for count in [33, 64, 65] { + let mut value = Value::Integer(1); + for _ in 0..count { + value = Value::Descriptor(Shared::new("null").with("next", value)); + } + let bytes = Shared::new("null").with("root", value).to_bytes(); + let result = crate::descriptor::read_descriptor(&mut Reader::new(&bytes)); + assert_eq!(result.is_ok(), count <= 64, "nested descriptor count {count}: {result:?}"); + } +} + +#[test] +fn shared_placed_layer_adapter_normalizes_before_warp_classification() { + use craft_psd::descriptor::{Descriptor as Shared, Id, Value}; + let warp = Shared::new("warp") + .with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpArc") }) + .with("warpValue", Value::Double(f64::NAN)) + .with("warpPerspective", Value::Double(f64::INFINITY)) + .with("warpPerspectiveOther", Value::Double(f64::NEG_INFINITY)); + let quad = [f64::NAN, 0.0, 20.0, 0.0, 20.0, 10.0, 0.0, 10.0]; + let descriptor = Shared::new("null").with("Trnf", Value::List(quad.into_iter().map(Value::Double).collect())).with("warp", Value::Descriptor(warp)); + let mut bytes = b"soLD".to_vec(); + bytes.extend_from_slice(&4u32.to_be_bytes()); + bytes.extend_from_slice(&16u32.to_be_bytes()); + bytes.extend_from_slice(&descriptor.to_bytes()); + let shared = craft_psd::smart::SmartObject::from_placed_layer_data_with_limits(&bytes, crate::descriptor::PARSE_LIMITS).unwrap(); + let object = crate::placed::from_craft_smart(shared); + assert_eq!(object.quad, [[0.0, 0.0], [20.0, 0.0], [20.0, 10.0], [0.0, 10.0]]); + assert!(object.warp.is_none(), "normalization must precede identity classification"); + assert!(!object.needs_bake()); + assert_eq!(object.map([10.0, 5.0], 20.0, 10.0), [10.0, 5.0]); +} From 218470e7b6471d4204595a15f5538192e3474c9a Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 08:08:36 +0100 Subject: [PATCH 51/78] #3779: pin explicit quilt bounds and template roundtrip fixes --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ed67e2422..f3af19213 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1449,7 +1449,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f8d869c1e70d1df8109a951c3a30eb2e0aecd54c#f8d869c1e70d1df8109a951c3a30eb2e0aecd54c" +source = "git+https://github.com/storytold/craft-libs?rev=b3960accde1b540b2fe9364f8b6b848284564601#b3960accde1b540b2fe9364f8b6b848284564601" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 097fb8389..24848646f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f8d869c1e70d1df8109a951c3a30eb2e0aecd54c" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "b3960accde1b540b2fe9364f8b6b848284564601" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } From 7bb70c73d84d1ede73656f15ba93ebfa53900b79 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 08:43:41 +0100 Subject: [PATCH 52/78] #3779: pin audited quilt read-write contract fixes --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f3af19213..7377934ab 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1449,7 +1449,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b3960accde1b540b2fe9364f8b6b848284564601#b3960accde1b540b2fe9364f8b6b848284564601" +source = "git+https://github.com/storytold/craft-libs?rev=be556bedcbc3fcd63d3146fd7fcec9bc488fc7ae#be556bedcbc3fcd63d3146fd7fcec9bc488fc7ae" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 24848646f..0c010e3d3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "b3960accde1b540b2fe9364f8b6b848284564601" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "be556bedcbc3fcd63d3146fd7fcec9bc488fc7ae" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } From cb3f66e06c1887290e9179f88ab150e446245642 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 09:36:47 +0100 Subject: [PATCH 53/78] fix(psd): align local warp bounds with shared numeric contract --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/psd/src/placed.rs | 8 +++++++- crates/psd/src/tests/opt.rs | 21 +++++++++++++++++++++ 4 files changed, 30 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7377934ab..377d2308f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1449,7 +1449,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=be556bedcbc3fcd63d3146fd7fcec9bc488fc7ae#be556bedcbc3fcd63d3146fd7fcec9bc488fc7ae" +source = "git+https://github.com/storytold/craft-libs?rev=e9ec4813311264ee1857079c2edd10a70e2389a6#e9ec4813311264ee1857079c2edd10a70e2389a6" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 0c010e3d3..4f064474f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "be556bedcbc3fcd63d3146fd7fcec9bc488fc7ae" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e9ec4813311264ee1857079c2edd10a70e2389a6" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } diff --git a/crates/psd/src/placed.rs b/crates/psd/src/placed.rs index 93ba2755b..7b3f513a8 100644 --- a/crates/psd/src/placed.rs +++ b/crates/psd/src/placed.rs @@ -130,7 +130,13 @@ impl Warp { /// The warp of a content point (content pixels → content pixels). pub fn apply(&self, p: [f64; 2], w: f64, h: f64) -> [f64; 2] { - let [l, t, r, b] = if self.bounds[2] > self.bounds[0] && self.bounds[3] > self.bounds[1] { self.bounds } else { [0.0, 0.0, w, h] }; + // Keep the local mapping facade aligned with the shared bake evaluator. + let valid_bounds = self.bounds.iter().all(|x| x.is_finite()) + && (self.bounds[2] - self.bounds[0]).is_finite() + && self.bounds[2] > self.bounds[0] + && (self.bounds[3] - self.bounds[1]).is_finite() + && self.bounds[3] > self.bounds[1]; + let [l, t, r, b] = if valid_bounds { self.bounds } else { [0.0, 0.0, w, h] }; let (bw, bh) = (r - l, b - t); let (u, v) = ((p[0] - l) / bw, (p[1] - t) / bh); if self.style == "warpCustom" { diff --git a/crates/psd/src/tests/opt.rs b/crates/psd/src/tests/opt.rs index 3f351a7ab..c4fdefcfe 100644 --- a/crates/psd/src/tests/opt.rs +++ b/crates/psd/src/tests/opt.rs @@ -751,3 +751,24 @@ fn shared_placed_layer_adapter_normalizes_before_warp_classification() { assert!(!object.needs_bake()); assert_eq!(object.map([10.0, 5.0], 20.0, 10.0), [10.0, 5.0]); } + +#[test] +fn local_and_shared_warp_mapping_agree_on_overflowing_bounds() { + let mesh: Vec<_> = (0..4).flat_map(|j| (0..4).map(move |i| [i as f64 * 20.0 / 3.0, j as f64 * 10.0 / 3.0])).collect(); + for bounds in [[-f64::MAX, 0.0, f64::MAX, 10.0], [0.0, -f64::MAX, 20.0, f64::MAX]] { + let shared = craft_psd::smart::SmartObject { + uuid: String::new(), + quad: [[0.0, 0.0], [20.0, 0.0], [20.0, 10.0], [0.0, 10.0]], + size: Some([20.0, 10.0]), + warp: Some(craft_psd::smart::Warp { style: "warpCustom".into(), bounds, cols: 1, rows: 1, mesh: mesh.clone(), ..Default::default() }), + }; + let local = crate::placed::from_craft_smart(shared.clone()); + for point in [[5.0, 2.5], [10.0, 5.0], [15.0, 7.5]] { + let actual = local.map(point, 20.0, 10.0); + assert_eq!(actual, shared.map(point, 20.0, 10.0)); + for axis in 0..2 { + assert!((actual[axis] - point[axis]).abs() < 1e-9, "{bounds:?} {point:?}: {actual:?}"); + } + } + } +} From 49170cdf18d5604776fae576cb9fd247d1ed7d36 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 09:43:01 +0100 Subject: [PATCH 54/78] fix(psd): surface unsupported modern placements at import boundary --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/psd/src/parse.rs | 15 ++++++--- crates/psd/src/tests/integration.rs | 48 +++++++++++++++++++++++++++++ 4 files changed, 60 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 377d2308f..347669243 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1449,7 +1449,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e9ec4813311264ee1857079c2edd10a70e2389a6#e9ec4813311264ee1857079c2edd10a70e2389a6" +source = "git+https://github.com/storytold/craft-libs?rev=c9862964df7f73ad37706539a06e346fc4865ca3#c9862964df7f73ad37706539a06e346fc4865ca3" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 4f064474f..551e634fd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e9ec4813311264ee1857079c2edd10a70e2389a6" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c9862964df7f73ad37706539a06e346fc4865ca3" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } diff --git a/crates/psd/src/parse.rs b/crates/psd/src/parse.rs index 446ecb7af..5bcb38cc0 100644 --- a/crates/psd/src/parse.rs +++ b/crates/psd/src/parse.rs @@ -68,7 +68,7 @@ impl Psd { } if let Some(info) = &file.layer_info { psd.merged_alpha = info.merged_alpha; - psd.layers = info.layers.iter().enumerate().map(|(i, rec)| psd.layer(rec, i, splice)).collect(); + psd.layers = info.layers.iter().enumerate().map(|(i, rec)| psd.layer(rec, i, splice)).collect::>>()?; } for b in &file.global_blocks { if let Some(stored) = b.stored.as_ref().filter(|_| linked(&b.key, 0)) { @@ -81,7 +81,7 @@ impl Psd { /// One layer record of the model, its additional information read into [`Layer`]. /// `splice` maps craft-psd's offsets back into `self.data` (see [`read_file`]). - fn layer(&self, rec: &craft_psd::LayerRecord, index: usize, splice: Splice) -> Layer { + fn layer(&self, rec: &craft_psd::LayerRecord, index: usize, splice: Splice) -> Result { let channels = rec .channels .iter() @@ -111,10 +111,15 @@ impl Psd { } for b in &rec.blocks { l.keys.push(b.key); - // A malformed block only loses that block's information. - let _ = self.layer_block(&mut l, &b.key, &b.data); + // A malformed optional block only loses that block's information. + // Unsupported modern placement geometry must not silently become an + // unwarped layer or fall back to a less expressive PlLd in either order. + match self.layer_block(&mut l, &b.key, &b.data) { + Err(e @ Error::Unsupported(_)) if matches!(&b.key, b"SoLd" | b"SoLE") => return Err(e), + _ => {} + } } - l + Ok(l) } /// The embedded bytes of linked file `uuid`. diff --git a/crates/psd/src/tests/integration.rs b/crates/psd/src/tests/integration.rs index ee40aee16..ca521fc5e 100644 --- a/crates/psd/src/tests/integration.rs +++ b/crates/psd/src/tests/integration.rs @@ -92,3 +92,51 @@ fn a_tiny_file_claiming_a_huge_image_is_refused_within_the_budget() { } } } + +#[test] +fn unsupported_modern_placement_does_not_fall_back_to_legacy_in_either_order() { + use craft_psd::descriptor::{Descriptor, Id, ObjectArray, UnicodeString, Value, VersionedDescriptor}; + let quad = [[0.0, 0.0], [20.0, 0.0], [20.0, 10.0], [0.0, 10.0]]; + let legacy = craft_psd::smart::SmartObject { uuid: "legacy".into(), quad, size: Some([20.0, 10.0]), warp: None }.to_placed_layer(); + let modern = |middle| { + let floats = |values| Value::UnitFloats { unit: *b"#Pxl", values }; + let points = Descriptor::new("rationalPoint") + .with("Hrzn", floats((0..4).flat_map(|_| (0..7).map(|i| i as f64 * 20.0 / 6.0)).collect())) + .with("Vrtc", floats((0..4).flat_map(|j| [j as f64 * 10.0 / 3.0; 7]).collect())); + let envelope = Descriptor::new("customEnvelopeWarp") + .with("quiltSliceX", floats(vec![0.0, middle, 20.0])) + .with("quiltSliceY", floats(vec![0.0, 10.0])) + .with("meshPoints", Value::ObjectArray(ObjectArray { prefix: 28, body: points })); + let warp = Descriptor::new("quiltWarp") + .with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpCustom") }) + .with("customEnvelopeWarp", Value::Descriptor(envelope)); + let descriptor = Descriptor::new("null") + .with("Idnt", Value::Text(UnicodeString::new("modern"))) + .with("Trnf", Value::List(quad.iter().flatten().map(|v| Value::Double(*v)).collect())) + .with("quiltWarp", Value::Descriptor(warp)); + let mut bytes = b"soLD".to_vec(); + bytes.extend_from_slice(&4u32.to_be_bytes()); + bytes.extend_from_slice(&VersionedDescriptor::new(descriptor).to_bytes()); + bytes + }; + for key in [*b"SoLd", *b"SoLE"] { + for legacy_first in [false, true] { + for (bytes, expected) in [(modern(5.0), None), (modern(10.0), Some("modern")), (b"soLD".to_vec(), Some("legacy"))] { + let mut blocks = vec![(key, bytes), (*b"PlLd", legacy.clone()), (*b"luni", vec![0])]; + if legacy_first { + blocks.swap(0, 1); + } + let mut doc = WDoc::new(2, 2); + doc.layers = vec![WLayer::empty("placement", blocks)]; + let result = Psd::parse(write(&doc)); + if let Some(uuid) = expected { + let parsed = result.unwrap(); + assert_eq!(parsed.layers[0].smart_object.as_ref().unwrap().uuid, uuid); + assert_eq!(parsed.layers[0].name, "placement", "malformed optional metadata still recovers"); + } else { + assert!(matches!(result, Err(Error::Unsupported(_))), "unsupported modern placement must be reported"); + } + } + } + } +} From 8030fd96e61ca269ec991af2eadf11216ceb49dc Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 10:12:07 +0100 Subject: [PATCH 55/78] fix(psd): pin quilt bounds context validation --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 347669243..ac50cba25 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1449,7 +1449,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c9862964df7f73ad37706539a06e346fc4865ca3#c9862964df7f73ad37706539a06e346fc4865ca3" +source = "git+https://github.com/storytold/craft-libs?rev=d78a99a0a79dcec0ee9cdc49a415c7fd38607454#d78a99a0a79dcec0ee9cdc49a415c7fd38607454" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 551e634fd..937cbb99f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c9862964df7f73ad37706539a06e346fc4865ca3" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d78a99a0a79dcec0ee9cdc49a415c7fd38607454" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } From 981981632c336910c1e8850b9b640f8d7f40da75 Mon Sep 17 00:00:00 2001 From: JCleanCode Date: Wed, 18 Nov 2026 10:25:06 +0100 Subject: [PATCH 56/78] =?UTF-8?q?Fix=20#1986=20Cmd+A=20("select=20all")=20?= =?UTF-8?q?doesn't=20work=20in=20"Import=20multiple=20files=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #1986 **Cause.** On macOS the open panel has no key equivalents of its own. Cmd+A (and C/V/X/Z) work because the menu bar sends `selectAll:`, `copy:` and so on down the responder chain to the key window. EffectCraft's Edit items are custom muda items, so while the sheet was up Cmd+A ran Edit > Select All on the Project panel behind it. **Fix.** The native file dialogs on screen are counted (`native_dialogs`). While one is open on macOS, Undo / Redo / Cut / Copy / Paste / Select All become macOS predefined items, which send the real actions to the dialog. The other `edit.*` items are disabled. The UI is repainted when a dialog opens so the menu is rebuilt before the next key. **Tests.** `edit_menu_is_disabled_while_a_file_dialog_is_open`, `edit_text_commands_are_predefined_while_a_file_dialog_is_open`. Checked by hand on macOS: Cmd+A in "Import multiple files" selects the files. 🤖 Generated with [Claude Code](https://claude.com/claude-code) ## Summary by CodeRabbit * **Bug Fixes** * On macOS, Edit menu commands are disabled while a native file dialog is open and return to their appropriate enabled state when it closes or is canceled. * While a dialog is open, Undo, Redo, Cut, Copy, Paste, and Select All appear as native macOS menu commands with their current labels. * Opening a file dialog now triggers an immediate interface refresh, helping the menu update before the next key event. --- apps/effectcraft/src/main.rs | 9 +- apps/effectcraft/src/native_menu.rs | 6 + crates/ui-egui/src/lib.rs | 5 + crates/ui-egui/src/menus/entries.rs | 6 + crates/ui-egui/src/menus/tests.rs | 35 ++++++ crates/ui-egui/src/native_menu.rs | 164 +++++++++++++++++++++++++++- 6 files changed, 222 insertions(+), 3 deletions(-) diff --git a/apps/effectcraft/src/main.rs b/apps/effectcraft/src/main.rs index 61554858f..a008a7b7a 100644 --- a/apps/effectcraft/src/main.rs +++ b/apps/effectcraft/src/main.rs @@ -441,6 +441,8 @@ fn run_desktop(reporter: &crash_report::Shutdown) -> eframe::Result { #[cfg(target_os = "macos")] menu: native_menu::NativeBar::new(&cc.egui_ctx), #[cfg(target_os = "macos")] + menu_sync: Default::default(), + #[cfg(target_os = "macos")] apple_events: apple_events.connect(&cc.egui_ctx), app, file_dialogs, @@ -531,6 +533,8 @@ struct Desktop { dialog_errors: std::sync::mpsc::Receiver, #[cfg(target_os = "macos")] menu: native_menu::NativeBar, + #[cfg(target_os = "macos")] + menu_sync: effectcraft_ui_egui::native_menu::MenuSync, /// Documents opened from Finder, the Dock or `open` (macOS). #[cfg(target_os = "macos")] apple_events: apple_events::Opened, @@ -547,7 +551,7 @@ impl eframe::App for Desktop { /// file dialogs asked for and, last, hand a close to the platform quit. fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { #[cfg(target_os = "macos")] - self.menu.update(&mut self.app, ctx); + self.menu_sync.before(&mut self.app, |app| self.menu.update(app, ctx)); self.app.tick(ctx, frame); self.app.finish_ime_logic(ctx); while let Ok(e) = self.dialog_errors.try_recv() { @@ -561,6 +565,9 @@ impl eframe::App for Desktop { fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { self.app.ui(ui, frame); + // A file dialog this frame's commands opened (or one that closed) syncs the menu again. + #[cfg(target_os = "macos")] + self.menu_sync.after(&mut self.app, |app| self.menu.update(app, ui.ctx())); if let Some(asked) = &self.file_dialogs { file_dialogs::show_asked(asked, frame, ui.ctx()); } diff --git a/apps/effectcraft/src/native_menu.rs b/apps/effectcraft/src/native_menu.rs index c3b142c5f..f8263fd70 100644 --- a/apps/effectcraft/src/native_menu.rs +++ b/apps/effectcraft/src/native_menu.rs @@ -118,6 +118,12 @@ impl NativeBar { Role::Hide => PredefinedMenuItem::hide(Some(label)), Role::HideOthers => PredefinedMenuItem::hide_others(Some(label)), Role::ShowAll => PredefinedMenuItem::show_all(Some(label)), + Role::SelectAll => PredefinedMenuItem::select_all(Some(label)), + Role::Cut => PredefinedMenuItem::cut(Some(label)), + Role::Copy => PredefinedMenuItem::copy(Some(label)), + Role::Paste => PredefinedMenuItem::paste(Some(label)), + Role::Undo => PredefinedMenuItem::undo(Some(label)), + Role::Redo => PredefinedMenuItem::redo(Some(label)), }; parent.append(&item) } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 717a9a370..5d49d397b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -542,6 +542,11 @@ impl FileDialogsUp { self.count = self.count.saturating_sub(1); } + /// How many dialogs are up, as last checked ([`FileDialogsUp::up`] drops those taken for gone). + pub(crate) fn count(&self) -> usize { + self.count + } + /// Whether a dialog is up at `now`, `focused`: whether one of the app's windows has the /// keyboard. pub(crate) fn up(&mut self, focused: bool, now: f64) -> bool { diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 3391e47bd..c3641196f 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -101,6 +101,12 @@ pub(crate) fn entry_checked(app: &EffectcraftApp, e: &MenuEntry) -> Option } pub(crate) fn entry_enabled(app: &EffectcraftApp, e: &MenuEntry) -> bool { + // A disabled macOS menu item lets its key through, so a native file dialog gets Cmd+A, C, V + // (and Z) instead of the Edit menu acting on the window behind it (#1986). Only macOS: the + // native menu bar owns the keys there, and Linux's portal dialog is a separate window. + if cfg!(target_os = "macos") && e.command.starts_with("edit.") && app.file_dialogs.count() > 0 { + return false; + } // The Project-panel enabled rules mirror the invoke redirects, so they stand down for the // same reason (see the redirect block): while a text edit is open the menu items must be // enabled by what their routed command can do, or the menu grays out commands that work. diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 68c8d3f43..f261d1057 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -448,6 +448,41 @@ fn file_dialogs_block_floating_windows_only_while_up() { assert!(blocked(&mut app, false, 13.1), "a later dialog blocks again"); } +/// While a native file dialog is up, the Edit menu is disabled on macOS so the OS hands Cmd+A +/// to the dialog instead of selecting in the Project panel behind it (#1986). Elsewhere the +/// menu stays as it was. +#[test] +fn edit_menu_is_disabled_while_a_file_dialog_is_open() { + use std::sync::{Arc, Mutex}; + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + app.session.execute("file.openDemoProject", json!({})).unwrap(); + app.ui.focused = PanelKind::Project; + let ctx = egui::Context::default(); + let entries = effectcraft_engine::menus::entries(); + let select_all = entries.iter().map(|(_, e)| e).find(|e| e.command == "edit.selectAll").expect("Select All is in the menu"); + let import = entries.iter().map(|(_, e)| e).find(|e| e.command == "file.import").expect("Import is in the menu"); + assert!(entry_enabled(&app, select_all)); + let steps_aside = cfg!(target_os = "macos"); + let pending: Arc>> = Arc::default(); + let queue = pending.clone(); + app.hooks.file_dialog_async = Some(Box::new(move |_, done| queue.lock().unwrap().push(done))); + invoke(&mut app, &ctx, "file.importMultiple", json!({})).unwrap(); + assert_eq!(!entry_enabled(&app, select_all), steps_aside, "Cmd+A must reach the dialog on macOS only"); + assert!(entry_enabled(&app, import), "only the Edit menu steps aside"); + // Cancelled: the menu is back. + let done = pending.lock().unwrap().pop().expect("a dialog was shown"); + done(Ok(Vec::new())); + app.run_dialog_answers(); + assert!(entry_enabled(&app, select_all)); + // Ended without answering: the menu is back once the dialog is taken for gone. + invoke(&mut app, &ctx, "file.importMultiple", json!({})).unwrap(); + assert_eq!(!entry_enabled(&app, select_all), steps_aside); + let _ = app.file_dialogs.up(true, 0.0); + let _ = app.file_dialogs.up(false, 0.1); + let _ = app.file_dialogs.up(true, 0.2); + assert!(entry_enabled(&app, select_all)); +} + /// #3084: a host whose dialog couldn't open (macOS: `+[NSOpenPanel openPanel]` returned nil) /// answers with the error. The status line says why, the command doesn't run and the dialog /// no longer blocks floating windows; the next dialog opens as usual. diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/native_menu.rs index 1d892b38a..f856db01d 100644 --- a/crates/ui-egui/src/native_menu.rs +++ b/crates/ui-egui/src/native_menu.rs @@ -29,6 +29,12 @@ pub enum Role { Hide, HideOthers, ShowAll, + SelectAll, + Cut, + Copy, + Paste, + Undo, + Redo, } /// One node of the native menu. @@ -151,9 +157,37 @@ pub fn build_now(app: &EffectcraftApp, ctx: &egui::Context) -> NativeMenu { } } let mut menu = build(app); - if text_field_window(ctx).is_some() { + // On macOS a file dialog takes the keys over the field behind it (#1986). + let dialog = cfg!(target_os = "macos") && app.file_dialogs.count() > 0; + if text_field_window(ctx).is_some() && !dialog { enable(app, &mut menu.menus); } + if dialog { + // The sandboxed open panel is a remote view: it gets Cmd+A, C, X, V, Z through the host's + // standard Edit items (first-responder selectors), not through items that run our + // commands, which swallow the key or leave the panel without one (#1986). + fn standard(nodes: &mut [NativeNode]) { + for node in nodes { + match node { + NativeNode::Item(item) => { + let role = match item.command.as_str() { + "edit.selectAll" => Role::SelectAll, + "edit.cut" => Role::Cut, + "edit.copy" => Role::Copy, + "edit.paste" => Role::Paste, + "edit.undo" => Role::Undo, + "edit.redo" => Role::Redo, + _ => continue, + }; + *node = NativeNode::Predefined { role, label: item.label.clone(), command: item.command.clone() }; + } + NativeNode::Submenu { children, .. } => standard(children), + _ => {} + } + } + } + standard(&mut menu.menus); + } menu } @@ -374,12 +408,37 @@ pub fn state_key(app: &EffectcraftApp) -> u64 { s.keymaps.active.hash(&mut h); let v = &app.ui.viewer; (v.rulers, v.guides, v.snap_guides, v.lock_guides, v.grid, v.snap_grid, v.show_layer_controls, v.pasteboard).hash(&mut h); - (app.ui.cache_when_idle, app.session.prefs.preview.active().include_audio, &app.ui.workspace, app.dialog.is_some()).hash(&mut h); + (app.ui.cache_when_idle, app.session.prefs.preview.active().include_audio, &app.ui.workspace, app.dialog.is_some(), app.file_dialogs.count()).hash(&mut h); // Window menu check marks: the panels on screen. crate::dock::PanelKind::ALL.iter().filter(|p| crate::menus::panel_shown(app, **p)).for_each(|p| p.hash(&mut h)); h.finish() } +/// Keeps the native menu in step with native file dialogs within a frame. The menu syncs at the +/// frame's start, but a dialog opened by the frame's commands is counted only after that: sync +/// again then, so its Edit items step aside before the next key (#1986). The second sync runs +/// only when the dialog count changed. +#[derive(Default)] +pub struct MenuSync { + /// Native file dialogs on screen at the last sync. + dialogs: usize, +} + +impl MenuSync { + /// The frame's sync, before its commands run. + pub fn before(&mut self, app: &mut EffectcraftApp, update: impl FnOnce(&mut EffectcraftApp)) { + update(app); + self.dialogs = app.file_dialogs.count(); + } + + /// After the frame's commands: sync again if a file dialog opened or closed meanwhile. + pub fn after(&mut self, app: &mut EffectcraftApp, update: impl FnOnce(&mut EffectcraftApp)) { + if app.file_dialogs.count() != self.dialogs { + self.before(app, update); + } + } +} + /// The window whose text field has the keyboard: a floating panel's own OS window, or the main /// window, where any widget that holds the keyboard counts (the Viewer's text editor is not an /// egui text field). @@ -490,9 +549,37 @@ mod tests { fn app() -> EffectcraftApp { let mut s = effectcraft_engine::Session::default(); s.execute("file.openDemoProject", json!({})).unwrap(); + // The default is "Match System": pin English so the tests do not follow the machine's locale. + s.execute("prefs.set", json!({"key": "general.language", "value": "en"})).unwrap(); EffectcraftApp::new(s) } + /// A file dialog opened by the frame's commands syncs the menu a second time (#1986); a + /// frame without one syncs it once. + #[test] + fn menu_syncs_again_when_a_frame_opens_a_file_dialog() { + let mut app = app(); + let ctx = egui::Context::default(); + let pending: std::sync::Arc>> = Default::default(); + let queue = pending.clone(); + app.hooks.file_dialog_async = Some(Box::new(move |_, done| queue.lock().unwrap().push(done))); + let mut sync = MenuSync::default(); + // A fake menu: records the dialog count each update sees. + let mut updates = Vec::new(); + let mut frame = |app: &mut EffectcraftApp, command: Option<&str>| { + sync.before(app, |a| updates.push(a.file_dialogs.count())); + if let Some(id) = command { + crate::menus::invoke(app, &ctx, id, json!({})).unwrap(); + } + sync.after(app, |a| updates.push(a.file_dialogs.count())); + }; + frame(&mut app, None); + frame(&mut app, Some("file.importMultiple")); + frame(&mut app, None); + assert_eq!(updates, [0, 0, 1, 1], "no dialog: one update; dialog opened: a second one that sees it"); + assert_eq!(pending.lock().unwrap().len(), 1, "a dialog was shown"); + } + #[test] fn every_engine_entry_is_in_the_native_menu() { let app = app(); @@ -822,6 +909,79 @@ mod tests { assert!(edits_text("edit.copy") && edits_text("edit.paste")); assert!(!edits_text("layer.newNull")); } + /// #1986: a file dialog opened while a text field has the keyboard takes Cmd+A: the field + /// behind it does not keep the Edit items enabled. + #[test] + fn a_file_dialog_takes_the_edit_keys_from_a_focused_text_field() { + let mut app = app(); + let ctx = egui::Context::default(); + let mut text = String::new(); + for _ in 0..2 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| ui.text_edit_singleline(&mut text).request_focus()); + out.textures_delta.clear(); + } + let select_all = |m: &NativeMenu| m.items().into_iter().any(|i| i.command == "edit.selectAll" && i.enabled); + assert!(select_all(&build_now(&app, &ctx))); + app.hooks.file_dialog_async = Some(Box::new(|_, _| {})); + crate::menus::invoke(&mut app, &ctx, "file.importMultiple", json!({})).unwrap(); + assert_eq!(select_all(&build_now(&app, &ctx)), !cfg!(target_os = "macos")); + } + + /// #1986: while a file dialog is open on macOS the Edit items for select-all, cut, copy, + /// paste, undo and redo become the host's standard (predefined) items, keeping label and + /// command; without a dialog they stay plain command items. + #[test] + fn a_file_dialog_turns_the_edit_keys_into_standard_items() { + fn predefined(menu: &NativeMenu) -> Vec<(String, Role, String)> { + fn rec(n: &[NativeNode], out: &mut Vec<(String, Role, String)>) { + for x in n { + match x { + NativeNode::Predefined { role, label, command } + if matches!(role, Role::SelectAll | Role::Cut | Role::Copy | Role::Paste | Role::Undo | Role::Redo) => + { + out.push((command.clone(), *role, label.to_string())) + } + NativeNode::Submenu { children, .. } => rec(children, out), + _ => {} + } + } + } + let mut out = vec![]; + rec(&menu.menus, &mut out); + out + } + fn by_command<'a>(menu: &'a NativeMenu, id: &str) -> Option<&'a NativeItem> { + menu.items().into_iter().find(|i| i.command == id) + } + let mut app = app(); + let ctx = egui::Context::default(); + let ids = ["edit.selectAll", "edit.cut", "edit.copy", "edit.paste", "edit.undo", "edit.redo"]; + let before = build_now(&app, &ctx); + assert!(predefined(&before).is_empty(), "no dialog: no standard edit items"); + let plain: Vec<_> = ids.iter().filter(|id| by_command(&before, id).is_some()).collect(); + app.hooks.file_dialog_async = Some(Box::new(|_, _| {})); + crate::menus::invoke(&mut app, &ctx, "file.importMultiple", json!({})).unwrap(); + let after = build_now(&app, &ctx); + let got = predefined(&after); + if cfg!(target_os = "macos") { + let want = [Role::SelectAll, Role::Cut, Role::Copy, Role::Paste, Role::Undo, Role::Redo]; + for (id, role) in ids.iter().zip(want) { + if !plain.contains(&id) { + continue; + } + let (_, r, label) = got.iter().find(|(c, _, _)| c == id).unwrap_or_else(|| panic!("{id} not predefined")); + assert_eq!(*r, role, "{id}"); + assert_eq!(label, &by_command(&before, id).map(|i| i.label.to_string()).unwrap_or_default(), "{id} keeps its label"); + assert!(by_command(&after, id).is_none(), "{id} no longer runs our command"); + } + assert_eq!(got.len(), plain.len()); + // Unrelated items are untouched. + assert!(by_command(&after, "file.importMultiple").is_some()); + } else { + assert!(got.is_empty()); + } + } + /// #2459: while a text field has the keyboard the Edit menu's Undo and Redo act on the field and /// read plain "Undo" / "Redo"; the project history labels come back once focus leaves. #[test] From 67942cda7b0821eb83234f78196df6c43ceb0abd Mon Sep 17 00:00:00 2001 From: Sean Hawkey <62113798+GenuineMoron@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:25:57 +0800 Subject: [PATCH 57/78] Expressions: a layer parameter left at None is the layer it sits on (#3601) Fixes #3601. ### What A layer parameter left at None (a Layer Control, or an effect's layer parameter) now stands for the layer it sits on, as in After Effects (values observed in AE 26.3 are in #3601). Before, its value was `null`. The property was still truthy, so a rig's `L ? L.sourceRectAtTime(t) : 0` went down the wrong branch and stopped with "not a callable function". The change is one line in `Prop.__wrap` (`crates/expr/src/prelude.js`). ### Tested - **`an_empty_layer_control_stands_for_its_own_layer`** in `crates/expr/src/tests.rs`: truthiness, `name`, `index`, the `L ? L.transform.position[0] : -1` pattern, and `sourceRectAtTime`. It fails without the change. - **Suites:** `cargo test -p effectcraft-expr` (167 passed) and `cargo test -p effectcraft-script` pass. clippy and fmt are clean. - **Not covered here:** calling the empty parameter like a layer (`L("ADBE Transform Group")`). That depends on #3554, and works with both applied. --- crates/expr/src/prelude.js | 10 ++++++--- crates/expr/src/tests.rs | 46 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/crates/expr/src/prelude.js b/crates/expr/src/prelude.js index 678dd6816..97fa64af1 100644 --- a/crates/expr/src/prelude.js +++ b/crates/expr/src/prelude.js @@ -870,14 +870,18 @@ Prop.prototype = { propertyGroup: function (n) { return __ancestor(this.__c, this.__l, this.__p, n); }, __wrap: function (v) { var kind = this.__info[2]; - if (kind === 'layer') return v === null ? null : __layer(this.__c, v); + // A layer parameter set to None is the layer it sits on, as in After Effects. + if (kind === 'layer') return __layer(this.__c, v === null ? this.__l : v); if (kind === 'path' && v !== null) return new __Path(v[0], v[1], v[2], v[3]); return v; }, - get value() { return this.__self ? value : this.valueAtTime(time); }, + get value() { return this.__self ? this.__selfValue() : this.valueAtTime(time); }, + // The evaluated property's own value: a layer parameter reads as its layer here too. + // (After posterizeTime, `value` may already be the layer.) + __selfValue: function () { return this.__info[2] === 'layer' && !value?.__isLayer ? this.__wrap(value) : value; }, valueAtTime: function (t) { t = __v(t); - if (this.__self && t === time) return value; + if (this.__self && t === time) return this.__selfValue(); return this.__wrap(__h(__VALUE, this.__c, this.__l, this.__p, t, this.__self)); }, velocityAtTime: function (t) { diff --git a/crates/expr/src/tests.rs b/crates/expr/src/tests.rs index e4df95ac4..dafb52e6a 100644 --- a/crates/expr/src/tests.rs +++ b/crates/expr/src/tests.rs @@ -1928,6 +1928,52 @@ fn layer_control_property_stands_for_its_layer() { assert_close!(f.num("effect('Map')(1).value.name == 'B' ? 1 : 0", 0.0), 1.0); } +#[test] +fn an_empty_layer_control_stands_for_its_own_layer() { + // In After Effects a Layer Control set to None gives the layer the effect is on: truthy, named + // and callable as that layer. Rigs test it with `L ? … : …` and then read `L.sourceRectAtTime`. + let mut f = fx(); + let spec = effectcraft_effects::find("ec.control.layer").unwrap(); + let mut map = group_push(&mut f.p, |ids| effectcraft_effects::instantiate(spec, ids, "Map", [20.0, 20.0])); + map.prop_mut("layer").unwrap().value = Value::Layer(None); + f.p.comp_mut(f.cid).unwrap().layers[0].props.sub_mut("effects").unwrap().children.push(map.into()); + assert_close!(f.num("effect('Map')(1) ? 1 : 0", 0.0), 1.0); + assert_close!(f.num("effect('Map')(1).name == thisLayer.name ? 1 : 0", 0.0), 1.0); + assert_close!(f.num("effect('Map')(1).index", 0.0), 1.0); + assert_close!(f.num("var L = effect('Map')(1); L ? L.transform.position[0] : -1", 0.0), 50.0); + assert_close!(f.num("effect('Map')(1).sourceRectAtTime(time).width == thisLayer.sourceRectAtTime(time).width ? 1 : 0", 0.0), 1.0); +} + +#[test] +fn a_layer_parameters_own_expression_reads_its_layer() { + // An expression on the layer parameter itself: `thisProperty.value` and + // `thisProperty.valueAtTime(time)` give the layer, as reads from other properties do. + let mut f = fx(); + let spec = effectcraft_effects::find("ec.control.layer").unwrap(); + let mut empty = group_push(&mut f.p, |ids| effectcraft_effects::instantiate(spec, ids, "Empty", [20.0, 20.0])); + empty.prop_mut("layer").unwrap().value = Value::Layer(None); + let mut set = group_push(&mut f.p, |ids| effectcraft_effects::instantiate(spec, ids, "Set", [20.0, 20.0])); + set.prop_mut("layer").unwrap().value = Value::Layer(Some(f.b.0)); + let fx_group = f.p.comp_mut(f.cid).unwrap().layers[0].props.sub_mut("effects").unwrap(); + fx_group.children.push(empty.into()); + fx_group.children.push(set.into()); + let n = f.p.comp(f.cid).unwrap().layers[0].props.sub("effects").unwrap().children.len(); + let (empty_path, set_path) = (format!("effects/#{}/layer", n - 1), format!("effects/#{n}/layer")); + // Each expression throws unless it reads the right layer's name. + for (path, read, want) in [ + (&empty_path, "thisProperty.value", "A"), + (&empty_path, "thisProperty.valueAtTime(time)", "A"), + (&set_path, "thisProperty.value", "B"), + (&set_path, "thisProperty.valueAtTime(time)", "B"), + ] { + let e = format!("if ({read}.name !== '{want}') throw new Error('read ' + {read}); value"); + f.ev(f.a, path, &e, 0.0).unwrap_or_else(|err| panic!("{path} {read}: {err}")); + // After posterizeTime moves the sample time, `value` already holds the layer. + let e = format!("posterizeTime(1); if ({read}.name !== '{want}') throw new Error('read ' + {read}); value"); + f.ev(f.a, path, &e, 0.5).unwrap_or_else(|err| panic!("posterized {path} {read}: {err}")); + } +} + #[test] fn time_to_frames_rounds_durations_away_from_zero() { let f = fx(); From e48cfde63facaa3384392f31476c8ddb494ac32a Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 10:40:03 +0100 Subject: [PATCH 58/78] fix(psd): pin corrected quilt policy test revision --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ac50cba25..bb7e32e31 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1449,7 +1449,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d78a99a0a79dcec0ee9cdc49a415c7fd38607454#d78a99a0a79dcec0ee9cdc49a415c7fd38607454" +source = "git+https://github.com/storytold/craft-libs?rev=e1fc4b1376148197c2cfd2381eeb400e2731269a#e1fc4b1376148197c2cfd2381eeb400e2731269a" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 937cbb99f..b5d7cedc0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d78a99a0a79dcec0ee9cdc49a415c7fd38607454" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e1fc4b1376148197c2cfd2381eeb400e2731269a" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } From 648ae785915de614063f1afbfeb340a743185bf8 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Wed, 18 Nov 2026 15:27:36 +0530 Subject: [PATCH 59/78] #3830: test the .3dl cap through an injectable limit; drop the local .spi3d precheck (#3831 belongs in craft-cms) --- crates/effects/src/ocio/lut.rs | 27 +++++++++----------------- crates/effects/src/ocio/tests.rs | 33 +++++++++++++++++--------------- 2 files changed, 27 insertions(+), 33 deletions(-) diff --git a/crates/effects/src/ocio/lut.rs b/crates/effects/src/ocio/lut.rs index f7ae08986..6868dff46 100644 --- a/crates/effects/src/ocio/lut.rs +++ b/crates/effects/src/ocio/lut.rs @@ -32,26 +32,17 @@ pub fn parse_spi1d(text: &str) -> Option { /// Parse a Sony Imageworks `.spi3d` lattice: `SPILUT 1.0`, `3 3`, the sizes, then one /// `r g b R G B` line per lattice point (indices, then the colour). pub fn parse_spi3d(text: &str) -> Option { - if !spi3d_rows_present(text) { - return None; - } let value = craft_cms::sony_lut::parse_spi3d(text)?; Some(Lut { n1: 0, d1: vec![], n3: value.size, d3: value.values, dmin: [0.0; 3], dmax: [1.0; 3] }) } -/// Whether a `.spi3d` file has at least as many rows as its header's lattice claims. The shared -/// reader reserves the whole lattice before it reads a row, so a short file is turned away -/// first (#3831). Counting stops at the claimed volume; nothing is allocated. -pub(super) fn spi3d_rows_present(text: &str) -> bool { - let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty()).skip(2); - let Some(n) = lines.next().and_then(|l| l.split_whitespace().next()?.parse::().ok()) else { - return false; - }; - n.checked_pow(3).is_some_and(|count| lines.take(count).count() == count) -} - /// Parse an Autodesk `.3dl` lattice (integers, blue fastest; an optional input-mesh line). pub fn parse_3dl(text: &str) -> Option { + parse_3dl_limited(text, MAX_LATTICE) +} + +/// [`parse_3dl`] with the largest accepted lattice side as a parameter, so tests can reach it. +pub(super) fn parse_3dl_limited(text: &str, max_side: usize) -> Option { let mut mesh: Option> = None; let mut rows: Vec<[f64; 3]> = vec![]; let mut out_bits: Option = None; @@ -68,15 +59,15 @@ pub fn parse_3dl(text: &str) -> Option { } continue; } - let v: Vec = l.split_whitespace().filter_map(|t| t.parse().ok()).take(MAX_LATTICE + 1).collect(); + let v: Vec = l.split_whitespace().filter_map(|t| t.parse().ok()).take(max_side.saturating_add(1)).collect(); if v.len() > 3 && mesh.is_none() && rows.is_empty() { // The mesh length is the lattice side: refuse one no lattice reader accepts (#3830). - if v.len() > MAX_LATTICE { + if v.len() > max_side { return None; } mesh = Some(v); } else if v.len() == 3 { - if rows.len() >= MAX_LATTICE.pow(3) { + if rows.len() >= max_side.saturating_pow(3) { return None; } rows.push([v[0], v[1], v[2]]); @@ -96,7 +87,7 @@ pub fn parse_3dl(text: &str) -> Option { Some(m) => m.len(), None => (rows.len() as f64).cbrt().round() as usize, }; - if !(2..=MAX_LATTICE).contains(&n) || n.checked_pow(3) != Some(rows.len()) { + if !(2..=max_side).contains(&n) || n.checked_pow(3) != Some(rows.len()) { return None; } let maxv = rows.iter().flat_map(|r| r.iter()).fold(0.0f64, |m, &v| m.max(v)); diff --git a/crates/effects/src/ocio/tests.rs b/crates/effects/src/ocio/tests.rs index 3952a8ab3..a11fe32f5 100644 --- a/crates/effects/src/ocio/tests.rs +++ b/crates/effects/src/ocio/tests.rs @@ -553,9 +553,7 @@ fn a_3dl_with_a_hostile_mesh_is_refused_without_overflow() { // #3830: 2 642 246³ is past usize::MAX, so cubing the mesh length overflowed. let huge = "0 ".repeat(2_642_246) + "\n0 0 0\n"; assert!(parse_file(&huge, "3dl").is_none()); - // A mesh longer than any lattice the readers accept, and a mesh whose rows run out. - let long = (0..130).map(|i| i.to_string()).collect::>().join(" ") + "\n0 0 0\n"; - assert!(parse_file(&long, "3dl").is_none()); + // A mesh whose rows run out. let short = (0..17).map(|i| (i * 64).to_string()).collect::>().join(" ") + "\n0 0 0\n1 1 1\n"; assert!(parse_file(&short, "3dl").is_none()); // A normal small table still loads. @@ -566,18 +564,23 @@ fn a_3dl_with_a_hostile_mesh_is_refused_without_overflow() { assert!(matches!(parse_file(&ok, "3dl"), Some(FileXform::Lut { lut, .. }) if lut.n3 == 3 && lut.d3.len() == 27)); } +/// A complete `.3dl` table of side `n`, with its input mesh line or without one. +fn table_3dl(n: usize, mesh: bool) -> String { + let mut text = if mesh { (0..n).map(|i| (i * 1023 / (n - 1)).to_string()).collect::>().join(" ") + "\n" } else { String::new() }; + for k in 0..n * n * n { + text += &format!("{} {} {}\n", k % 1024, k % 1024, k % 1024); + } + text +} + #[test] -fn a_spi3d_without_its_rows_is_refused_before_the_lattice_is_reserved() { - // #3831: a header-only 129³ claim must not reach the reader that reserves the whole lattice. - let empty = "SPILUT 1.0\n3 3\n129 129 129\n"; - assert!(!lut::spi3d_rows_present(empty)); - assert!(!lut::spi3d_rows_present("SPILUT 1.0\n3 3\n2 2 2\n0 0 0 1 1 1\n")); - assert!(!lut::spi3d_rows_present("SPILUT 1.0\n3 3\n99999999999 2 2\n")); - assert!(parse_spi3d(empty).is_none()); - let mut ok = String::from("SPILUT 1.0\n3 3\n2 2 2\n"); - for i in 0..8 { - ok += &format!("{} {} {} 0 0 0\n", i & 1, (i >> 1) & 1, i >> 2); +fn a_3dl_lattice_is_capped_at_the_largest_side() { + // #3830: a complete table at the cap loads, and one a side larger is refused, with or without + // its mesh line (without one, row collection stops at the cap's volume). + for mesh in [true, false] { + let at = lut::parse_3dl_limited(&table_3dl(4, mesh), 4); + assert!(at.is_some_and(|l| l.n3 == 4 && l.d3.len() == 64), "mesh {mesh}"); + assert!(lut::parse_3dl_limited(&table_3dl(5, mesh), 4).is_none(), "mesh {mesh}"); + assert!(lut::parse_3dl_limited(&table_3dl(5, mesh), 5).is_some(), "mesh {mesh}"); } - assert!(lut::spi3d_rows_present(&ok)); - assert!(parse_spi3d(&ok).is_some_and(|l| l.n3 == 2 && l.d3.len() == 8)); } From bf31b6527123afbcd3fc53be041ba51e3afe213d Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Wed, 18 Nov 2026 15:38:08 +0530 Subject: [PATCH 60/78] #3830: keep four .3dl tokens and a spare mesh row at small limits --- crates/effects/src/ocio/lut.rs | 6 ++++-- crates/effects/src/ocio/tests.rs | 5 +++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/effects/src/ocio/lut.rs b/crates/effects/src/ocio/lut.rs index 6868dff46..8424e33cd 100644 --- a/crates/effects/src/ocio/lut.rs +++ b/crates/effects/src/ocio/lut.rs @@ -59,7 +59,7 @@ pub(super) fn parse_3dl_limited(text: &str, max_side: usize) -> Option { } continue; } - let v: Vec = l.split_whitespace().filter_map(|t| t.parse().ok()).take(max_side.saturating_add(1)).collect(); + let v: Vec = l.split_whitespace().filter_map(|t| t.parse().ok()).take(max_side.max(3).saturating_add(1)).collect(); if v.len() > 3 && mesh.is_none() && rows.is_empty() { // The mesh length is the lattice side: refuse one no lattice reader accepts (#3830). if v.len() > max_side { @@ -67,7 +67,9 @@ pub(super) fn parse_3dl_limited(text: &str, max_side: usize) -> Option { } mesh = Some(v); } else if v.len() == 3 { - if rows.len() >= max_side.saturating_pow(3) { + // One spare row while no mesh is known: a 3-entry mesh reads as a data row until the + // count tells them apart below. + if rows.len() >= max_side.saturating_pow(3).saturating_add(usize::from(mesh.is_none())) { return None; } rows.push([v[0], v[1], v[2]]); diff --git a/crates/effects/src/ocio/tests.rs b/crates/effects/src/ocio/tests.rs index a11fe32f5..afeabea22 100644 --- a/crates/effects/src/ocio/tests.rs +++ b/crates/effects/src/ocio/tests.rs @@ -583,4 +583,9 @@ fn a_3dl_lattice_is_capped_at_the_largest_side() { assert!(lut::parse_3dl_limited(&table_3dl(5, mesh), 4).is_none(), "mesh {mesh}"); assert!(lut::parse_3dl_limited(&table_3dl(5, mesh), 5).is_some(), "mesh {mesh}"); } + // A 3-entry mesh reads as a 28th row until the count separates it, and a four-value row is + // still refused at the smallest limit. + assert!(lut::parse_3dl_limited(&table_3dl(3, true), 3).is_some_and(|l| l.n3 == 3)); + let four = table_3dl(2, false).replacen("7 7 7", "7 7 7 7", 1); + assert!(lut::parse_3dl_limited(&four, 2).is_none()); } From c6612da7986ada222eeff03b8b9798b14811c00f Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Wed, 18 Nov 2026 15:46:04 +0530 Subject: [PATCH 61/78] #3830: tell a 3-entry .3dl mesh apart by the row count alone --- crates/effects/src/ocio/lut.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/crates/effects/src/ocio/lut.rs b/crates/effects/src/ocio/lut.rs index 8424e33cd..8674d9bd9 100644 --- a/crates/effects/src/ocio/lut.rs +++ b/crates/effects/src/ocio/lut.rs @@ -77,12 +77,8 @@ pub(super) fn parse_3dl_limited(text: &str, max_side: usize) -> Option { return None; } } - let is_cube = |k: usize| { - let n = (k as f64).cbrt().round() as usize; - n * n * n == k - }; - // A 3-entry input mesh (3³ lattice) looks like a data row: tell them apart by the count. - if mesh.is_none() && !is_cube(rows.len()) && rows.len() == 28 { + // A 3-entry input mesh (3³ lattice) looks like a data row: 28 rows are a mesh and 27. + if mesh.is_none() && rows.len() == 28 { mesh = Some(rows.remove(0).to_vec()); } let n = match &mesh { From c149bb513f52b886b3ec7c7cdff6918f8ca9abed Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 13:19:34 +0100 Subject: [PATCH 62/78] psd: read vector mask records through craft-psd --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/psd/src/parse.rs | 48 ++++++--------- crates/psd/src/tests.rs | 1 + crates/psd/src/tests/vector_records.rs | 85 ++++++++++++++++++++++++++ 5 files changed, 108 insertions(+), 30 deletions(-) create mode 100644 crates/psd/src/tests/vector_records.rs diff --git a/Cargo.lock b/Cargo.lock index bb7e32e31..91318f8fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1449,7 +1449,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e1fc4b1376148197c2cfd2381eeb400e2731269a#e1fc4b1376148197c2cfd2381eeb400e2731269a" +source = "git+https://github.com/storytold/craft-libs?rev=a557fed94e0f528c281b4bab241eb518b7f756ac#a557fed94e0f528c281b4bab241eb518b7f756ac" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index b5d7cedc0..62c38f6f3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e1fc4b1376148197c2cfd2381eeb400e2731269a" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a557fed94e0f528c281b4bab241eb518b7f756ac" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } diff --git a/crates/psd/src/parse.rs b/crates/psd/src/parse.rs index 5bcb38cc0..d8993b7b9 100644 --- a/crates/psd/src/parse.rs +++ b/crates/psd/src/parse.rs @@ -247,45 +247,37 @@ impl Psd { l.smart_object = Some(placed::from_craft_smart(craft_psd::smart::SmartObject::from_placed_layer(b).map_err(|e| error(&e))?)); } b"vmsk" | b"vsms" => { - let _ver = r.u32()?; - let flags = r.u32()?; - l.vector_mask = Some(self.vector_paths(&mut r, flags)?); + let block = craft_psd::path::VectorMaskBlock::from_bytes(b).map_err(|e| error(&e))?; + l.vector_mask = Some(self.vector_paths(&block)); } _ => {} } Ok(()) } - fn vector_paths(&self, r: &mut Reader, flags: u32) -> Result { + fn vector_paths(&self, block: &craft_psd::path::VectorMaskBlock) -> VectorMask { + use craft_psd::path::{VectorMaskBlock, selector}; let (w, h) = (self.width as f64, self.height as f64); - let mut vm = VectorMask { inverted: flags & 1 != 0, disabled: flags & 4 != 0, subpaths: vec![] }; - let fixed = |r: &mut Reader| -> Result { Ok(r.i32()? as f64 / (1 << 24) as f64) }; - while r.remaining() >= 26 { - let sel = r.u16()?; - match sel { - 0 | 3 => { - let _n = r.u16()?; - r.skip(22)?; - vm.subpaths.push(SubPath { closed: sel == 0, knots: vec![] }); - } - 1 | 2 | 4 | 5 => { - let mut pts = [[0.0; 2]; 3]; - for p in &mut pts { - let y = fixed(r)?; - let x = fixed(r)?; - *p = [x * w, y * h]; - } - if let Some(sp) = vm.subpaths.last_mut() { - sp.knots.push(pts); - } - } - _ => r.skip(24)?, + let mut vm = VectorMask { + inverted: block.flags & VectorMaskBlock::FLAG_INVERT != 0, + disabled: block.flags & VectorMaskBlock::FLAG_DISABLED != 0, + subpaths: vec![], + }; + // Keep Effect's recovery policy: ignore declared counts and orphan knots, and + // keep mixed open/closed knot selectors in the last declared subpath. + // PathData::subpaths deliberately has a different, more permissive policy. + for record in &block.path.records { + if record.is_length() { + vm.subpaths.push(SubPath { closed: record.selector == selector::CLOSED_LENGTH, knots: vec![] }); + } else if let Some(knot) = record.knot() + && let Some(sp) = vm.subpaths.last_mut() + { + sp.knots.push([knot.pre, knot.anchor, knot.post].map(|(x, y)| [x * w, y * h])); } } vm.subpaths.retain(|s| !s.knots.is_empty()); - Ok(vm) + vm } - /// The layer tree, top of the stack first. Groups nest at most [`MAX_GROUP_DEPTH`] deep (see /// [`Psd::tree_report`]). pub fn tree(&self) -> Vec { diff --git a/crates/psd/src/tests.rs b/crates/psd/src/tests.rs index 1f84f27b7..8c1e211a9 100644 --- a/crates/psd/src/tests.rs +++ b/crates/psd/src/tests.rs @@ -5,6 +5,7 @@ use crate::pixels::srgb_encode; mod integration; mod opt; mod shared_corpus; +mod vector_records; fn gradient(w: u32, h: u32) -> Vec<[f32; 4]> { (0..w * h).map(|i| [(i % w) as f32 / (w - 1).max(1) as f32, (i / w) as f32 / (h - 1).max(1) as f32, 0.25, 1.0]).collect() diff --git a/crates/psd/src/tests/vector_records.rs b/crates/psd/src/tests/vector_records.rs new file mode 100644 index 000000000..246596ca4 --- /dev/null +++ b/crates/psd/src/tests/vector_records.rs @@ -0,0 +1,85 @@ +use super::*; + +// Independent wire fixtures: do not use the shared path encoder to test its decoder. +fn record(selector: u16, data: [u8; 24]) -> Vec { + let mut out = selector.to_be_bytes().to_vec(); + out.extend_from_slice(&data); + out +} + +fn length(selector: u16, count: u16) -> Vec { + let mut data = [0; 24]; + data[..2].copy_from_slice(&count.to_be_bytes()); + record(selector, data) +} + +fn knot(selector: u16) -> Vec { + let mut data = [0; 24]; + // Stored y then x, including negative and outside-document coordinates. + for (chunk, value) in data.chunks_exact_mut(4).zip([-(1i32 << 23), 1 << 22, 1 << 24, -(1 << 24), 1 << 23, 1 << 25]) { + chunk.copy_from_slice(&value.to_be_bytes()); + } + record(selector, data) +} + +fn parse_mask(key: [u8; 4], bytes: Vec) -> Option { + let mut doc = WDoc::new(64, 32); + doc.layers = vec![WLayer::empty("mask", vec![(key, bytes)])]; + Psd::parse(write(&doc)).unwrap().layers.remove(0).vector_mask +} + +fn header(version: u32, flags: u32) -> Vec { + [version.to_be_bytes(), flags.to_be_bytes()].concat() +} + +#[test] +fn vector_masks_preserve_record_recovery_and_dimension_mapping() { + for key in [*b"vmsk", *b"vsms"] { + for version in [3, 99] { + for tail in 0..26 { + let mut bytes = header(version, 1 | 2 | 4 | 0x80); + bytes.extend(knot(1)); // Orphan knots are ignored, not made into a path. + bytes.extend(length(0, u16::MAX)); // Empty subpath is removed. + bytes.extend(length(3, 0)); // Counts do not control app grouping. + for selector in [1, 2, 4, 5] { + bytes.extend(knot(selector)); // Keep mixed selectors in the open path. + } + bytes.extend(record(0xffff, [0xff; 24])); + bytes.extend(length(0, 1)); + bytes.extend(knot(4)); + bytes.extend(knot(2)); // More knots than declared still belong to this path. + bytes.extend(length(3, 1)); // Empty final path is removed too. + bytes.extend(std::iter::repeat_n(0xff, tail)); + let mask = parse_mask(key, bytes).unwrap(); + assert!(mask.inverted && mask.disabled); + assert_eq!(mask.subpaths.len(), 2); + assert!(!mask.subpaths[0].closed); + assert!(mask.subpaths[1].closed); + assert_eq!(mask.subpaths[0].knots.len(), 4); + assert_eq!(mask.subpaths[1].knots.len(), 2); + for path in mask.subpaths { + for points in path.knots { + assert_eq!(points, [[16.0, -16.0], [-64.0, 32.0], [128.0, 16.0]]); + } + } + } + } + } +} + +#[test] +fn vector_masks_preserve_short_header_and_empty_path_recovery() { + for key in [*b"vmsk", *b"vsms"] { + let bytes = header(3, 0); + for len in 0..8 { + assert!(parse_mask(key, bytes[..len].to_vec()).is_none()); + } + for records in [vec![], knot(5), length(3, u16::MAX), record(8, [0xff; 24])] { + let mut bytes = header(3, 2 | 0x80); + bytes.extend(records); + let mask = parse_mask(key, bytes).unwrap(); + assert!(!mask.inverted && !mask.disabled); + assert!(mask.subpaths.is_empty()); + } + } +} From 82cf1b5c5e6a308e028219fe10dca397bdbf7232 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 13:39:15 +0100 Subject: [PATCH 63/78] psd: align vector fixtures with fixed-size chunk lint --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/psd/src/tests/vector_records.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 91318f8fd..10b750e60 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1449,7 +1449,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a557fed94e0f528c281b4bab241eb518b7f756ac#a557fed94e0f528c281b4bab241eb518b7f756ac" +source = "git+https://github.com/storytold/craft-libs?rev=4d2784ec90413e53b8f6c1a1c6b8526b8077e8c5#4d2784ec90413e53b8f6c1a1c6b8526b8077e8c5" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 62c38f6f3..ca4970bc2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a557fed94e0f528c281b4bab241eb518b7f756ac" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "4d2784ec90413e53b8f6c1a1c6b8526b8077e8c5" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } diff --git a/crates/psd/src/tests/vector_records.rs b/crates/psd/src/tests/vector_records.rs index 246596ca4..531650835 100644 --- a/crates/psd/src/tests/vector_records.rs +++ b/crates/psd/src/tests/vector_records.rs @@ -16,7 +16,7 @@ fn length(selector: u16, count: u16) -> Vec { fn knot(selector: u16) -> Vec { let mut data = [0; 24]; // Stored y then x, including negative and outside-document coordinates. - for (chunk, value) in data.chunks_exact_mut(4).zip([-(1i32 << 23), 1 << 22, 1 << 24, -(1 << 24), 1 << 23, 1 << 25]) { + for (chunk, value) in data.as_chunks_mut::<4>().0.iter_mut().zip([-(1i32 << 23), 1 << 22, 1 << 24, -(1 << 24), 1 << 23, 1 << 25]) { chunk.copy_from_slice(&value.to_be_bytes()); } record(selector, data) From 47384980a4bbf1e03ce94d8e06f9c5fa057295b1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 07:44:01 -0500 Subject: [PATCH 64/78] psd: cover the shared PackBits row-limit error mapping The recovery wrapper maps every non-decompress failure to Error::Invalid so a limit refusal is never reported as truncated data. That arm had no test, which left the changed lines under the coverage gate. --- crates/psd/src/tests.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/psd/src/tests.rs b/crates/psd/src/tests.rs index e2b92b180..7fe3fe387 100644 --- a/crates/psd/src/tests.rs +++ b/crates/psd/src/tests.rs @@ -609,3 +609,10 @@ fn shared_packbits_keeps_padded_rows_and_truncated_packet_errors() { unpack_bits(&[0, 9, 255], 1, &mut row).unwrap(); assert_eq!(row, [9]); } + +#[test] +fn shared_packbits_reports_row_limits_as_invalid_not_truncated() { + // The shared recovery decoder refuses a row beyond its decoded-size limit. That refusal + // is a limit, not truncated PackBits data, so the wrapper must not report it as one. + assert!(matches!(unpack_bits(&[], usize::MAX, &mut Vec::new()), Err(Error::Invalid(_)))); +} From 67e6e27fa78e570c695a597a7cee74661e22ff02 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 14:27:17 +0100 Subject: [PATCH 65/78] psd: share Unicode layer-name record framing --- crates/psd/src/descriptor.rs | 12 ---- crates/psd/src/parse.rs | 8 ++- crates/psd/src/tests.rs | 1 + crates/psd/src/tests/unicode_name.rs | 86 ++++++++++++++++++++++++++++ 4 files changed, 94 insertions(+), 13 deletions(-) create mode 100644 crates/psd/src/tests/unicode_name.rs diff --git a/crates/psd/src/descriptor.rs b/crates/psd/src/descriptor.rs index 56d75e7b3..37e7cb94b 100644 --- a/crates/psd/src/descriptor.rs +++ b/crates/psd/src/descriptor.rs @@ -114,18 +114,6 @@ impl Descriptor { } } -pub(crate) fn read_unicode(r: &mut Reader) -> Result { - let n = r.u32()? as usize; - let mut v = Vec::with_capacity(n.min(r.remaining() / 2)); - for _ in 0..n { - v.push(r.u16()?); - } - while v.last() == Some(&0) { - v.pop(); - } - Ok(String::from_utf16_lossy(&v)) -} - /// Preserve the application parser's per-container limits in the shared parser. pub(crate) const PARSE_LIMITS: craft_psd::descriptor::ParseLimits = craft_psd::descriptor::ParseLimits { max_descriptor_items: 100_000, max_list_items: 1_000_000 }; diff --git a/crates/psd/src/parse.rs b/crates/psd/src/parse.rs index 5bcb38cc0..633b5ac90 100644 --- a/crates/psd/src/parse.rs +++ b/crates/psd/src/parse.rs @@ -144,7 +144,13 @@ impl Psd { let mut r = Reader::new(b); match key { b"luni" => { - let name = descriptor::read_unicode(&mut r)?; + // Shared framing rejects truncated counts/payloads before allocation. Only + // the first record belongs to this block; UTF-16 repair and naming stay local. + let units = craft_psd::unicode_names::records(b).next().ok_or(Error::Truncated)?; + let mut name: String = char::decode_utf16(units.as_chunks::<2>().0.iter().map(|v| u16::from_be_bytes(*v))) + .map(|v| v.unwrap_or(char::REPLACEMENT_CHARACTER)) + .collect(); + name.truncate(name.trim_end_matches('\0').len()); if !name.is_empty() { l.name = name; } diff --git a/crates/psd/src/tests.rs b/crates/psd/src/tests.rs index 1f84f27b7..7406c0345 100644 --- a/crates/psd/src/tests.rs +++ b/crates/psd/src/tests.rs @@ -5,6 +5,7 @@ use crate::pixels::srgb_encode; mod integration; mod opt; mod shared_corpus; +mod unicode_name; fn gradient(w: u32, h: u32) -> Vec<[f32; 4]> { (0..w * h).map(|i| [(i % w) as f32 / (w - 1).max(1) as f32, (i / w) as f32 / (h - 1).max(1) as f32, 0.25, 1.0]).collect() diff --git a/crates/psd/src/tests/unicode_name.rs b/crates/psd/src/tests/unicode_name.rs new file mode 100644 index 000000000..8785b1a49 --- /dev/null +++ b/crates/psd/src/tests/unicode_name.rs @@ -0,0 +1,86 @@ +use super::*; + +fn record(units: &[u16]) -> Vec { + let mut bytes = (units.len() as u32).to_be_bytes().to_vec(); + bytes.extend(units.iter().flat_map(|v| v.to_be_bytes())); + bytes +} + +fn parse_name(blocks: Vec>) -> String { + let mut doc = WDoc::new(1, 1); + doc.layers = vec![WLayer::empty("Fallback", blocks.into_iter().map(|b| (*b"luni", b)).collect())]; + Psd::parse(write(&doc)).unwrap().layers.remove(0).name +} + +#[test] +fn unicode_names_preserve_lossy_utf16_and_trailing_nul_policy() { + for (units, expected) in [ + (vec![], "Fallback"), + (vec![0, 0], "Fallback"), + (vec![65], "A"), + (vec![65, 0, 0], "A"), + (vec![0, 65, 0, 66, 0], "\0A\0B"), + (vec![0x00e4, 0xd83d, 0xde00], "\u{e4}\u{1f600}"), + (vec![0xd800, 65, 0xdc00, 0], "\u{fffd}A\u{fffd}"), + (vec![0xd800, 0], "\u{fffd}"), + (vec![0xd800, 0xd83d, 0xde00, 0xdc00], "\u{fffd}\u{1f600}\u{fffd}"), + ] { + assert_eq!(parse_name(vec![record(&units)]), expected, "{units:?}"); + } +} + +#[test] +fn unicode_name_uses_first_complete_record_and_recovers_in_block_order() { + let first = record(&[65]); + let mut combined = first.clone(); + combined.extend(record(&[66])); + combined.extend([0xff, 0]); + assert_eq!(parse_name(vec![combined]), "A"); + let mut empty_then_name = record(&[]); + empty_then_name.extend(record(&[66])); + assert_eq!(parse_name(vec![empty_then_name]), "Fallback"); + for suffix in [vec![], vec![0xff], vec![0, 0, 0], vec![0xff; 8]] { + let mut bytes = first.clone(); + bytes.extend(suffix); + assert_eq!(parse_name(vec![bytes]), "A"); + } + let mut malformed = vec![vec![], vec![0], vec![0, 0], vec![0, 0, 0], vec![0, 0, 0, 1], vec![0, 0, 0, 1, 0]]; + malformed.push([2u32.to_be_bytes().as_slice(), &[0, 65, 0]].concat()); + malformed.push(u32::MAX.to_be_bytes().to_vec()); + for bad in malformed { + assert_eq!(parse_name(vec![bad.clone()]), "Fallback"); + assert_eq!(parse_name(vec![first.clone(), bad.clone(), record(&[0, 0])]), "A"); + assert_eq!(parse_name(vec![bad, record(&[66])]), "B"); + } + assert_eq!(parse_name(vec![first, record(&[66])]), "B"); +} + +#[test] +fn unicode_layer_name_writer_keeps_code_unit_count_without_added_terminator() { + for name in ["", "A", "\u{e4}\u{1f600}", "A\0", "\0B\0"] { + let mut doc = WDoc::new(1, 1); + doc.layers = vec![WLayer::empty(name, vec![])]; + let bytes = write(&doc); + let file = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let block = file.layer_info.as_ref().unwrap().layers[0].block(b"luni").unwrap(); + let units: Vec<_> = name.encode_utf16().collect(); + assert_eq!(block.data, record(&units)); + } +} + +#[test] +fn missing_empty_or_malformed_unicode_name_keeps_pascal_name() { + let mut doc = WDoc::new(1, 1); + doc.layers = vec![WLayer::empty("Generated Unicode name", vec![])]; + let bytes = write(&doc); + for payload in [None, Some(vec![]), Some(record(&[])), Some(record(&[0, 0])), Some(vec![0, 0, 0, 1, 0]), Some(u32::MAX.to_be_bytes().to_vec())] { + let mut file = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let layer = &mut file.layer_info.as_mut().unwrap().layers[0]; + layer.name = b"Pascal".to_vec(); + layer.blocks.retain(|b| b.key != *b"luni"); + if let Some(data) = payload { + layer.blocks.push(craft_psd::tagged::TaggedBlock::new(*b"luni", data)); + } + assert_eq!(Psd::parse(file.to_bytes().unwrap()).unwrap().layers[0].name, "Pascal"); + } +} From 1d823a01a1585256a8c4cb2587ffc1622202df7c Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 15:12:01 +0100 Subject: [PATCH 66/78] psd: share fixed-binary adjustment readers --- crates/psd/src/parse.rs | 52 +++++------ crates/psd/src/tests.rs | 1 + crates/psd/src/tests/fixed_adjustments.rs | 101 ++++++++++++++++++++++ 3 files changed, 123 insertions(+), 31 deletions(-) create mode 100644 crates/psd/src/tests/fixed_adjustments.rs diff --git a/crates/psd/src/parse.rs b/crates/psd/src/parse.rs index 633b5ac90..3ba26e9fc 100644 --- a/crates/psd/src/parse.rs +++ b/crates/psd/src/parse.rs @@ -199,11 +199,14 @@ impl Psd { l.fill = d.color("Clr "); } b"nvrt" => l.adjustment = Some(Adjustment::Invert), - b"brit" => { - let brightness = r.i16()? as f64; - let contrast = r.i16()? as f64; - if l.adjustment.is_none() { - l.adjustment = Some(Adjustment::BrightnessContrast { brightness, contrast, legacy: true }); + b"brit" | b"hue2" | b"hue " | b"levl" | b"expA" => { + if let Some(adjustment) = craft_psd::adjust::Adjustment::from_block(key, b) { + let adjustment = adjustment.map_err(|e| error(&e))?; + // Photoshop can write brit beside CgEd: retain Effect's first-only + // brit policy while other complete typed blocks replace prior values. + if key != b"brit" || l.adjustment.is_none() { + l.adjustment = Some(from_shared_adjustment(adjustment)); + } } } b"CgEd" => { @@ -215,32 +218,6 @@ impl Psd { legacy: d.bool("useLegacy").unwrap_or(false), }); } - b"hue2" | b"hue " => { - let _ver = r.u16()?; - let colorize = r.u8()? != 0; - r.skip(1)?; - let ch = (r.i16()? as f64, r.i16()? as f64, r.i16()? as f64); - let m = (r.i16()? as f64, r.i16()? as f64, r.i16()? as f64); - let (hue, saturation, lightness) = if colorize { ch } else { m }; - l.adjustment = Some(Adjustment::HueSaturation { hue, saturation, lightness, colorize }); - } - b"levl" => { - let _ver = r.u16()?; - let (ib, iw, ob, ow, g) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?, r.i16()?); - l.adjustment = - Some(Adjustment::Levels { in_black: ib as f64, in_white: iw as f64, gamma: g as f64 / 100.0, out_black: ob as f64, out_white: ow as f64 }); - } - b"expA" => { - let _ver = r.u16()?; - let mut finite = |default: f64| -> Result { - let v = f64::from(r.f32()?); - Ok(if v.is_finite() { v } else { default }) - }; - let exposure = finite(0.0)?; - let offset = finite(0.0)?; - let gamma = finite(1.0)?; - l.adjustment = Some(Adjustment::Exposure { exposure, offset, gamma }); - } b"curv" | b"blnc" | b"post" | b"thrs" | b"selc" | b"mixr" | b"phfl" | b"vibA" | b"blwh" | b"grdm" | b"clrL" if l.adjustment.is_none() => { l.adjustment = Some(Adjustment::Other(String::from_utf8_lossy(key).into_owned())); } @@ -521,3 +498,16 @@ fn error(e: &craft_psd::PsdError) -> Error { fn mac_roman_string(b: &[u8]) -> String { b.iter().map(|&b| if b < 0x80 { b as char } else { super::read::mac_roman(b) }).collect() } + +/// App representation only; binary field framing belongs to craft-psd. +fn from_shared_adjustment(value: craft_psd::adjust::Adjustment) -> Adjustment { + use craft_psd::adjust::Adjustment as Shared; + match value { + Shared::Invert => Adjustment::Invert, + Shared::BrightnessContrast { brightness, contrast, legacy } => Adjustment::BrightnessContrast { brightness, contrast, legacy }, + Shared::HueSaturation { hue, saturation, lightness, colorize } => Adjustment::HueSaturation { hue, saturation, lightness, colorize }, + Shared::Levels { in_black, in_white, gamma, out_black, out_white } => Adjustment::Levels { in_black, in_white, gamma, out_black, out_white }, + Shared::Exposure { exposure, offset, gamma } => Adjustment::Exposure { exposure, offset, gamma }, + Shared::Other(key) => Adjustment::Other(String::from_utf8_lossy(&key).into_owned()), + } +} diff --git a/crates/psd/src/tests.rs b/crates/psd/src/tests.rs index 7406c0345..c0ee136d5 100644 --- a/crates/psd/src/tests.rs +++ b/crates/psd/src/tests.rs @@ -2,6 +2,7 @@ use super::write::*; use super::*; use crate::pixels::srgb_encode; +mod fixed_adjustments; mod integration; mod opt; mod shared_corpus; diff --git a/crates/psd/src/tests/fixed_adjustments.rs b/crates/psd/src/tests/fixed_adjustments.rs new file mode 100644 index 000000000..223e973d3 --- /dev/null +++ b/crates/psd/src/tests/fixed_adjustments.rs @@ -0,0 +1,101 @@ +use super::*; + +type Block = ([u8; 4], Vec); + +fn i16s(prefix: &[u8], values: &[i16]) -> Vec { + let mut bytes = prefix.to_vec(); + bytes.extend(values.iter().flat_map(|v| v.to_be_bytes())); + bytes +} + +fn exposure(values: [f32; 3]) -> Vec { + let mut bytes = vec![0xff, 0xfe]; // Versions are intentionally not rejected. + bytes.extend(values.iter().flat_map(|v| v.to_be_bytes())); + bytes +} + +fn parse_adjustment(blocks: Vec) -> Option { + let mut doc = WDoc::new(1, 1); + doc.layers = vec![WLayer::empty("adjustment", blocks)]; + Psd::parse(write(&doc)).unwrap().layers.remove(0).adjustment +} + +fn cases() -> Vec<(Block, Adjustment)> { + let mut cases = vec![ + ((*b"brit", i16s(&[], &[i16::MIN, i16::MAX])), Adjustment::BrightnessContrast { brightness: -32768.0, contrast: 32767.0, legacy: true }), + ( + (*b"levl", i16s(&[0xff, 0xfe], &[i16::MIN, i16::MAX, -12, 300, -250])), + Adjustment::Levels { in_black: -32768.0, in_white: 32767.0, gamma: -2.5, out_black: -12.0, out_white: 300.0 }, + ), + ((*b"expA", exposure([-1.5, 2.25, 0.125])), Adjustment::Exposure { exposure: -1.5, offset: 2.25, gamma: 0.125 }), + ]; + for key in [*b"hue2", *b"hue "] { + for flag in [0, 1, 255] { + let values = if flag == 0 { [100.0, -200.0, 300.0] } else { [-32768.0, 32767.0, -4.0] }; + cases.push(( + (key, i16s(&[0xff, 0xfe, flag, 0xa5], &[i16::MIN, i16::MAX, -4, 100, -200, 300])), + Adjustment::HueSaturation { hue: values[0], saturation: values[1], lightness: values[2], colorize: flag != 0 }, + )); + } + } + cases +} + +#[test] +fn fixed_adjustments_preserve_fields_truncation_and_trailing_bytes() { + for ((key, bytes), expected) in cases() { + for end in 0..bytes.len() { + assert_eq!(parse_adjustment(vec![(key, bytes[..end].to_vec())]), None, "{key:?} prefix {end}"); + assert_eq!(parse_adjustment(vec![(*b"nvrt", vec![]), (key, bytes[..end].to_vec())]), Some(Adjustment::Invert)); + } + for tail in [vec![], vec![0xff], vec![0; 20]] { + let mut data = bytes.clone(); + data.extend(tail); + assert_eq!(parse_adjustment(vec![(key, data)]), Some(expected.clone()), "{key:?}"); + } + let after_invert = if key == *b"brit" { Adjustment::Invert } else { expected }; + assert_eq!(parse_adjustment(vec![(*b"nvrt", vec![]), (key, bytes)]), Some(after_invert)); + } +} + +#[test] +fn exposure_nonfinite_values_use_each_fields_original_default() { + for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + for axis in 0..3 { + let mut values = [-1.5, 2.25, 0.125]; + values[axis] = value; + let mut expected = [-1.5, 2.25, 0.125]; + expected[axis] = [0.0, 0.0, 1.0][axis]; + assert_eq!( + parse_adjustment(vec![(*b"expA", exposure(values))]), + Some(Adjustment::Exposure { exposure: expected[0], offset: expected[1], gamma: expected[2] }) + ); + } + } + let Some(Adjustment::Exposure { exposure: e, offset, gamma }) = parse_adjustment(vec![(*b"expA", exposure([-0.0; 3]))]) else { + panic!("exposure missing"); + }; + assert!(e.is_sign_negative() && offset.is_sign_negative() && gamma.is_sign_negative()); +} + +#[test] +fn fixed_adjustments_keep_brit_descriptor_and_other_block_precedence() { + let brit = (*b"brit", i16s(&[], &[10, 20])); + let mut cged = 16u32.to_be_bytes().to_vec(); + crate::descriptor::write_descriptor( + &mut cged, + &Descriptor::new("brightnessContrast").with("Brgh", DValue::Double(30.0)).with("Cntr", DValue::Double(-40.0)).with("useLegacy", DValue::Bool(false)), + ); + let modern = Adjustment::BrightnessContrast { brightness: 30.0, contrast: -40.0, legacy: false }; + for blocks in [vec![brit.clone(), (*b"CgEd", cged.clone())], vec![(*b"CgEd", cged), brit.clone()]] { + assert_eq!(parse_adjustment(blocks), Some(modern.clone())); + } + assert_eq!(parse_adjustment(vec![(*b"curv", vec![]), brit.clone()]), Some(Adjustment::Other("curv".into()))); + assert_eq!( + parse_adjustment(vec![brit.clone(), (*b"curv", vec![]), (*b"brit", i16s(&[], &[50, 60]))]), + Some(Adjustment::BrightnessContrast { brightness: 10.0, contrast: 20.0, legacy: true }) + ); + for ((key, data), expected) in cases().into_iter().filter(|((key, _), _)| key != b"brit") { + assert_eq!(parse_adjustment(vec![(*b"curv", vec![]), brit.clone(), (key, data), (*b"curv", vec![]), brit.clone()]), Some(expected)); + } +} From d0693d9dcb800e4dbc18439759a5b915847fcd11 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 16:39:11 +0100 Subject: [PATCH 67/78] psd: share recovering section-divider framing --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/psd/src/parse.rs | 14 ++++--- crates/psd/src/tests.rs | 1 + crates/psd/src/tests/section_divider.rs | 53 +++++++++++++++++++++++++ 5 files changed, 64 insertions(+), 8 deletions(-) create mode 100644 crates/psd/src/tests/section_divider.rs diff --git a/Cargo.lock b/Cargo.lock index d341691d6..b212dca03 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1463,7 +1463,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e1fc4b1376148197c2cfd2381eeb400e2731269a#e1fc4b1376148197c2cfd2381eeb400e2731269a" +source = "git+https://github.com/storytold/craft-libs?rev=8df7c0268ac112fd285d33688eb6819365391a80#8df7c0268ac112fd285d33688eb6819365391a80" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index b5d7cedc0..05384d547 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e1fc4b1376148197c2cfd2381eeb400e2731269a" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8df7c0268ac112fd285d33688eb6819365391a80" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } diff --git a/crates/psd/src/parse.rs b/crates/psd/src/parse.rs index 3ba26e9fc..473d849c9 100644 --- a/crates/psd/src/parse.rs +++ b/crates/psd/src/parse.rs @@ -158,14 +158,16 @@ impl Psd { b"lyid" => l.id = Some(r.u32()?), b"iOpa" => l.fill_opacity = r.u8()?, b"lsct" | b"lsdk" => { - l.section = match r.u32()? { - 1 => Section::OpenFolder, - 2 => Section::ClosedFolder, - 3 => Section::Divider, + use craft_psd::tagged::{SectionDivider, SectionType}; + let divider = SectionDivider::from_bytes_recovering_blend(b).map_err(|e| error(&e))?; + l.section = match divider.kind { + SectionType::OpenFolder => Section::OpenFolder, + SectionType::ClosedFolder => Section::ClosedFolder, + SectionType::BoundingDivider => Section::Divider, _ => Section::Layer, }; - if b.len() >= 12 && &b[4..8] == b"8BIM" { - l.blend.copy_from_slice(&b[8..12]); + if let Some(blend) = divider.blend_mode { + l.blend = blend.key(); } } b"TySh" => { diff --git a/crates/psd/src/tests.rs b/crates/psd/src/tests.rs index 2935841dd..628a30bff 100644 --- a/crates/psd/src/tests.rs +++ b/crates/psd/src/tests.rs @@ -5,6 +5,7 @@ use crate::pixels::srgb_encode; mod fixed_adjustments; mod integration; mod opt; +mod section_divider; mod shared_corpus; mod unicode_name; diff --git a/crates/psd/src/tests/section_divider.rs b/crates/psd/src/tests/section_divider.rs new file mode 100644 index 000000000..ec208383b --- /dev/null +++ b/crates/psd/src/tests/section_divider.rs @@ -0,0 +1,53 @@ +use super::*; + +fn parse_section_blocks(blocks: Vec<([u8; 4], Vec)>) -> (Section, [u8; 4]) { + let mut doc = WDoc::new(1, 1); + doc.layers = vec![WLayer::empty("Section", blocks).with_blend(b"mul ")]; + let layer = Psd::parse(write(&doc)).unwrap().layers.remove(0); + (layer.section, layer.blend) +} + +#[test] +fn section_prefixes_and_invalid_optional_signatures_preserve_prior_state() { + let full = [0, 0, 0, 2, b'8', b'B', b'I', b'M', b'z', b'z', b'z', b'z', 0, 0, 0, 7, 255]; + for key in [*b"lsct", *b"lsdk"] { + for len in 0..=17 { + let data = full[..len].to_vec(); + assert_eq!( + parse_section_blocks(vec![(key, data.clone())]), + (if len < 4 { Section::Layer } else { Section::ClosedFolder }, if len < 12 { *b"mul " } else { *b"zzzz" }), + "{key:?} length {len}" + ); + let previous = vec![0, 0, 0, 1, b'8', b'B', b'I', b'M', b's', b'c', b'r', b'n']; + let other = if key == *b"lsct" { *b"lsdk" } else { *b"lsct" }; + assert_eq!( + parse_section_blocks(vec![(other, previous), (key, data.clone())]), + (if len < 4 { Section::OpenFolder } else { Section::ClosedFolder }, if len < 12 { *b"scrn" } else { *b"zzzz" }), + ); + if len >= 12 { + let mut bad = data; + bad[4..8].copy_from_slice(b"nope"); + assert_eq!(parse_section_blocks(vec![(key, bad)]), (Section::ClosedFolder, *b"mul ")); + } + } + } +} + +#[test] +fn section_unknown_kinds_and_sequential_keys_keep_blend_until_replaced() { + for kind in [0u32, 1, 2, 3, 99, u32::MAX] { + let expected = match kind { + 1 => Section::OpenFolder, + 2 => Section::ClosedFolder, + 3 => Section::Divider, + _ => Section::Layer, + }; + for keys in [[*b"lsct", *b"lsdk"], [*b"lsdk", *b"lsct"]] { + let previous = vec![0, 0, 0, 1, b'8', b'B', b'I', b'M', b'z', b'z', b'z', b'z']; + let mut bad = kind.to_be_bytes().to_vec(); + bad.extend_from_slice(b"nopepass"); + bad.extend_from_slice(&7u32.to_be_bytes()); + assert_eq!(parse_section_blocks(vec![(keys[0], previous), (keys[1], bad)]), (expected, *b"zzzz")); + } + } +} From a6c46ec7c5d9b9b7f688804049fe890bc8d617fa Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 10:41:47 -0500 Subject: [PATCH 68/78] Drop the now-unused WAV probe re-export --- crates/media/src/wav_markers.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/media/src/wav_markers.rs b/crates/media/src/wav_markers.rs index 2f8ee8c48..bc198d1b7 100644 --- a/crates/media/src/wav_markers.rs +++ b/crates/media/src/wav_markers.rs @@ -5,7 +5,7 @@ use effectcraft_project::Marker; use effectcraft_time::Tick; use std::collections::HashSet; -pub use shared::{MAX_MARKERS, is_wav}; +pub use shared::MAX_MARKERS; #[cfg(test)] const MAX_ADTL_RECORDS: usize = 4 * MAX_MARKERS; From a2e2d68107329e005fb9c4d70f0f5bff8236eed2 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 17:40:26 +0100 Subject: [PATCH 69/78] fix(psd): pin vector revision with repaired Windows validation --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 10b750e60..23938a75a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1449,7 +1449,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4d2784ec90413e53b8f6c1a1c6b8526b8077e8c5#4d2784ec90413e53b8f6c1a1c6b8526b8077e8c5" +source = "git+https://github.com/storytold/craft-libs?rev=8ea89705a5e345001833d259c7c719f2cc08dcec#8ea89705a5e345001833d259c7c719f2cc08dcec" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index ca4970bc2..edb23ee02 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "4d2784ec90413e53b8f6c1a1c6b8526b8077e8c5" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8ea89705a5e345001833d259c7c719f2cc08dcec" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } From e436d421cd9f7c5f25a2f8b0cc420cb1d738838b Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 17:42:52 +0100 Subject: [PATCH 70/78] psd: pin section reader with hosted validation repair --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b212dca03..e10293d96 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1463,7 +1463,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8df7c0268ac112fd285d33688eb6819365391a80#8df7c0268ac112fd285d33688eb6819365391a80" +source = "git+https://github.com/storytold/craft-libs?rev=d04bd2c4fbf49e399c7e0cd7a16feebebadd739c#d04bd2c4fbf49e399c7e0cd7a16feebebadd739c" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 05384d547..c007d1628 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8df7c0268ac112fd285d33688eb6819365391a80" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d04bd2c4fbf49e399c7e0cd7a16feebebadd739c" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } From e97a6390acc2d7b763130f7b47abe1f01d322c3d Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 17:42:55 +0100 Subject: [PATCH 71/78] psd: share bounded type-layer text prefix --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/psd/src/descriptor.rs | 4 +- crates/psd/src/parse.rs | 11 +-- crates/psd/src/tests.rs | 1 + crates/psd/src/tests/tysh_prefix.rs | 115 ++++++++++++++++++++++++++++ 6 files changed, 123 insertions(+), 12 deletions(-) create mode 100644 crates/psd/src/tests/tysh_prefix.rs diff --git a/Cargo.lock b/Cargo.lock index d341691d6..1d6ab3fcb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1463,7 +1463,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e1fc4b1376148197c2cfd2381eeb400e2731269a#e1fc4b1376148197c2cfd2381eeb400e2731269a" +source = "git+https://github.com/storytold/craft-libs?rev=9af6a8e4a1ee698e6a7c8af938cf92de82319e07#9af6a8e4a1ee698e6a7c8af938cf92de82319e07" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index b5d7cedc0..2822dec9f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e1fc4b1376148197c2cfd2381eeb400e2731269a" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9af6a8e4a1ee698e6a7c8af938cf92de82319e07" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } diff --git a/crates/psd/src/descriptor.rs b/crates/psd/src/descriptor.rs index 37e7cb94b..63efce100 100644 --- a/crates/psd/src/descriptor.rs +++ b/crates/psd/src/descriptor.rs @@ -127,7 +127,7 @@ pub fn read_descriptor(r: &mut Reader) -> Result { Ok(from_craft_descriptor(d)) } -fn desc_err(e: craft_psd::PsdError) -> Error { +pub(crate) fn desc_err(e: craft_psd::PsdError) -> Error { match e { craft_psd::PsdError::UnexpectedEof { .. } => Error::Truncated, craft_psd::PsdError::Unsupported(s) => Error::Unsupported(s), @@ -143,7 +143,7 @@ fn unit_str(u: &[u8; 4]) -> String { String::from_utf8_lossy(u).into_owned() } -fn from_craft_descriptor(d: craft_psd::descriptor::Descriptor) -> Descriptor { +pub(crate) fn from_craft_descriptor(d: craft_psd::descriptor::Descriptor) -> Descriptor { Descriptor { class_name: d.name.to_string_lossy(), class_id: id_str(&d.class_id), diff --git a/crates/psd/src/parse.rs b/crates/psd/src/parse.rs index 3ba26e9fc..552307708 100644 --- a/crates/psd/src/parse.rs +++ b/crates/psd/src/parse.rs @@ -169,18 +169,13 @@ impl Psd { } } b"TySh" => { - let _ver = r.u16()?; - let mut t = [0.0; 6]; - for v in &mut t { - *v = r.f64()?; - } + let prefix = craft_psd::text::TypeLayerPrefix::from_bytes_with_limits(b, descriptor::PARSE_LIMITS).map_err(descriptor::desc_err)?; + let mut t = prefix.transform; // A transform with NaN/inf is unusable: fall back to the identity. if t.iter().any(|v| !v.is_finite()) { t = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; } - let _text_ver = r.u16()?; - let _desc_ver = r.u32()?; - let d = descriptor::read_descriptor(&mut r)?; + let d = descriptor::from_craft_descriptor(prefix.descriptor); let text = d.text("Txt ").unwrap_or_default().replace("\r\n", "\n").replace('\r', "\n"); let text = text.strip_suffix('\n').map(str::to_string).unwrap_or(text); let style = d.raw("EngineData").map(|e| engine_data::text_style(&engine_data::parse_lossy(e))).unwrap_or_default(); diff --git a/crates/psd/src/tests.rs b/crates/psd/src/tests.rs index 2935841dd..e45a1636e 100644 --- a/crates/psd/src/tests.rs +++ b/crates/psd/src/tests.rs @@ -6,6 +6,7 @@ mod fixed_adjustments; mod integration; mod opt; mod shared_corpus; +mod tysh_prefix; mod unicode_name; fn gradient(w: u32, h: u32) -> Vec<[f32; 4]> { diff --git a/crates/psd/src/tests/tysh_prefix.rs b/crates/psd/src/tests/tysh_prefix.rs new file mode 100644 index 000000000..027a21cbb --- /dev/null +++ b/crates/psd/src/tests/tysh_prefix.rs @@ -0,0 +1,115 @@ +use super::*; +use craft_psd::descriptor::{Class, Descriptor as SharedDescriptor, Id, ReferenceItem, UnicodeString, Value}; + +fn block(transform: [f64; 6], descriptor: SharedDescriptor) -> Vec { + let mut b = 999u16.to_be_bytes().to_vec(); + b.extend(transform.into_iter().flat_map(f64::to_be_bytes)); + b.extend(999u16.to_be_bytes()); + b.extend(999u32.to_be_bytes()); + b.extend(descriptor.to_bytes()); + b +} + +fn text_descriptor(text: &str) -> SharedDescriptor { + SharedDescriptor::new("TxLr").with("Txt ", Value::Text(UnicodeString::new(text))) +} + +fn parse_text(blocks: Vec>) -> Option { + let mut doc = WDoc::new(1, 1); + doc.layers = vec![WLayer::empty("Text", blocks.into_iter().map(|b| (*b"TySh", b)).collect())]; + Psd::parse(write(&doc)).unwrap().layers.remove(0).text +} + +#[test] +fn text_prefix_recovers_suffixes_and_repeated_blocks_without_changing_text_policy() { + let transform = [2.0, 0.0, 0.0, 3.0, 4.0, 5.0]; + let data = block(transform, text_descriptor("a\r\nb\rc\n\n")); + let expected = TextInfo { text: "a\nb\nc\n".into(), transform, ..Default::default() }; + for suffix in [vec![], vec![255], vec![0; 6], vec![255; 40]] { + let mut b = data.clone(); + b.extend(suffix); + assert_eq!(parse_text(vec![b]), Some(expected.clone())); + } + for cut in 0..data.len() { + assert_eq!(parse_text(vec![data[..cut].to_vec()]), None, "cut {cut}"); + assert_eq!(parse_text(vec![data.clone(), data[..cut].to_vec()]), Some(expected.clone())); + } + let last = block(transform, text_descriptor("last")); + assert_eq!(parse_text(vec![data, last]).unwrap().text, "last"); + for index in 0..6 { + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let mut t = transform; + t[index] = bad; + assert_eq!(parse_text(vec![block(t, text_descriptor("x"))]).unwrap().transform, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + } + } +} + +#[test] +fn text_prefix_preserves_descriptor_normalization_and_bounds_precedence() { + let bounds = SharedDescriptor::new("bounds") + .with("Left", Value::Double(f64::NAN)) + .with("Top ", Value::UnitFloat { unit: *b"#Pnt", value: f64::INFINITY }) + .with("Rght", Value::Double(20.0)) + .with("Btom", Value::Double(10.0)); + let d = text_descriptor("x").with("bounds", Value::Descriptor(bounds.clone())); + assert_eq!(parse_text(vec![block([1.0; 6], d)]).unwrap().bounds, Some([0.0, 0.0, 20.0, 10.0])); + let d = text_descriptor("x") + .with("bounds", Value::Descriptor(SharedDescriptor::new("bounds").with("Left", Value::Double(1.0)))) + .with("boundingBox", Value::Descriptor(bounds.clone())); + assert_eq!(parse_text(vec![block([1.0; 6], d)]).unwrap().bounds, None); + let d = text_descriptor("x").with("boundingBox", Value::Descriptor(bounds)); + assert_eq!(parse_text(vec![block([1.0; 6], d)]).unwrap().bounds, Some([0.0, 0.0, 20.0, 10.0])); + + let class = Class { name: UnicodeString::new("named"), class_id: Id::Str(b"abcd".to_vec()) }; + let d = text_descriptor("x") + .with("ref ", Value::Reference(vec![ReferenceItem::Identifier { class: class.clone(), id: 7 }])) + .with("cls ", Value::Class(class.clone())) + .with("nums", Value::UnitFloats { unit: *b"#Pxl", values: vec![f64::NEG_INFINITY, 2.0] }); + let raw = craft_psd::text::TypeLayerPrefix::from_bytes_with_limits(&block([1.0; 6], d), descriptor::PARSE_LIMITS).unwrap(); + let converted = descriptor::from_craft_descriptor(raw.descriptor); + assert_eq!(converted.class_id, "TxLr"); + assert_eq!(converted.items[1].1, descriptor::DValue::Reference(vec![descriptor::RefItem::IdentifierWithClass(class, 7)])); + assert_eq!(converted.items[2].1, descriptor::DValue::Class("named".into(), "abcd".into())); + assert_eq!(converted.items[3].1, descriptor::DValue::UnitFloats("#Pxl".into(), vec![0.0, 2.0])); +} + +#[test] +fn text_prefix_enforces_effect_descriptor_count_limit_before_reading_items() { + let mut data = block([1.0; 6], SharedDescriptor::new("TxLr")); + let end = data.len(); + data[end - 4..].copy_from_slice(&100_001u32.to_be_bytes()); + let err = craft_psd::text::TypeLayerPrefix::from_bytes_with_limits(&data, descriptor::PARSE_LIMITS).unwrap_err(); + assert!(matches!(descriptor::desc_err(err), Error::Invalid(_) | Error::Unsupported(_))); + assert_eq!(parse_text(vec![data]), None); +} + +#[test] +fn text_prefix_reads_independent_raw_header_and_text_descriptor() { + let mut data = vec![0, 9]; + for value in [1.0f64, 0.0, 0.0, 1.0, 12.0, -3.0] { + data.extend(value.to_be_bytes()); + } + // Ignored text/descriptor versions; empty class name, code class, one text item. + data.extend([0, 8, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0]); + data.extend(b"TxLr"); + data.extend(1u32.to_be_bytes()); + data.extend(0u32.to_be_bytes()); + data.extend(b"Txt TEXT"); + data.extend(4u32.to_be_bytes()); + data.extend([0, 65, 0, 13, 0, 10, 0, 66]); + let t = parse_text(vec![data]).unwrap(); + assert_eq!(t.text, "A\nB"); + assert_eq!(t.transform, [1.0, 0.0, 0.0, 1.0, 12.0, -3.0]); +} + +#[test] +fn text_prefix_keeps_first_engine_style() { + let engine = craft_psd::engine_data::minimal("x", "Courier", 24.0, [0.2, 0.4, 0.6], 1); + let d = text_descriptor("x").with("EngineData", Value::RawData(engine)); + let style = parse_text(vec![block([1.0; 6], d)]).unwrap().style; + assert_eq!(style.font.as_deref(), Some("Courier")); + assert_eq!(style.size, Some(24.0)); + assert_eq!(style.color, Some([0.2, 0.4, 0.6])); + assert_eq!(style.justification, Some(1)); +} From 57ae4ceeff6dbc10859607c084acfa7f6e9bb6f8 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 19:31:24 +0100 Subject: [PATCH 72/78] psd: read scalar layer blocks through shared views --- crates/psd/src/parse.rs | 18 +++++++++--- crates/psd/src/tests.rs | 1 + crates/psd/src/tests/scalar_blocks.rs | 40 +++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 4 deletions(-) create mode 100644 crates/psd/src/tests/scalar_blocks.rs diff --git a/crates/psd/src/parse.rs b/crates/psd/src/parse.rs index 3ba26e9fc..ce86a71ac 100644 --- a/crates/psd/src/parse.rs +++ b/crates/psd/src/parse.rs @@ -114,7 +114,7 @@ impl Psd { // A malformed optional block only loses that block's information. // Unsupported modern placement geometry must not silently become an // unwarped layer or fall back to a less expressive PlLd in either order. - match self.layer_block(&mut l, &b.key, &b.data) { + match self.layer_block(&mut l, b) { Err(e @ Error::Unsupported(_)) if matches!(&b.key, b"SoLd" | b"SoLE") => return Err(e), _ => {} } @@ -140,7 +140,9 @@ impl Psd { } } - fn layer_block(&self, l: &mut Layer, key: &[u8; 4], b: &[u8]) -> Result<()> { + fn layer_block(&self, l: &mut Layer, block: &craft_psd::tagged::TaggedBlock) -> Result<()> { + let key = &block.key; + let b = block.data.as_slice(); let mut r = Reader::new(b); match key { b"luni" => { @@ -155,8 +157,16 @@ impl Psd { l.name = name; } } - b"lyid" => l.id = Some(r.u32()?), - b"iOpa" => l.fill_opacity = r.u8()?, + b"lyid" | b"iOpa" => { + use craft_psd::tagged::BlockData; + // Borrow the original block; short fields keep the previous value, + // while complete prefixes retain the shared parser's trailing-byte policy. + match block.parsed().transpose().map_err(|e| error(&e))? { + Some(BlockData::LayerId(id)) => l.id = Some(id), + Some(BlockData::FillOpacity(opacity)) => l.fill_opacity = opacity, + _ => {} + } + } b"lsct" | b"lsdk" => { l.section = match r.u32()? { 1 => Section::OpenFolder, diff --git a/crates/psd/src/tests.rs b/crates/psd/src/tests.rs index 2935841dd..db65196fa 100644 --- a/crates/psd/src/tests.rs +++ b/crates/psd/src/tests.rs @@ -5,6 +5,7 @@ use crate::pixels::srgb_encode; mod fixed_adjustments; mod integration; mod opt; +mod scalar_blocks; mod shared_corpus; mod unicode_name; diff --git a/crates/psd/src/tests/scalar_blocks.rs b/crates/psd/src/tests/scalar_blocks.rs new file mode 100644 index 000000000..d8dff9a1a --- /dev/null +++ b/crates/psd/src/tests/scalar_blocks.rs @@ -0,0 +1,40 @@ +use super::*; + +fn scalars(blocks: Vec<([u8; 4], Vec)>) -> (Option, u8, u8) { + let mut doc = WDoc::new(1, 1); + doc.layers = vec![WLayer::empty("Scalars", blocks).with_opacity(37)]; + let layer = Psd::parse(write(&doc)).unwrap().layers.remove(0); + (layer.id, layer.fill_opacity, layer.opacity) +} + +#[test] +fn scalar_prefixes_keep_defaults_and_ignore_trailing_bytes() { + assert_eq!(scalars(vec![]), (None, 255, 37)); + let bytes = [0x89, 0xab, 0xcd, 0xef, 255, 0, 23]; + for end in 0..=bytes.len() { + assert_eq!(scalars(vec![(*b"lyid", bytes[..end].to_vec())]), (if end < 4 { None } else { Some(0x89ab_cdef) }, 255, 37), "lyid prefix {end}"); + assert_eq!(scalars(vec![(*b"iOpa", bytes[..end].to_vec())]), (None, if end == 0 { 255 } else { 0x89 }, 37), "iOpa prefix {end}"); + } + for id in [0u32, 1, 0x8000_0000, u32::MAX] { + for opacity in [0, 1, 254, 255] { + assert_eq!(scalars(vec![(*b"lyid", id.to_be_bytes().to_vec()), (*b"iOpa", vec![opacity])]), (Some(id), opacity, 37)); + } + } +} + +#[test] +fn repeated_scalar_blocks_preserve_prior_values_on_short_fields_in_both_orders() { + for reverse in [false, true] { + for short in 0..4 { + let mut initial = vec![(*b"lyid", vec![0, 0, 0, 42]), (*b"iOpa", vec![99])]; + if reverse { + initial.reverse(); + } + let mut blocks = initial.clone(); + blocks.extend([(*b"lyid", vec![255; short]), (*b"iOpa", vec![]), (*b"zzzz", vec![0; 4])]); + assert_eq!(scalars(blocks.clone()), (Some(42), 99, 37)); + blocks.extend([(*b"iOpa", vec![0, 77]), (*b"lyid", vec![0, 0, 0, 7, 255])]); + assert_eq!(scalars(blocks), (Some(7), 0, 37)); + } + } +} From f3ba7a5cd25c6b525fd6c6494ba1ae611fb4d7a0 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 20:38:43 +0100 Subject: [PATCH 73/78] psd: share recovering descriptor-block headers --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/psd/src/parse.rs | 39 +++++---- crates/psd/src/tests.rs | 1 + crates/psd/src/tests/tagged_descriptors.rs | 92 ++++++++++++++++++++++ 5 files changed, 114 insertions(+), 22 deletions(-) create mode 100644 crates/psd/src/tests/tagged_descriptors.rs diff --git a/Cargo.lock b/Cargo.lock index 92dc7b239..8a080e7d1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1463,7 +1463,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=62f7a7e4777d9b60f55a18a8865c73bb12297f38#62f7a7e4777d9b60f55a18a8865c73bb12297f38" +source = "git+https://github.com/storytold/craft-libs?rev=c62d548b6b806beac8c1f93f2f23f4f2f3cf1c13#c62d548b6b806beac8c1f93f2f23f4f2f3cf1c13" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 81d390d38..ed1e08e34 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "62f7a7e4777d9b60f55a18a8865c73bb12297f38" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c62d548b6b806beac8c1f93f2f23f4f2f3cf1c13" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } diff --git a/crates/psd/src/parse.rs b/crates/psd/src/parse.rs index 6d1e64b55..93bbc60b8 100644 --- a/crates/psd/src/parse.rs +++ b/crates/psd/src/parse.rs @@ -114,7 +114,7 @@ impl Psd { // A malformed optional block only loses that block's information. // Unsupported modern placement geometry must not silently become an // unwarped layer or fall back to a less expressive PlLd in either order. - match self.layer_block(&mut l, &b.key, &b.data) { + match self.layer_block(&mut l, b) { Err(e @ Error::Unsupported(_)) if matches!(&b.key, b"SoLd" | b"SoLE") => return Err(e), _ => {} } @@ -140,7 +140,9 @@ impl Psd { } } - fn layer_block(&self, l: &mut Layer, key: &[u8; 4], b: &[u8]) -> Result<()> { + fn layer_block(&self, l: &mut Layer, block: &craft_psd::tagged::TaggedBlock) -> Result<()> { + let key = &block.key; + let b = block.data.as_slice(); let mut r = Reader::new(b); match key { b"luni" => { @@ -185,15 +187,21 @@ impl Psd { d.obj("bounds").or_else(|| d.obj("boundingBox")).and_then(|o| Some([o.num("Left")?, o.num("Top ")?, o.num("Rght")?, o.num("Btom")?])); l.text = Some(TextInfo { text, transform: t, style, bounds }); } - b"lfx2" => { - let _ver = r.u32()?; - let _dver = r.u32()?; - l.effects = Some(descriptor::read_descriptor(&mut r)?); - } - b"SoCo" => { - let _ver = r.u32()?; - let d = descriptor::read_descriptor(&mut r)?; - l.fill = d.color("Clr "); + b"lfx2" | b"SoCo" | b"CgEd" => { + if let Some(parsed) = block.descriptor_prefix_recovering_versions_with_limits(descriptor::PARSE_LIMITS) { + let d = descriptor::from_craft_descriptor(parsed.map_err(descriptor::desc_err)?); + match key { + b"lfx2" => l.effects = Some(d), + b"SoCo" => l.fill = d.color("Clr "), + _ => { + l.adjustment = Some(Adjustment::BrightnessContrast { + brightness: d.num("Brgh").unwrap_or(0.0), + contrast: d.num("Cntr").unwrap_or(0.0), + legacy: d.bool("useLegacy").unwrap_or(false), + }); + } + } + } } b"nvrt" => l.adjustment = Some(Adjustment::Invert), b"brit" | b"hue2" | b"hue " | b"levl" | b"expA" => { @@ -206,15 +214,6 @@ impl Psd { } } } - b"CgEd" => { - let _ver = r.u32()?; - let d = descriptor::read_descriptor(&mut r)?; - l.adjustment = Some(Adjustment::BrightnessContrast { - brightness: d.num("Brgh").unwrap_or(0.0), - contrast: d.num("Cntr").unwrap_or(0.0), - legacy: d.bool("useLegacy").unwrap_or(false), - }); - } b"curv" | b"blnc" | b"post" | b"thrs" | b"selc" | b"mixr" | b"phfl" | b"vibA" | b"blwh" | b"grdm" | b"clrL" if l.adjustment.is_none() => { l.adjustment = Some(Adjustment::Other(String::from_utf8_lossy(key).into_owned())); } diff --git a/crates/psd/src/tests.rs b/crates/psd/src/tests.rs index 915b48ed2..6d6258029 100644 --- a/crates/psd/src/tests.rs +++ b/crates/psd/src/tests.rs @@ -7,6 +7,7 @@ mod integration; mod opt; mod section_divider; mod shared_corpus; +mod tagged_descriptors; mod tysh_prefix; mod unicode_name; mod vector_records; diff --git a/crates/psd/src/tests/tagged_descriptors.rs b/crates/psd/src/tests/tagged_descriptors.rs new file mode 100644 index 000000000..28e0e3fc6 --- /dev/null +++ b/crates/psd/src/tests/tagged_descriptors.rs @@ -0,0 +1,92 @@ +use super::*; +use craft_psd::descriptor::{Descriptor as Shared, UnicodeString, Value}; + +fn bytes(key: [u8; 4], d: Shared, version: u32) -> Vec { + let mut b = version.to_be_bytes().repeat(if key == *b"lfx2" { 2 } else { 1 }); + b.extend(d.to_bytes()); + b +} + +fn state(blocks: Vec<([u8; 4], Vec)>) -> (Option, Option<[f64; 3]>, Option) { + let mut doc = WDoc::new(1, 1); + doc.layers = vec![WLayer::empty("Descriptor", blocks)]; + let layer = Psd::parse(write(&doc)).unwrap().layers.remove(0); + (layer.effects, layer.fill, layer.adjustment) +} + +fn value(key: [u8; 4]) -> Shared { + match &key { + b"lfx2" => Shared::new("null").with("name", Value::Text(UnicodeString::new("effect"))), + b"SoCo" => Shared::new("null").with( + "Clr ", + Value::Descriptor(Shared::new("RGBC").with("Rd ", Value::Double(255.0)).with("Grn ", Value::Double(127.5)).with("Bl ", Value::Double(0.0))), + ), + _ => Shared::new("null").with("Brgh", Value::Double(12.0)).with("Cntr", Value::Double(-4.0)).with("useLegacy", Value::Boolean(true)), + } +} + +#[test] +fn tagged_descriptor_headers_ignore_versions_and_tails_and_preserve_short_block_state() { + for key in [*b"lfx2", *b"SoCo", *b"CgEd"] { + let good = bytes(key, value(key), 16); + let expected = state(vec![(key, good.clone())]); + match &key { + b"lfx2" => assert_eq!(expected.0.as_ref().unwrap().text("name"), Some("effect")), + b"SoCo" => assert_eq!(expected.1, Some([1.0, 0.5, 0.0])), + _ => assert_eq!(expected.2, Some(Adjustment::BrightnessContrast { brightness: 12.0, contrast: -4.0, legacy: true })), + } + for cut in 0..good.len() { + assert_eq!(state(vec![(key, good[..cut].to_vec())]), (None, None, None), "{key:?} cut {cut}"); + assert_eq!(state(vec![(key, good.clone()), (key, good[..cut].to_vec())]), expected); + } + for version in [0, 99, u32::MAX] { + for tail in [vec![], vec![255], vec![1, 2, 3, 4, 5]] { + let mut b = bytes(key, value(key), version); + b.extend(tail); + assert_eq!(state(vec![(key, b)]), expected); + } + } + let empty = bytes(key, Shared::new("null"), 0); + let replaced = state(vec![(key, good), (key, empty)]); + match &key { + b"lfx2" => assert!(replaced.0.unwrap().items.is_empty()), + b"SoCo" => assert_eq!(replaced.1, None), + _ => assert_eq!(replaced.2, Some(Adjustment::BrightnessContrast { brightness: 0.0, contrast: 0.0, legacy: false })), + } + } +} + +#[test] +fn tagged_descriptors_keep_normalization_and_adjustment_precedence() { + let d = Shared::new("null").with("Brgh", Value::Double(f64::NAN)).with("Cntr", Value::UnitFloat { unit: *b"#Prc", value: f64::INFINITY }); + let cged = bytes(*b"CgEd", d, 99); + let expected = Some(Adjustment::BrightnessContrast { brightness: 0.0, contrast: 0.0, legacy: false }); + assert_eq!(state(vec![(*b"nvrt", vec![]), (*b"CgEd", cged.clone())]).2, expected); + assert_eq!(state(vec![(*b"CgEd", cged.clone()), (*b"brit", vec![0, 42, 0, 7])]).2, expected); + assert_eq!(state(vec![(*b"CgEd", cged), (*b"nvrt", vec![])]).2, Some(Adjustment::Invert)); + let color = Shared::new("RGBC").with("Rd ", Value::Double(f64::NEG_INFINITY)).with("Grn ", Value::Double(255.0)).with("Bl ", Value::Double(0.0)); + assert_eq!(state(vec![(*b"SoCo", bytes(*b"SoCo", Shared::new("null").with("Clr ", Value::Descriptor(color)), 0))]).1, Some([0.0, 1.0, 0.0])); +} + +#[test] +fn tagged_descriptor_raw_fixture_and_limits_do_not_depend_on_shared_writer() { + for key in [*b"lfx2", *b"SoCo", *b"CgEd"] { + let mut raw = vec![255; if key == *b"lfx2" { 8 } else { 4 }]; + raw.extend([0; 8]); + raw.extend(b"null"); + raw.extend(0u32.to_be_bytes()); + let result = state(vec![(key, raw.clone())]); + if key == *b"lfx2" { + assert!(result.0.is_some()); + } + if key == *b"CgEd" { + assert!(result.2.is_some()); + } + let end = raw.len(); + raw[end - 4..].copy_from_slice(&100_001u32.to_be_bytes()); + let block = craft_psd::tagged::TaggedBlock::new(key, raw.clone()); + assert!(matches!(block.descriptor_prefix_recovering_versions_with_limits(descriptor::PARSE_LIMITS), Some(Err(craft_psd::PsdError::LimitExceeded(_))))); + let good = bytes(key, value(key), 16); + assert_eq!(state(vec![(key, good.clone()), (key, raw)]), state(vec![(key, good)])); + } +} From a089c3f312beb6a3ebb1694f15ce66a162c7295c Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 21:23:52 +0100 Subject: [PATCH 74/78] Delegate raw adjustment writers to craft-psd --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/psd/src/tests.rs | 1 + crates/psd/src/tests/fixed_writers.rs | 26 ++++++++++++++++++++++++++ crates/psd/src/write.rs | 16 ++++------------ 5 files changed, 33 insertions(+), 14 deletions(-) create mode 100644 crates/psd/src/tests/fixed_writers.rs diff --git a/Cargo.lock b/Cargo.lock index 92dc7b239..431e35b39 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1463,7 +1463,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=62f7a7e4777d9b60f55a18a8865c73bb12297f38#62f7a7e4777d9b60f55a18a8865c73bb12297f38" +source = "git+https://github.com/storytold/craft-libs?rev=5c0abaaa4418ccffbf6717c983c1dec9fa8a7741#5c0abaaa4418ccffbf6717c983c1dec9fa8a7741" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 81d390d38..4f4ef770d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "62f7a7e4777d9b60f55a18a8865c73bb12297f38" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5c0abaaa4418ccffbf6717c983c1dec9fa8a7741" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } diff --git a/crates/psd/src/tests.rs b/crates/psd/src/tests.rs index 915b48ed2..0a7d23ce1 100644 --- a/crates/psd/src/tests.rs +++ b/crates/psd/src/tests.rs @@ -3,6 +3,7 @@ use super::*; use crate::pixels::srgb_encode; mod fixed_adjustments; +mod fixed_writers; mod integration; mod opt; mod section_divider; diff --git a/crates/psd/src/tests/fixed_writers.rs b/crates/psd/src/tests/fixed_writers.rs new file mode 100644 index 000000000..129b501d8 --- /dev/null +++ b/crates/psd/src/tests/fixed_writers.rs @@ -0,0 +1,26 @@ +use super::*; + +#[test] +fn fixed_adjustment_writers_keep_exact_bytes_through_full_psd() { + let cases = [ + (brightness_block(i16::MIN, i16::MAX), *b"brit", vec![0x80, 0, 0x7f, 0xff, 0, 0x7f, 0]), + (brightness_block(-1, 0), *b"brit", vec![0xff, 0xff, 0, 0, 0, 0x7f, 0]), + (exposure_block(0.0, -0.0, f32::INFINITY), *b"expA", vec![0, 1, 0, 0, 0, 0, 0x80, 0, 0, 0, 0x7f, 0x80, 0, 0]), + ( + exposure_block(f32::NEG_INFINITY, f32::from_bits(0x7fc1_2345), f32::from_bits(0xffc5_4321)), + *b"expA", + vec![0, 1, 0xff, 0x80, 0, 0, 0x7f, 0xc1, 0x23, 0x45, 0xff, 0xc5, 0x43, 0x21], + ), + (exposure_block(1.0, -2.5, 0.125), *b"expA", vec![0, 1, 0x3f, 0x80, 0, 0, 0xc0, 0x20, 0, 0, 0x3e, 0, 0, 0]), + ]; + for (block, key, expected) in cases { + assert_eq!(block.0, key); + assert_eq!(block.1, expected); + let mut doc = WDoc::new(1, 1); + doc.layers = vec![WLayer::empty("raw adjustment", vec![block])]; + let bytes = write(&doc); + let file = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let emitted = file.layer_info.as_ref().unwrap().layers[0].block(&key).unwrap(); + assert_eq!(emitted.data, expected); + } +} diff --git a/crates/psd/src/write.rs b/crates/psd/src/write.rs index e5ec285b8..b8067fc92 100644 --- a/crates/psd/src/write.rs +++ b/crates/psd/src/write.rs @@ -465,21 +465,13 @@ pub fn invert_block() -> ([u8; 4], Vec) { } pub fn brightness_block(brightness: i16, contrast: i16) -> ([u8; 4], Vec) { - let mut d = vec![]; - for v in [brightness, contrast, 127] { - d.extend_from_slice(&v.to_be_bytes()); - } - d.push(0); - (*b"brit", d) + let block = craft_psd::adjust::brightness_contrast_block(brightness, contrast); + (block.key, block.data) } pub fn exposure_block(exposure: f32, offset: f32, gamma: f32) -> ([u8; 4], Vec) { - let mut d = vec![]; - put_u16(&mut d, 1); - for v in [exposure, offset, gamma] { - d.extend_from_slice(&v.to_be_bytes()); - } - (*b"expA", d) + let block = craft_psd::adjust::exposure_block(exposure, offset, gamma); + (block.key, block.data) } /// `vmsk`: a vector mask from closed polygons/curves given as (in, anchor, out) knots in pixels. From 4139f5db597ba895148888dc90f1d69a3754d56d Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 23:39:26 +0100 Subject: [PATCH 75/78] Remove unused PSD reader after shared parser integration --- crates/psd/src/parse.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/psd/src/parse.rs b/crates/psd/src/parse.rs index 28cd033e8..2f1ccd2b3 100644 --- a/crates/psd/src/parse.rs +++ b/crates/psd/src/parse.rs @@ -1,6 +1,6 @@ use super::limits::{Error, Result}; use super::model::{Adjustment, ChannelInfo, ColorMode, Layer, LayerMask, LinkedFile, MAX_GROUP_DEPTH, Node, Rect, Section, SubPath, TextInfo, VectorMask}; -use super::{Psd, Reader, descriptor, engine_data, placed}; +use super::{Psd, descriptor, engine_data, placed}; use std::sync::Arc; /// Whether `bytes` start like a Photoshop document. @@ -143,7 +143,6 @@ impl Psd { fn layer_block(&self, l: &mut Layer, block: &craft_psd::tagged::TaggedBlock) -> Result<()> { let key = &block.key; let b = block.data.as_slice(); - let mut r = Reader::new(b); match key { b"luni" => { // Shared framing rejects truncated counts/payloads before allocation. Only From 27ce4e9fa2edc6835f386cf65d8938d4440082fc Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 01:02:42 +0100 Subject: [PATCH 76/78] psd: share hue and levels writer framing --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/psd/src/tests/fixed_writers.rs | 44 +++++++++++++++++++++++++++ crates/psd/src/write.rs | 24 +++------------ 4 files changed, 50 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f1481e105..c8bb8f50f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1463,7 +1463,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=027416ac9f36b60229c595f942d36bf74f0ed4d2#027416ac9f36b60229c595f942d36bf74f0ed4d2" +source = "git+https://github.com/storytold/craft-libs?rev=fa4741d0bbba8da303dd1bb1a93cbcb78e7747a0#fa4741d0bbba8da303dd1bb1a93cbcb78e7747a0" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 148d344e6..832eeef8c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs" craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "027416ac9f36b60229c595f942d36bf74f0ed4d2" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "fa4741d0bbba8da303dd1bb1a93cbcb78e7747a0" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } diff --git a/crates/psd/src/tests/fixed_writers.rs b/crates/psd/src/tests/fixed_writers.rs index 129b501d8..4aac3c9c2 100644 --- a/crates/psd/src/tests/fixed_writers.rs +++ b/crates/psd/src/tests/fixed_writers.rs @@ -24,3 +24,47 @@ fn fixed_adjustment_writers_keep_exact_bytes_through_full_psd() { assert_eq!(emitted.data, expected); } } + +fn assert_written_payload(block: ([u8; 4], Vec), key: [u8; 4], expected: Vec) { + assert_eq!(block.0, key); + assert_eq!(block.1, expected); + let mut doc = WDoc::new(1, 1); + doc.layers = vec![WLayer::empty("raw adjustment", vec![block])]; + let bytes = write(&doc); + let file = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); + assert_eq!(file.layer_info.as_ref().unwrap().layers[0].block(&key).unwrap().data, expected); +} + +#[test] +fn hue_writer_keeps_all_six_unused_ranges_and_signed_master_values() { + let mut expected = vec![0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0x80, 0, 0x7f, 0xff, 0xff, 0xff]; + expected.extend([0; 144]); + assert_written_payload(hue_sat_block(i16::MIN, i16::MAX, -1), *b"hue2", expected); + let mut expected = vec![0; 160]; + expected[1] = 2; + assert_written_payload(hue_sat_block(0, 0, 0), *b"hue2", expected); +} + +#[test] +fn levels_writer_preserves_gamma_conversion_and_all_default_records() { + // Expected bytes are constants, not another execution of the conversion. + for (gamma, gamma_bytes) in [ + (0.125, [0, 13]), + (-0.125, [255, 243]), + (0.0, [0, 0]), + (-0.0, [0, 0]), + (f64::NAN, [0, 0]), + (f64::INFINITY, [127, 255]), + (f64::NEG_INFINITY, [128, 0]), + (f64::MAX, [127, 255]), + (-f64::MAX, [128, 0]), + (400.0, [127, 255]), + (-400.0, [128, 0]), + (1.0, [0, 100]), + ] { + let mut expected = vec![0, 2, 0x80, 0, 0x7f, 0xff, 0xff, 0xff, 0, 0]; + expected.extend(gamma_bytes); + expected.extend([0, 0, 0, 255, 0, 0, 0, 255, 0, 100].repeat(28)); + assert_written_payload(levels_block(i16::MIN, i16::MAX, -1, 0, gamma), *b"levl", expected); + } +} diff --git a/crates/psd/src/write.rs b/crates/psd/src/write.rs index b8067fc92..1004e28b5 100644 --- a/crates/psd/src/write.rs +++ b/crates/psd/src/write.rs @@ -434,30 +434,14 @@ pub fn solid_color_block(rgb: [f64; 3]) -> ([u8; 4], Vec) { /// `hue2`: Hue/Saturation (master). pub fn hue_sat_block(hue: i16, sat: i16, light: i16) -> ([u8; 4], Vec) { - let mut d = vec![]; - put_u16(&mut d, 2); - d.extend_from_slice(&[0, 0]); - for v in [0i16, 0, 0, hue, sat, light] { - d.extend_from_slice(&v.to_be_bytes()); - } - // Six colour ranges (unused). - d.resize(d.len() + 6 * 24, 0); - (*b"hue2", d) + let block = craft_psd::adjust::hue_saturation_block(hue, sat, light); + (block.key, block.data) } /// `levl`: Levels (composite record). pub fn levels_block(in_black: i16, in_white: i16, out_black: i16, out_white: i16, gamma: f64) -> ([u8; 4], Vec) { - let mut d = vec![]; - put_u16(&mut d, 2); - for v in [in_black, in_white, out_black, out_white, (gamma * 100.0).round() as i16] { - d.extend_from_slice(&v.to_be_bytes()); - } - for _ in 0..28 { - for v in [0i16, 255, 0, 255, 100] { - d.extend_from_slice(&v.to_be_bytes()); - } - } - (*b"levl", d) + let block = craft_psd::adjust::levels_block(in_black, in_white, out_black, out_white, (gamma * 100.0).round() as i16); + (block.key, block.data) } pub fn invert_block() -> ([u8; 4], Vec) { From f6ed0b250002404a705e0cd40ce51a535df6eac7 Mon Sep 17 00:00:00 2001 From: nicolafalcier99 Date: Thu, 19 Nov 2026 09:12:26 +0900 Subject: [PATCH 77/78] #3391: a Views 1 | 2 | 4 switch in the Composition viewer's control row (#3848) * contributors: Nicola Falcier * #3391: a Views 1 | 2 | 4 switch in the Composition viewer's control row --------- Co-authored-by: Nicola Falcier <298941634+nicolafalcier99@users.noreply.github.com> --- contributors/people.toml | 5 ++ crates/ui-egui/src/a11y.rs | 11 ++++ crates/ui-egui/src/i18n/ui.rs | 11 ++++ crates/ui-egui/src/panels/viewer_tools.rs | 32 ++++++++++ crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/ui_view_layout.rs | 70 ++++++++++++++++++++++ crates/ui-egui/tests/it/viewer_geometry.rs | 41 ++++++++++--- 7 files changed, 163 insertions(+), 8 deletions(-) create mode 100644 crates/ui-egui/tests/it/ui_view_layout.rs diff --git a/contributors/people.toml b/contributors/people.toml index beb91a413..4f77ce8d1 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -138,3 +138,8 @@ sync_github_name = true [people.andreaaazo] sync_github_name = true + +[people.nicolafalcier99] +real_name = "Nicola Falcier" +display_name = "Nicola Falcier" +sync_github_name = false diff --git a/crates/ui-egui/src/a11y.rs b/crates/ui-egui/src/a11y.rs index b8f88ae23..b33c8ac05 100644 --- a/crates/ui-egui/src/a11y.rs +++ b/crates/ui-egui/src/a11y.rs @@ -103,6 +103,17 @@ pub(crate) fn check_box(r: &Response, label: &str, checked: bool, enabled: bool) }); } +/// A push button that is one of a set of choices (a view-layout button): `pressed` is whether it is +/// the current one, exposed as the toggled state. `description` says what the set is. +pub(crate) fn choice_button(r: &Response, label: &str, description: &str, pressed: bool) { + node(r, |n| { + n.set_role(Role::Button); + n.set_label(label); + n.set_description(description); + n.set_toggled(if pressed { Toggled::True } else { Toggled::False }); + }); +} + /// A drop-down: `label` says what it sets and `value` is what it is set to. pub(crate) fn combo_box(r: &Response, label: &str, value: &str, enabled: bool) { node(r, |n| { diff --git a/crates/ui-egui/src/i18n/ui.rs b/crates/ui-egui/src/i18n/ui.rs index b2e0b3631..69a8d56a1 100644 --- a/crates/ui-egui/src/i18n/ui.rs +++ b/crates/ui-egui/src/i18n/ui.rs @@ -181,6 +181,7 @@ pub(crate) fn tr_args(text: &str, args: &[&dyn Display]) -> String { /// Japanese: the same rows, in the same order, as the Chinese catalogs below. const JAPANESE: &[(&str, &str)] = &[ + ("Views:", "画面:"), ("Click to sample color", "クリックして色をサンプル"), ("Appearance Settings…", "外観設定…"), ("Add to favorites", "お気に入りに追加"), @@ -1325,6 +1326,7 @@ const JAPANESE: &[(&str, &str)] = &[ ]; const SIMPLIFIED_CHINESE: &[(&str, &str)] = &[ + ("Views:", "视图:"), ("Click to sample color", "单击以取样颜色"), ("Appearance Settings…", "外观设置…"), ("Add to favorites", "添加到收藏"), @@ -2445,6 +2447,7 @@ const SIMPLIFIED_CHINESE: &[(&str, &str)] = &[ /// Swedish (`sv`), written from the English source. const SWEDISH: &[(&str, &str)] = &[ + ("Views:", "Vyer:"), ("Appearance Settings…", "Utseendeinställningar…"), ("Add to favorites", "Lägg till i favoriter"), ("Remove from favorites", "Ta bort från favoriter"), @@ -3721,6 +3724,7 @@ const SWEDISH: &[(&str, &str)] = &[ ]; const TRADITIONAL_CHINESE: &[(&str, &str)] = &[ + ("Views:", "檢視:"), ("Click to sample color", "按一下以取樣顏色"), ("Appearance Settings…", "外觀設定…"), ("Add to favorites", "加入最愛"), @@ -4790,6 +4794,7 @@ const TRADITIONAL_CHINESE: &[(&str, &str)] = &[ /// Ukrainian (uk): original translations of the same interface rows as the Chinese catalogs. /// Technical names, key names and substituted project content keep their original spelling. const UKRAINIAN: &[(&str, &str)] = &[ + ("Views:", "Вигляди:"), ("Click to sample color", "Клацніть, щоб узяти зразок кольору"), ("Appearance Settings…", "Налаштування вигляду…"), ("Add to favorites", "Додати до вибраного"), @@ -5380,6 +5385,7 @@ const UKRAINIAN: &[(&str, &str)] = &[ // Brazilian Portuguese. const PORTUGUESE: &[(&str, &str)] = &[ + ("Views:", "Visualizações:"), ("Click to sample color", "Clique para obter uma amostra de cor"), ("Export Scene to Blender...", "Exportar cena para o Blender..."), (" OK ", " OK "), @@ -6148,6 +6154,7 @@ const PORTUGUESE: &[(&str, &str)] = &[ /// Polish (pl): original translations covering every row in the Chinese panel catalogs. const POLISH: &[(&str, &str)] = &[ + ("Views:", "Widoki:"), ("Click to sample color", "Kliknij, aby pobrać próbkę koloru"), ("Appearance Settings…", "Ustawienia wyglądu…"), ("Add to favorites", "Dodaj do ulubionych"), @@ -6909,6 +6916,7 @@ const POLISH: &[(&str, &str)] = &[ /// Czech (cs): original translations covering every row in the Chinese panel catalogs. const CZECH: &[(&str, &str)] = &[ + ("Views:", "Zobrazení:"), ("Click to sample color", "Kliknutím naberete barvu"), (" OK ", " OK "), (" Delete ", " Odstranit "), @@ -7479,6 +7487,7 @@ const CZECH: &[(&str, &str)] = &[ /// order. Terms follow the Spanish menu catalog (composición, material de archivo, cola de procesamiento, /// ajuste preestablecido, método abreviado). Written from the English source. const SPANISH: &[(&str, &str)] = &[ + ("Views:", "Vistas:"), ("Click to sample color", "Haz clic para tomar una muestra de color"), ("Copy Source Path", "Copiar ruta de origen"), ("Appearance Settings…", "Ajustes de apariencia…"), @@ -8051,6 +8060,7 @@ const SPANISH: &[(&str, &str)] = &[ /// Georgian (ka): every row of the Chinese catalogs, in the same order (the tests keep them in step). const GEORGIAN: &[(&str, &str)] = &[ + ("Views:", "ხედები:"), ("Click to sample color", "დააწკაპუნეთ ფერის ნიმუშის ასაღებად"), ("Appearance Settings…", "იერსახის პარამეტრები…"), ("Add to favorites", "რჩეულებში დამატება"), @@ -9023,6 +9033,7 @@ const GEORGIAN_PANELS: &[(&str, &str)] = &[ /// clé, métrage, file d'attente de rendu, chronologie, repère, estampe). A no-break space precedes /// `:`, `;`, `?` and `!`, and the apostrophe is the typographic one. Written from the English source. const FRENCH: &[(&str, &str)] = &[ + ("Views:", "Vues\u{a0}:"), ("Appearance Settings…", "Paramètres d’apparence…"), ("Add to favorites", "Ajouter aux favoris"), ("Remove from favorites", "Retirer des favoris"), diff --git a/crates/ui-egui/src/panels/viewer_tools.rs b/crates/ui-egui/src/panels/viewer_tools.rs index ded5fbdb3..52e19e999 100644 --- a/crates/ui-egui/src/panels/viewer_tools.rs +++ b/crates/ui-egui/src/panels/viewer_tools.rs @@ -969,12 +969,16 @@ fn bottom_bar_contents(app: &mut EffectcraftApp, ui: &mut egui::Ui, bar: Rect, z let _ = app.session.execute("view.set3DView", json!({"view": View3D::ALL[i].id()})); } x = r.max.x + 4.0; + x = layout_switch(app, ui, x, cy, &t); // Extended Viewer (Settings ▸ 3D): custom views and Draft 3D show past the comp frame. let on = app.session.prefs.three_d.extended_viewer; if tog(ui, &mut app.auto, &mut x, Icon::ExtendedViewer, on, "extendedViewer", "Extended Viewer").0 { let _ = app.session.execute("view.extendedViewer", json!({})); } x += 2.0; + } else { + // A 2D comp has no 3D View menu, but it can still be in a 2/4-view layout: keep the way back. + x = layout_switch(app, ui, x, cy, &t); } // Current time. let tc = crate::panels::timecode(&app.session, comp, time); @@ -1005,6 +1009,34 @@ fn go_to_time_on_click(app: &mut EffectcraftApp, resp: &egui::Response) { } } +/// The "Views: 1 | 2 | 4" switch (#3391): a label and three text buttons, the current layout +/// highlighted; a click runs `view.layout`. Returns the x after it. +fn layout_switch(app: &mut EffectcraftApp, ui: &mut egui::Ui, mut x: f32, cy: f32, t: &Tokens) -> f32 { + let label = crate::i18n::tr("Views:"); + let g = ui.painter().layout_no_wrap(label.to_string(), Tokens::ui(11.0), t.text_dim); + ui.painter().galley(pos2(x, cy - g.size().y / 2.0), g.clone(), t.text_dim); + x += g.size().x + 4.0; + let current = app.session.state.view_layout; + for (n, text, tip) in [(1u8, "1", "1 View"), (2, "2", "2 Views"), (4, "4", "4 Views")] { + let r = Rect::from_min_size(pos2(x, cy - 10.0), vec2(26.0, 20.0)); + let resp = widgets::text_button(ui, r, text, current == n, t, egui::Id::unique(("vw-layout", n))); + // The drawn text is just "1" / "2" / "4": the accessible name is the full "N View(s)", the group + // label ("Views") is its description, and the current layout is exposed as pressed. + let name = crate::i18n::command_label("view.layout", tip); + crate::a11y::choice_button(&resp, name, label.trim_end_matches([':', ':', ' ', '\u{a0}']), current == n); + let resp = resp.on_hover_text(name); + app.auto.add_response(&format!("viewer.layout.{n}"), &resp, tip); + if resp.clicked() + && current != n + && let Err(e) = app.session.execute("view.layout", json!({"views": n})) + { + app.ui.status = e.to_string(); + } + x = r.max.x + 2.0; + } + x + 4.0 +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 8b156cb51..f80611a9b 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -112,6 +112,7 @@ mod ui_toolbar_gradient; mod ui_tracker; mod ui_unreadable_footage; mod ui_video_preview_off; +mod ui_view_layout; mod ui_viewer; mod ui_viewer_trackpad; mod ui_viewers; diff --git a/crates/ui-egui/tests/it/ui_view_layout.rs b/crates/ui-egui/tests/it/ui_view_layout.rs new file mode 100644 index 000000000..a6af5c688 --- /dev/null +++ b/crates/ui-egui/tests/it/ui_view_layout.rs @@ -0,0 +1,70 @@ +//! #3391: the Composition viewer's control row has a "Views: 1 | 2 | 4" switch (egui_kittest). + +use effectcraft_engine::Session; +use effectcraft_ui_egui::EffectcraftApp; +use egui_kittest::Harness; +use serde_json::json; + +fn harness(comp: Option<&str>) -> Harness<'static, EffectcraftApp> { + let mut s = Session::default(); + s.execute("file.openDemoProject", json!({})).unwrap(); + if let Some(comp) = comp { + s.execute("comp.open", json!({"comp": comp})).unwrap(); + } + Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s)) +} + +/// Click the centre of the automation element `id`. +fn click_id(h: &mut Harness<'_, EffectcraftApp>, id: &str) { + h.run_steps(3); + let [x, y, w, hh] = h.state().auto.find(id).unwrap_or_else(|| panic!("{id} is registered")).rect; + let p = egui::pos2(x + w / 2.0, y + hh / 2.0); + h.input_mut().events.push(egui::Event::PointerMoved(p)); + h.input_mut().events.push(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.step(); + h.input_mut().events.push(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(3); +} + +#[test] +fn the_layout_buttons_switch_between_one_two_and_four_views_in_a_3d_comp() { + let mut h = harness(Some("3D Showcase")); + h.run_steps(3); + assert!(h.state().auto.find("viewer.view3d").is_some(), "this is a 3D comp"); + for (id, want) in [("viewer.layout.4", 4), ("viewer.layout.2", 2), ("viewer.layout.1", 1)] { + click_id(&mut h, id); + assert_eq!(h.state().session.state.view_layout, want, "{id}"); + } +} + +#[test] +fn the_layout_buttons_are_there_in_a_2d_comp_too() { + let mut h = harness(None); + h.run_steps(3); + assert!(h.state().auto.find("viewer.view3d").is_none(), "this is a 2D comp"); + for id in ["viewer.layout.1", "viewer.layout.2", "viewer.layout.4"] { + assert!(h.state().auto.find(id).is_some(), "{id} is registered"); + } + click_id(&mut h, "viewer.layout.4"); + assert_eq!(h.state().session.state.view_layout, 4); +} + +#[test] +fn the_layout_buttons_are_named_in_full_and_expose_the_current_layout() { + use egui::accesskit::{Role, Toggled}; + use egui_kittest::kittest::{NodeT, Queryable}; + let mut h = harness(None); + h.run_steps(3); + let state = |h: &Harness<'_, EffectcraftApp>, name: &str| { + let node = h.query_by_label(name).unwrap_or_else(|| panic!("a button named {name:?}")); + let node = node.accesskit_node(); + assert_eq!(node.role(), Role::Button, "{name}"); + node.toggled() + }; + assert_eq!(state(&h, "1 View"), Some(Toggled::True)); + assert_eq!(state(&h, "2 Views"), Some(Toggled::False)); + assert_eq!(state(&h, "4 Views"), Some(Toggled::False)); + click_id(&mut h, "viewer.layout.2"); + assert_eq!(state(&h, "1 View"), Some(Toggled::False)); + assert_eq!(state(&h, "2 Views"), Some(Toggled::True)); +} diff --git a/crates/ui-egui/tests/it/viewer_geometry.rs b/crates/ui-egui/tests/it/viewer_geometry.rs index 8a212cc35..72ee46013 100644 --- a/crates/ui-egui/tests/it/viewer_geometry.rs +++ b/crates/ui-egui/tests/it/viewer_geometry.rs @@ -19,14 +19,22 @@ fn harness(width: f32, kind: ThemeKind) -> Harness<'static, EffectcraftApp> { fn harness_at_scale(width: f32, kind: ThemeKind, scale: f32) -> Harness<'static, EffectcraftApp> { let mut session = Session::default(); session.execute("comp.new", json!({"name":"Geometry validation", "width":640, "height":360, "duration":4})).unwrap(); - let mut h = Harness::builder().with_size(vec2(width, 360.0)).with_pixels_per_point(scale).build_ui_state( - |ui, app: &mut EffectcraftApp| { - app.auto.begin_frame(); - *app.frames.last_ms.lock().unwrap() = 0.0; - viewer::show(app, ui, ui.max_rect()); - }, - EffectcraftApp::new(session), - ); + let app = EffectcraftApp::new(session); + // Install the fonts the real app installs at startup *before* the harness's first pass: the control + // row draws `widgets::text_button` text in the "medium" family, which has no fonts until then. + let tokens = app.tokens; + let mut h = Harness::builder() + .with_size(vec2(width, 360.0)) + .with_pixels_per_point(scale) + .with_context_setup(move |ctx| theme::install(ctx, &tokens, "en")) + .build_ui_state( + |ui, app: &mut EffectcraftApp| { + app.auto.begin_frame(); + *app.frames.last_ms.lock().unwrap() = 0.0; + viewer::show(app, ui, ui.max_rect()); + }, + app, + ); let ctx = h.ctx.clone(); h.state_mut().set_theme(&ctx, kind); theme::install(&ctx, &h.state().tokens, "en"); @@ -107,7 +115,24 @@ fn compact_control_row_scrolls_and_preserves_interactions() { let timecode = rect(&h, "viewer.timecode"); let row = rect(&h, "viewer.controls"); assert!(timecode.left() >= row.left() && timecode.right() <= row.right(), "last viewer control must scroll into view: {timecode:?}"); + // The Views switch (#3391) widened the row, so the exposure reset is no longer in view at the far + // end: scroll back until it is, then check the scrolled controls as before. + for _ in 0..40 { + let e = rect(&h, "viewer.resetExposure"); + if e.left() >= row.left() && e.right() <= row.right() { + break; + } + h.event(Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(40.0, 0.0), + modifiers: Default::default(), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + }); + h.run_steps(4); + } let exposure = rect(&h, "viewer.resetExposure"); + // The convergence check for the scroll-back loop above: it must have brought the control into view. assert!(exposure.left() >= row.left() && exposure.right() <= row.right()); h.state_mut().session.execute("view.exposure", json!({"stops":2.0})).unwrap(); h.run_steps(2); From 665bfac0b33904b1dcda6de889f43f43a94ad3f8 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 21:55:05 -0500 Subject: [PATCH 78/78] export: cut over exr_out to craft-exr (#3937) * export: cut over exr_out to craft-exr * fix(export): keep exr in dev-dependencies for tests --- Cargo.lock | 3 +- Cargo.toml | 2 +- crates/export/Cargo.toml | 3 +- crates/export/src/exr_out.rs | 107 ++++++++++++----------------------- 4 files changed, 42 insertions(+), 73 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c8bb8f50f..01e0b6fd4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1314,7 +1314,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2 [[package]] name = "craft-exr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e" dependencies = [ "exr", "flate2", @@ -2091,6 +2091,7 @@ name = "effectcraft-export" version = "0.24.1" dependencies = [ "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", + "craft-exr", "craft-gif", "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", diff --git a/Cargo.toml b/Cargo.toml index 832eeef8c..6fbb4f986 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } -craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } +craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3b8e426a260695af840a2cd79a064d40778f939e" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "fa4741d0bbba8da303dd1bb1a93cbcb78e7747a0" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" } diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml index 1bf883df3..6b93a8a7c 100644 --- a/crates/export/Cargo.toml +++ b/crates/export/Cargo.toml @@ -18,14 +18,15 @@ craft-video = { workspace = true } craft-audio = { workspace = true } craft-media = { workspace = true } craft-gif = { workspace = true } +craft-exr = { workspace = true, features = ["decode"] } image = { workspace = true, features = ["png", "jpeg", "tiff", "exr", "tga"] } -exr = { workspace = true } rayon = { workspace = true } web-time = { workspace = true } thiserror = { workspace = true } log = { workspace = true } [dev-dependencies] +exr = { workspace = true } gif = { workspace = true } tempfile = { workspace = true } effectcraft-media = { workspace = true } diff --git a/crates/export/src/exr_out.rs b/crates/export/src/exr_out.rs index 43467629a..cefa81a07 100644 --- a/crates/export/src/exr_out.rs +++ b/crates/export/src/exr_out.rs @@ -12,40 +12,25 @@ use std::io::{Seek, Write}; +use craft_exr::decode::{Compression, Result, SampleDepth}; use effectcraft_project::render_queue::{ExrBitDepth, ExrCompression}; -use exr::meta::attribute::Chromaticities; -use exr::prelude::{Blocks, Compression, Encoding, Image, Layer, LayerAttributes, LineOrder, SpecificChannels, Vec2, WritableImage, f16}; -/// The largest finite half float. -const HALF_MAX: f32 = 65_504.0; - -/// A sample as half float: rounded to the nearest half (ties to even), held to ±65 504 so an -/// over-range render doesn't turn into infinity. NaN stays NaN. -fn to_half(v: f32) -> f16 { - f16::from_f32(v.clamp(-HALF_MAX, HALF_MAX)) -} - -/// The `exr` crate's compression for an Output Module setting. +/// The `craft-exr` compression for an Output Module setting. pub fn compression(c: ExrCompression) -> Compression { match c { - ExrCompression::None => Compression::Uncompressed, - ExrCompression::Rle => Compression::RLE, - ExrCompression::Zips => Compression::ZIP1, - ExrCompression::Zip => Compression::ZIP16, - ExrCompression::Piz => Compression::PIZ, - ExrCompression::Pxr24 => Compression::PXR24, + ExrCompression::None => Compression::None, + ExrCompression::Rle => Compression::Rle, + ExrCompression::Zips => Compression::Zip1, + ExrCompression::Zip => Compression::Zip16, + ExrCompression::Piz => Compression::Piz, + ExrCompression::Pxr24 => Compression::Pxr24, ExrCompression::B44 => Compression::B44, - ExrCompression::B44a => Compression::B44A, - ExrCompression::Dwaa => Compression::DWAA(None), - ExrCompression::Dwab => Compression::DWAB(None), + ExrCompression::B44a => Compression::B44a, + ExrCompression::Dwaa => Compression::Dwaa, + ExrCompression::Dwab => Compression::Dwab, } } -/// Scan lines, top to bottom, with compression `c`. -fn encoding(c: ExrCompression) -> Encoding { - Encoding { compression: compression(c), blocks: Blocks::ScanLines, line_order: LineOrder::Increasing } -} - /// Write `w`×`h` RGBA pixels (`data`: four samples per pixel as they are to be written, /// premultiplied, rows top to bottom) as one OpenEXR frame, its blocks compressed in parallel as before. A pixel `data` /// doesn't cover is written as transparent black. @@ -58,56 +43,38 @@ pub fn write_rgba( (w, h): (usize, usize), (c, depth): (ExrCompression, ExrBitDepth), chroma: Option<[[f32; 2]; 4]>, -) -> exr::error::UnitResult { - let chroma = chroma.map(|[red, green, blue, white]| { - let v = |[x, y]: [f32; 2]| Vec2(x, y); - Chromaticities { red: v(red), green: v(green), blue: v(blue), white: v(white) } - }); - let row = w.saturating_mul(4); - let px = move |p: Vec2| -> [f32; 4] { - let o = p.y().saturating_mul(row).saturating_add(p.x().saturating_mul(4)); - match data.get(o..o.saturating_add(4)) { - Some(&[r, g, b, a]) => [r, g, b, a], - _ => [0.0; 4], - } +) -> Result<()> { + let sample_depth = match depth { + ExrBitDepth::Float => SampleDepth::Float, + ExrBitDepth::Half => SampleDepth::Half, }; - match depth { - ExrBitDepth::Float => { - let mut image = Image::from_layer(Layer::new( - (w, h), - LayerAttributes::default(), - encoding(c), - SpecificChannels::rgba(move |p: Vec2| { - let [r, g, b, a] = px(p); - (r, g, b, a) - }), - )); - image.attributes.chromaticities = chroma; - image.write().to_buffered(file) - } - ExrBitDepth::Half => { - let mut image = Image::from_layer(Layer::new( - (w, h), - LayerAttributes::default(), - encoding(c), - SpecificChannels::rgba(move |p: Vec2| { - let [r, g, b, a] = px(p).map(to_half); - (r, g, b, a) - }), - )); - image.attributes.chromaticities = chroma; - image.write().to_buffered(file) - } - } + craft_exr::decode::write_rgba(file, data, w as u32, h as u32, sample_depth, compression(c), chroma) } #[cfg(test)] mod tests { use super::*; - use exr::prelude::{ReadChannels, ReadLayers}; - use exr::prelude::{SampleType, read}; + use exr::prelude::{ + Encoding, Image, Layer, LayerAttributes, LineOrder, ReadChannels, ReadLayers, SampleType, SpecificChannels, Vec2, WritableImage, f16, read, + }; use std::io::Cursor; + fn exr_compression(c: ExrCompression) -> exr::compression::Compression { + use exr::compression::Compression as C; + match c { + ExrCompression::None => C::Uncompressed, + ExrCompression::Rle => C::RLE, + ExrCompression::Zips => C::ZIP1, + ExrCompression::Zip => C::ZIP16, + ExrCompression::Piz => C::PIZ, + ExrCompression::Pxr24 => C::PXR24, + ExrCompression::B44 => C::B44, + ExrCompression::B44a => C::B44A, + ExrCompression::Dwaa => C::DWAA(None), + ExrCompression::Dwab => C::DWAB(None), + } + } + /// A frame with a smooth gradient, grain, over-range highlights, a hard-edged high-contrast /// block and a soft alpha ramp (premultiplied), like a render with text over a plate. fn frame(w: usize, h: usize) -> Vec { @@ -172,7 +139,7 @@ mod tests { }; let ty = if depth == ExrBitDepth::Half { SampleType::F16 } else { SampleType::F32 }; for c in ExrCompression::ALL { - assert_eq!(c.is_lossy(depth), !compression(c).is_lossless_for(ty), "{c:?} {depth:?}"); + assert_eq!(c.is_lossy(depth), !exr_compression(c).is_lossless_for(ty), "{c:?} {depth:?}"); let bytes = write(&src, (w, h), c, depth); if c.is_lossy(depth) { assert!(bytes.len() < write(&src, (w, h), ExrCompression::None, depth).len(), "{c:?} {depth:?}: smaller than None"); @@ -205,7 +172,7 @@ mod tests { let meta = exr::meta::MetaData::read_from_buffered(Cursor::new(&bytes), false).unwrap(); assert_eq!(meta.headers.len(), 1); assert_eq!(meta.headers[0].blocks, exr::meta::BlockDescription::ScanLines, "{c:?}"); - assert_eq!(meta.headers[0].compression, compression(c), "{c:?}"); + assert_eq!(meta.headers[0].compression, exr_compression(c), "{c:?}"); assert_eq!(meta.headers[0].line_order, LineOrder::Increasing); } }