From 6591d38b582905e5f6eec2debb11627f48cc5015 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:45:11 +0100 Subject: [PATCH 1/4] Render Video: Alpha Channel option for PNG sequences (#14163) file.export.renderVideo takes `alpha` (none, straight, premultipliedBlack, premultipliedWhite, premultipliedColor; default none) and `matte` (default black). A PNG frame is written from the composite with the choice applied: none writes RGB with transparent areas black, straight keeps the colours and makes fully transparent pixels white, the premultiplied choices mix each colour with the matte by its opacity and keep the alpha. A frame left fully opaque is written as RGB. Other formats ignore the option; a wrong value is an error. --- crates/engine-core/src/cmd/video_cmds.rs | 95 +++++++++++++++- .../video_cmds/render_video_alpha_tests.rs | 104 ++++++++++++++++++ 2 files changed, 198 insertions(+), 1 deletion(-) create mode 100644 crates/engine-core/src/cmd/video_cmds/render_video_alpha_tests.rs diff --git a/crates/engine-core/src/cmd/video_cmds.rs b/crates/engine-core/src/cmd/video_cmds.rs index dd0d1368a0..56f7d1cef5 100644 --- a/crates/engine-core/src/cmd/video_cmds.rs +++ b/crates/engine-core/src/cmd/video_cmds.rs @@ -665,6 +665,7 @@ pub fn render_video_with( ) -> Result { let dir = p.get("dir").and_then(Value::as_str).unwrap_or(""); let format = p.get("format").and_then(Value::as_str).unwrap_or("png"); + let alpha = render_alpha(p)?; let st = s.active().ok_or(EngineError::NoDocument)?; let mut base = (*st.doc).clone(); store(&mut base); @@ -721,6 +722,8 @@ pub fn render_video_with( // Image sequence. // PSD / PSB frames would embed the files linked smart objects name: not for a restricted session. let opts = photocraft_io::ExportOptions { read_linked_files: s.authorize.is_none(), ..Default::default() }; + // Only a PNG sequence can hold the alpha the option chooses; other formats ignore it. + let alpha = format.eq_ignore_ascii_case("png").then_some(alpha); let mut files = Vec::new(); for f in 0..frames { let mut doc = base.clone(); @@ -728,6 +731,9 @@ pub fn render_video_with( t.current = f; } sync(&mut doc); + if let Some(alpha) = alpha { + doc = matted_frame(&doc, alpha)?; + } let path = format!("{stem}_{f:04}.{format}"); let bytes = photocraft_io::export(&doc, format, &opts).map(|r| r.bytes).map_err(|e| EngineError::Other(format!("render frame {f}: {e}")))?; write(&path, &bytes)?; @@ -739,6 +745,86 @@ pub fn render_video_with( Ok(json!({"frames": files.len(), "dir": dir})) } +/// Render Video's Alpha Channel choice for a sequence frame (#14163). +#[derive(Clone, Copy, Debug, PartialEq)] +enum RenderAlpha { + /// No alpha in the file: transparent areas are black. + None, + /// The colours as composited; fully transparent pixels are white. + Straight, + /// Colours mixed with the matte by their opacity (`c·a + matte·(1 - a)`), alpha kept. + Premultiplied([f32; 3]), +} + +/// `alpha` and `matte` of `file.export.renderVideo`; a wrong type or name is an error. +fn render_alpha(p: &Value) -> Result { + let bad = |msg: &str| EngineError::BadParams { cmd: "file.export.renderVideo".into(), msg: msg.into() }; + let matte = match p.get("matte") { + None | Some(Value::Null) => [0.0; 3], + Some(Value::String(c)) => { + crate::commands::parse_hex(c).map(|c| [c[0], c[1], c[2]]).ok_or_else(|| bad("`matte` must be \"#rrggbb\" or [r, g, b] in 0..1"))? + } + Some(Value::Array(a)) if a.len() == 3 => { + let mut c = [0.0; 3]; + for (slot, v) in c.iter_mut().zip(a) { + *slot = v.as_f64().filter(|x| (0.0..=1.0).contains(x)).ok_or_else(|| bad("`matte` as an array must hold 3 numbers in 0..1"))? as f32; + } + c + } + Some(_) => return Err(bad("`matte` must be \"#rrggbb\" or [r, g, b] in 0..1")), + }; + match p.get("alpha") { + None | Some(Value::Null) => Ok(RenderAlpha::None), + Some(Value::String(a)) => match a.as_str() { + "none" => Ok(RenderAlpha::None), + "straight" => Ok(RenderAlpha::Straight), + "premultipliedBlack" => Ok(RenderAlpha::Premultiplied([0.0; 3])), + "premultipliedWhite" => Ok(RenderAlpha::Premultiplied([1.0; 3])), + "premultipliedColor" => Ok(RenderAlpha::Premultiplied(matte)), + _ => Err(bad("`alpha` must be \"none\", \"straight\", \"premultipliedBlack\", \"premultipliedWhite\" or \"premultipliedColor\"")), + }, + Some(_) => Err(bad("`alpha` must be a string")), + } +} + +/// `doc` as one layer holding its composite with `alpha` applied, at the document's own depth. +/// A frame left fully opaque is written without alpha, as any opaque export is. +fn matted_frame(doc: &Document, alpha: RenderAlpha) -> Result { + let fmt = doc.pixel_format(); + let bounds = doc.bounds(); + let mut surf = crate::file_cmds::flattened_checked(doc, fmt, "file.export.renderVideo")?; + let n = fmt.channels(); + let color = fmt.mode.color_channels(); + let paint = |rgb: [f32; 3]| photocraft_raster::from_rgba(&fmt, [rgb[0], rgb[1], rgb[2], 1.0]); + let white = paint([1.0; 3]); + let matte = paint(if let RenderAlpha::Premultiplied(m) = alpha { m } else { [0.0; 3] }); + let mut band = Vec::new(); + // A band of tile rows at a time, so no frame-sized float buffer is held. + for y in (bounds.y0..bounds.y1).step_by(photocraft_geom::TILE_SIZE as usize) { + let rows = photocraft_geom::Rect::new(bounds.x0, y, bounds.x1, (y + photocraft_geom::TILE_SIZE).min(bounds.y1)); + surf.read_region_into(rows, &mut band); + for px in band.chunks_exact_mut(n) { + let a = px[color].clamp(0.0, 1.0); + match alpha { + RenderAlpha::Straight if a <= 0.0 => px[..color].copy_from_slice(&white[..color]), + RenderAlpha::Straight => {} + RenderAlpha::None | RenderAlpha::Premultiplied(_) => { + for (c, m) in px[..color].iter_mut().zip(&matte) { + *c = *c * a + m * (1.0 - a); + } + if alpha == RenderAlpha::None { + px[color] = 1.0; + } + } + } + } + surf.write_region(rows, &band); + } + let mut out = doc.clone(); + out.layers = vec![Layer::new("Layer 0", LayerContent::Raster(surf))].into(); + Ok(out) +} + /// One animated GIF frame from straight RGBA pixels, as Save for Web's GIF does (#3061): pixels /// under 50 % opacity get the frame's transparent index, the rest are drawn opaque, and the /// palette is built from the visible pixels with one entry kept for transparency. @@ -781,9 +867,16 @@ pub fn specs() -> Vec { spec!("layer.videoLayers.interpretFootage", "Interpret Footage…", vl, active_video, |s, p| interpret_footage(s, p)), spec!("layer.videoLayers.reloadFrame", "Reload Frame", vl, active_video, |s, p| reload_frame(s, p)), spec!("file.import.videoFramesToLayers", "Video Frames to Layers…", &["File", "Import"], has_doc, |s, p| frames_to_layers(s, p)), - spec!("file.export.renderVideo", "Render Video…", &["File", "Export"], has_doc, |s, p| render_video(s, p)), + CommandSpec { + params: r##"{"dir":folder,"format":"png|jpg|psd|tiff|…|gif"="png","alpha":"none|straight|premultipliedBlack|premultipliedWhite|premultipliedColor"="none" (png sequences only; none writes no alpha, transparent areas black),"matte":color=#000000 (premultipliedColor)} → {frames, dir}|{frames, file}"##, + ..spec!("file.export.renderVideo", "Render Video…", &["File", "Export"], has_doc, |s, p| render_video(s, p)) + }, ] } #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "video_cmds/render_video_alpha_tests.rs"] +mod render_video_alpha_tests; diff --git a/crates/engine-core/src/cmd/video_cmds/render_video_alpha_tests.rs b/crates/engine-core/src/cmd/video_cmds/render_video_alpha_tests.rs new file mode 100644 index 0000000000..183323056f --- /dev/null +++ b/crates/engine-core/src/cmd/video_cmds/render_video_alpha_tests.rs @@ -0,0 +1,104 @@ +//! Render Video's Alpha Channel option for image sequences (#14163). + +use photocraft_codecs::{ChannelLayout, Image}; +use photocraft_geom::Rect; +use serde_json::{Value, json}; + +use super::*; + +/// A 4 x 2 document at `depth` whose left half is opaque red and right half transparent; with +/// `background` the right half is the white Background instead, so the composite is opaque. +fn half_red(depth: u32, background: bool) -> Session { + let mut s = crate::session(); + let bg = if background { "white" } else { "transparent" }; + s.execute("file.new", json!({"width": 4, "height": 2, "depth": depth, "background": bg})).unwrap(); + s.edit("red", |doc, active| { + let id = (*active).ok_or(EngineError::NoDocument)?; + let surf = crate::pixels_mut(doc.layer_mut(id).ok_or(EngineError::NoDocument)?)?; + let red = photocraft_raster::from_rgba(&surf.format(), [1.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(0, 0, 2, 2), &red); + Ok(()) + }) + .unwrap(); + s +} + +/// The one PNG frame Render Video writes for `params`. +fn render(s: &Session, params: Value) -> Image { + let mut out = Vec::new(); + render_video_with( + s, + ¶ms, + |_, bytes| { + out.push(bytes.to_vec()); + Ok(()) + }, + |_, _| true, + ) + .unwrap(); + assert_eq!(out.len(), 1); + photocraft_codecs::decode(&out[0]).unwrap() +} + +/// The pixel at `x, y` in 0..255, with alpha when the file has it. +fn px(img: &Image, x: u32, y: u32) -> Vec { + (0..img.layout().channels()).map(|c| (img.get(x, y, c) * 255.0).round() as u32).collect() +} + +#[test] +fn each_choice_writes_the_measured_transparent_pixel_and_keeps_the_opaque_one() { + let cases: [(Value, ChannelLayout, [u32; 4]); 6] = [ + (json!({}), ChannelLayout::Rgb, [0, 0, 0, 255]), + (json!({"alpha": "none"}), ChannelLayout::Rgb, [0, 0, 0, 255]), + (json!({"alpha": "straight"}), ChannelLayout::Rgba, [255, 255, 255, 0]), + (json!({"alpha": "premultipliedBlack"}), ChannelLayout::Rgba, [0, 0, 0, 0]), + (json!({"alpha": "premultipliedWhite"}), ChannelLayout::Rgba, [255, 255, 255, 0]), + (json!({"alpha": "premultipliedColor", "matte": "#00ff00"}), ChannelLayout::Rgba, [0, 255, 0, 0]), + ]; + for depth in [8, 16] { + let s = half_red(depth, false); + for (choice, layout, transparent) in &cases { + let mut params = choice.clone(); + params["format"] = json!("png"); + let img = render(&s, params); + assert_eq!(img.layout(), *layout, "{choice} at {depth} bit"); + let n = layout.channels(); + assert_eq!(px(&img, 3, 1), transparent[..n], "transparent pixel, {choice} at {depth} bit"); + assert_eq!(px(&img, 0, 0), [255, 0, 0, 255][..n], "opaque pixel, {choice} at {depth} bit"); + } + } +} + +#[test] +fn an_opaque_document_writes_rgb_for_every_choice() { + let s = half_red(8, true); + for alpha in ["none", "straight", "premultipliedBlack", "premultipliedWhite", "premultipliedColor"] { + let img = render(&s, json!({"format": "png", "alpha": alpha, "matte": "#00ff00"})); + assert_eq!(img.layout(), ChannelLayout::Rgb, "{alpha}"); + assert_eq!(px(&img, 3, 1), [255, 255, 255], "{alpha}: the white Background shows"); + } +} + +#[test] +fn formats_without_the_option_keep_their_transparency() { + let s = half_red(8, false); + let img = render(&s, json!({"format": "tif", "alpha": "premultipliedColor", "matte": "#00ff00"})); + assert!(img.layout().channels() == 4, "TIFF keeps today's transparency: {:?}", img.layout()); + assert_eq!(px(&img, 3, 1)[3], 0); +} + +#[test] +fn a_wrong_alpha_or_matte_is_an_error() { + let s = half_red(8, false); + for params in [ + json!({"format": "png", "alpha": "matte"}), + json!({"format": "png", "alpha": true}), + json!({"format": "png", "alpha": "premultipliedColor", "matte": "green"}), + json!({"format": "png", "alpha": "premultipliedColor", "matte": [0, 2, 0]}), + json!({"format": "png", "alpha": "premultipliedColor", "matte": 7}), + json!({"format": "gif", "alpha": "matte"}), + ] { + let r = render_video_with(&s, ¶ms, |_, _| Ok(()), |_, _| true); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{params}: {r:?}"); + } +} From d137f58e061b002a3a422194db8bfc0e5a6a1b73 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:36:13 +0100 Subject: [PATCH 2/4] Render Video alpha: keep partly transparent pixels, strict matte (#14163) The issue measured only fully transparent pixels and says unmeasured cases keep today's behaviour, so straight and the premultiplied choices now change only fully transparent pixels (to white or the matte); partly transparent ones keep their colour and alpha. None still composites over black, now toward the document's own black in every colour mode. The matte accepts "#rrggbb" only, not "rrggbb" or "#rrggbbaa". A new test checks that 16-bit frames keep 16-bit precision and soft pixels. --- crates/engine-core/src/cmd/video_cmds.rs | 43 +++++++++---------- .../video_cmds/render_video_alpha_tests.rs | 29 ++++++++++++- 2 files changed, 49 insertions(+), 23 deletions(-) diff --git a/crates/engine-core/src/cmd/video_cmds.rs b/crates/engine-core/src/cmd/video_cmds.rs index 56f7d1cef5..c9cf6fd622 100644 --- a/crates/engine-core/src/cmd/video_cmds.rs +++ b/crates/engine-core/src/cmd/video_cmds.rs @@ -748,12 +748,12 @@ pub fn render_video_with( /// Render Video's Alpha Channel choice for a sequence frame (#14163). #[derive(Clone, Copy, Debug, PartialEq)] enum RenderAlpha { - /// No alpha in the file: transparent areas are black. + /// No alpha in the file: the colours are composited over black, so transparent areas are black. None, - /// The colours as composited; fully transparent pixels are white. - Straight, - /// Colours mixed with the matte by their opacity (`c·a + matte·(1 - a)`), alpha kept. - Premultiplied([f32; 3]), + /// The alpha is kept and fully transparent pixels take this colour: white for Straight, the + /// matte for the premultiplied choices. Partly transparent pixels keep their colour and alpha + /// (the issue measured only fully transparent ones). + Kept([f32; 3]), } /// `alpha` and `matte` of `file.export.renderVideo`; a wrong type or name is an error. @@ -761,9 +761,11 @@ fn render_alpha(p: &Value) -> Result { let bad = |msg: &str| EngineError::BadParams { cmd: "file.export.renderVideo".into(), msg: msg.into() }; let matte = match p.get("matte") { None | Some(Value::Null) => [0.0; 3], - Some(Value::String(c)) => { - crate::commands::parse_hex(c).map(|c| [c[0], c[1], c[2]]).ok_or_else(|| bad("`matte` must be \"#rrggbb\" or [r, g, b] in 0..1"))? - } + // `parse_hex` also reads "rrggbb" and "#rrggbbaa"; the matte is "#rrggbb" only. + Some(Value::String(c)) => crate::commands::parse_hex(c) + .filter(|_| c.len() == 7 && c.starts_with('#')) + .map(|c| [c[0], c[1], c[2]]) + .ok_or_else(|| bad("`matte` must be \"#rrggbb\" or [r, g, b] in 0..1"))?, Some(Value::Array(a)) if a.len() == 3 => { let mut c = [0.0; 3]; for (slot, v) in c.iter_mut().zip(a) { @@ -777,10 +779,9 @@ fn render_alpha(p: &Value) -> Result { None | Some(Value::Null) => Ok(RenderAlpha::None), Some(Value::String(a)) => match a.as_str() { "none" => Ok(RenderAlpha::None), - "straight" => Ok(RenderAlpha::Straight), - "premultipliedBlack" => Ok(RenderAlpha::Premultiplied([0.0; 3])), - "premultipliedWhite" => Ok(RenderAlpha::Premultiplied([1.0; 3])), - "premultipliedColor" => Ok(RenderAlpha::Premultiplied(matte)), + "straight" | "premultipliedWhite" => Ok(RenderAlpha::Kept([1.0; 3])), + "premultipliedBlack" => Ok(RenderAlpha::Kept([0.0; 3])), + "premultipliedColor" => Ok(RenderAlpha::Kept(matte)), _ => Err(bad("`alpha` must be \"none\", \"straight\", \"premultipliedBlack\", \"premultipliedWhite\" or \"premultipliedColor\"")), }, Some(_) => Err(bad("`alpha` must be a string")), @@ -796,8 +797,8 @@ fn matted_frame(doc: &Document, alpha: RenderAlpha) -> Result { let n = fmt.channels(); let color = fmt.mode.color_channels(); let paint = |rgb: [f32; 3]| photocraft_raster::from_rgba(&fmt, [rgb[0], rgb[1], rgb[2], 1.0]); - let white = paint([1.0; 3]); - let matte = paint(if let RenderAlpha::Premultiplied(m) = alpha { m } else { [0.0; 3] }); + let black = paint([0.0; 3]); + let clear = paint(if let RenderAlpha::Kept(c) = alpha { c } else { [0.0; 3] }); let mut band = Vec::new(); // A band of tile rows at a time, so no frame-sized float buffer is held. for y in (bounds.y0..bounds.y1).step_by(photocraft_geom::TILE_SIZE as usize) { @@ -806,16 +807,14 @@ fn matted_frame(doc: &Document, alpha: RenderAlpha) -> Result { for px in band.chunks_exact_mut(n) { let a = px[color].clamp(0.0, 1.0); match alpha { - RenderAlpha::Straight if a <= 0.0 => px[..color].copy_from_slice(&white[..color]), - RenderAlpha::Straight => {} - RenderAlpha::None | RenderAlpha::Premultiplied(_) => { - for (c, m) in px[..color].iter_mut().zip(&matte) { - *c = *c * a + m * (1.0 - a); - } - if alpha == RenderAlpha::None { - px[color] = 1.0; + RenderAlpha::None => { + for (c, k) in px[..color].iter_mut().zip(&black) { + *c = *c * a + k * (1.0 - a); } + px[color] = 1.0; } + RenderAlpha::Kept(_) if a <= 0.0 => px[..color].copy_from_slice(&clear[..color]), + RenderAlpha::Kept(_) => {} } } surf.write_region(rows, &band); diff --git a/crates/engine-core/src/cmd/video_cmds/render_video_alpha_tests.rs b/crates/engine-core/src/cmd/video_cmds/render_video_alpha_tests.rs index 183323056f..2635b4f6f7 100644 --- a/crates/engine-core/src/cmd/video_cmds/render_video_alpha_tests.rs +++ b/crates/engine-core/src/cmd/video_cmds/render_video_alpha_tests.rs @@ -1,6 +1,6 @@ //! Render Video's Alpha Channel option for image sequences (#14163). -use photocraft_codecs::{ChannelLayout, Image}; +use photocraft_codecs::{ChannelLayout, Image, SampleType}; use photocraft_geom::Rect; use serde_json::{Value, json}; @@ -69,6 +69,31 @@ fn each_choice_writes_the_measured_transparent_pixel_and_keeps_the_opaque_one() } } +/// A level only 16 bits can hold: 1000 / 65535 is between two 8-bit steps. +const FINE: f32 = 1000.0 / 65535.0; + +#[test] +fn a_16_bit_frame_keeps_its_precision_and_partly_transparent_pixels() { + let mut s = half_red(16, false); + s.edit("soft", |doc, active| { + let id = (*active).ok_or(EngineError::NoDocument)?; + crate::pixels_mut(doc.layer_mut(id).ok_or(EngineError::NoDocument)?)?.write_pixel(2, 0, &[FINE, 0.25, 0.0, 0.5]); + Ok(()) + }) + .unwrap(); + let near = |got: f32, want: f32, what: &str| assert!((got - want).abs() < 1.0 / 65535.0, "{what}: {got} vs {want}"); + for alpha in ["straight", "premultipliedBlack", "premultipliedWhite", "premultipliedColor"] { + let img = render(&s, json!({"format": "png", "alpha": alpha, "matte": "#00ff00"})); + assert_eq!(img.sample_type(), SampleType::U16, "{alpha}"); + // Not measured by the issue, so a partly transparent pixel keeps today's colour and alpha. + near(img.get(2, 0, 0), FINE, alpha); + near(img.get(2, 0, 3), 0.5, alpha); + } + let img = render(&s, json!({"format": "png", "alpha": "none"})); + assert_eq!((img.layout(), img.sample_type()), (ChannelLayout::Rgb, SampleType::U16)); + near(img.get(2, 0, 0), FINE * 0.5, "none composites over black"); +} + #[test] fn an_opaque_document_writes_rgb_for_every_choice() { let s = half_red(8, true); @@ -96,6 +121,8 @@ fn a_wrong_alpha_or_matte_is_an_error() { json!({"format": "png", "alpha": "premultipliedColor", "matte": "green"}), json!({"format": "png", "alpha": "premultipliedColor", "matte": [0, 2, 0]}), json!({"format": "png", "alpha": "premultipliedColor", "matte": 7}), + json!({"format": "png", "alpha": "premultipliedColor", "matte": "00ff00"}), + json!({"format": "png", "alpha": "premultipliedColor", "matte": "#00ff0080"}), json!({"format": "gif", "alpha": "matte"}), ] { let r = render_video_with(&s, ¶ms, |_, _| Ok(()), |_, _| true); From e5ef3bd3fe0092356f503aefc0767d6830f631a1 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:07:47 +0100 Subject: [PATCH 3/4] Render Video alpha: a matte array of the wrong length or with a non-number is an error (#14163) --- .../engine-core/src/cmd/video_cmds/render_video_alpha_tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/engine-core/src/cmd/video_cmds/render_video_alpha_tests.rs b/crates/engine-core/src/cmd/video_cmds/render_video_alpha_tests.rs index 2635b4f6f7..dc3661b12c 100644 --- a/crates/engine-core/src/cmd/video_cmds/render_video_alpha_tests.rs +++ b/crates/engine-core/src/cmd/video_cmds/render_video_alpha_tests.rs @@ -120,6 +120,8 @@ fn a_wrong_alpha_or_matte_is_an_error() { json!({"format": "png", "alpha": true}), json!({"format": "png", "alpha": "premultipliedColor", "matte": "green"}), json!({"format": "png", "alpha": "premultipliedColor", "matte": [0, 2, 0]}), + json!({"format": "png", "alpha": "premultipliedColor", "matte": [0, 1]}), + json!({"format": "png", "alpha": "premultipliedColor", "matte": [0, "1", 0]}), json!({"format": "png", "alpha": "premultipliedColor", "matte": 7}), json!({"format": "png", "alpha": "premultipliedColor", "matte": "00ff00"}), json!({"format": "png", "alpha": "premultipliedColor", "matte": "#00ff0080"}), From 71c718f8b77d67723d8b40a5ee71bacab7b2a47c Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:50:26 +0100 Subject: [PATCH 4/4] Render Video alpha: refuse unreadable scratch tiles, resolve PNG as the encoder does (#14163) A PNG frame is flattened for its Alpha Channel choice before the export pipeline's scratch check, which then saw only the matted copy: a failed source read could be written as placeholder pixels. Guard the source frame with Artboards to Files' ScratchGuard across the flatten. The PNG check compared the literal "png", so ".png" (which the encoder writes as PNG) skipped the option; resolve the format as io does. --- crates/engine-core/src/cmd/artboard_cmds.rs | 15 ++-- crates/engine-core/src/cmd/video_cmds.rs | 14 ++- .../video_cmds/render_video_alpha_tests.rs | 12 +++ crates/engine/tests/global_state/main.rs | 1 + .../global_state/render_video_scratch.rs | 89 +++++++++++++++++++ 5 files changed, 121 insertions(+), 10 deletions(-) create mode 100644 crates/engine/tests/global_state/render_video_scratch.rs diff --git a/crates/engine-core/src/cmd/artboard_cmds.rs b/crates/engine-core/src/cmd/artboard_cmds.rs index ccc46b1d4d..b1f7be2dc7 100644 --- a/crates/engine-core/src/cmd/artboard_cmds.rs +++ b/crates/engine-core/src/cmd/artboard_cmds.rs @@ -1089,17 +1089,18 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result { Ok(json!({"files": files, "warnings": warnings})) } -/// The scratch state an artboard export starts from. Building the boards copies their pixels -/// (and the PNG-8 and PDF paths flatten them) before the encoder's own scratch check sees them, -/// and a tile that fails to read gives placeholder pixels: [`ScratchGuard::check`] refuses them -/// before a file is written, as the export pipeline does for a document it reads itself. -struct ScratchGuard<'a> { +/// The scratch state an export starts from. Building artboards copies their pixels (and the +/// PNG-8 and PDF paths flatten them), as Render Video's PNG frames are flattened, before the +/// encoder's own scratch check sees them, and a tile that fails to read gives placeholder pixels: +/// [`ScratchGuard::check`] refuses them before a file is written, as the export pipeline does for +/// a document it reads itself. +pub(crate) struct ScratchGuard<'a> { doc: &'a Document, generation: u64, } impl<'a> ScratchGuard<'a> { - fn new(doc: &'a Document) -> Result { + pub(crate) fn new(doc: &'a Document) -> Result { photocraft_compose::discard_unreadable_pixel_caches(); doc.scratch_health().map_err(EngineError::Other)?; Ok(Self { doc, generation: photocraft_raster::spill::read_error_generation() }) @@ -1107,7 +1108,7 @@ impl<'a> ScratchGuard<'a> { /// An error when a scratch read failed since [`ScratchGuard::new`], or the document's own /// pixels are unreadable. - fn check(&self) -> Result<()> { + pub(crate) fn check(&self) -> Result<()> { photocraft_raster::spill::check_since(self.generation).and_then(|()| self.doc.scratch_health()).map_err(EngineError::Other) } } diff --git a/crates/engine-core/src/cmd/video_cmds.rs b/crates/engine-core/src/cmd/video_cmds.rs index c9cf6fd622..2d9e809582 100644 --- a/crates/engine-core/src/cmd/video_cmds.rs +++ b/crates/engine-core/src/cmd/video_cmds.rs @@ -722,8 +722,11 @@ pub fn render_video_with( // Image sequence. // PSD / PSB frames would embed the files linked smart objects name: not for a restricted session. let opts = photocraft_io::ExportOptions { read_linked_files: s.authorize.is_none(), ..Default::default() }; - // Only a PNG sequence can hold the alpha the option chooses; other formats ignore it. - let alpha = format.eq_ignore_ascii_case("png").then_some(alpha); + // Only a PNG sequence can hold the alpha the option chooses; other formats ignore it. The + // format is resolved as the encoder resolves it, so ".png" and "PNG" are PNG too. + let ext = format.rsplit(['.', '/', '\\']).next().unwrap_or(format); + let png = photocraft_formats::from_extension(ext).and_then(photocraft_formats::Format::raster_codec) == Some(photocraft_codecs::Format::Png); + let alpha = png.then_some(alpha); let mut files = Vec::new(); for f in 0..frames { let mut doc = base.clone(); @@ -732,7 +735,12 @@ pub fn render_video_with( } sync(&mut doc); if let Some(alpha) = alpha { - doc = matted_frame(&doc, alpha)?; + // The frame is flattened here, before the export pipeline's scratch check, which then + // sees only the matted copy: refuse placeholder pixels from a failed read ourselves. + let guard = crate::artboard_cmds::ScratchGuard::new(&doc)?; + let matted = matted_frame(&doc, alpha)?; + guard.check()?; + doc = matted; } let path = format!("{stem}_{f:04}.{format}"); let bytes = photocraft_io::export(&doc, format, &opts).map(|r| r.bytes).map_err(|e| EngineError::Other(format!("render frame {f}: {e}")))?; diff --git a/crates/engine-core/src/cmd/video_cmds/render_video_alpha_tests.rs b/crates/engine-core/src/cmd/video_cmds/render_video_alpha_tests.rs index dc3661b12c..9912bc9903 100644 --- a/crates/engine-core/src/cmd/video_cmds/render_video_alpha_tests.rs +++ b/crates/engine-core/src/cmd/video_cmds/render_video_alpha_tests.rs @@ -104,6 +104,18 @@ fn an_opaque_document_writes_rgb_for_every_choice() { } } +/// The encoder reads ".png" and "PNG" as PNG, so the choice applies to every spelling of it. +#[test] +fn every_spelling_of_png_takes_the_choice() { + let s = half_red(8, false); + for format in ["png", ".png", "PNG", ".PNG"] { + let img = render(&s, json!({"format": format, "alpha": "premultipliedColor", "matte": "#00ff00"})); + assert_eq!(px(&img, 3, 1), [0, 255, 0, 0], "{format}: the matte fills the transparent pixel"); + let img = render(&s, json!({"format": format})); + assert_eq!(px(&img, 3, 1), [0, 0, 0], "{format}: no alpha by default"); + } +} + #[test] fn formats_without_the_option_keep_their_transparency() { let s = half_red(8, false); diff --git a/crates/engine/tests/global_state/main.rs b/crates/engine/tests/global_state/main.rs index 4f3d3b7438..741a80a112 100644 --- a/crates/engine/tests/global_state/main.rs +++ b/crates/engine/tests/global_state/main.rs @@ -7,6 +7,7 @@ mod color_settings_presets; mod lut_row_cache_purge; mod mask_cache_purge; mod memory_gate; +mod render_video_scratch; mod scratch_disk; mod scratch_pause; mod scratch_release; diff --git a/crates/engine/tests/global_state/render_video_scratch.rs b/crates/engine/tests/global_state/render_video_scratch.rs new file mode 100644 index 0000000000..861a1f1a18 --- /dev/null +++ b/crates/engine/tests/global_state/render_video_scratch.rs @@ -0,0 +1,89 @@ +//! Render Video never writes a frame whose scratch tiles can't be read (#14163): a PNG sequence +//! flattens each frame for its Alpha Channel choice before the checked export pipeline sees it, so +//! the placeholder pixels a failed read gives would otherwise be encoded as real pixels. +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_doc::{Document, Layer}; +use photocraft_engine::Session; +use photocraft_geom::{Size, TileCoord}; +use photocraft_raster::spill; +use serde_json::{Value, json}; +use std::io::{Read, Seek, SeekFrom, Write}; + +/// How many frames Render Video handed its writer for `params`, and whether it succeeded. +fn render(session: &Session, params: &Value) -> (usize, bool) { + let mut written = 0; + let r = photocraft_engine::render_video_with( + session, + params, + |_, _| { + written += 1; + Ok(()) + }, + |_, _| true, + ); + (written, r.is_ok()) +} + +#[test] +fn render_video_refuses_unreadable_scratch_tiles() { + photocraft_raster::spill::use_test_volume_space(); + let _scratch = crate::lock(&crate::PROCESS); + let scratch = std::env::temp_dir().join(format!("photocraft-render-video-scratch-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&scratch); + let mut session = Session::new(); + session.edit_prefs(|p| { + p.scratch_disks.disks = vec![photocraft_engine::prefs::ScratchDisk { path: scratch.to_string_lossy().into(), enabled: true }]; + p.performance.memory_usage_mb = 1; + }); + assert!(spill::enabled()); + let mut doc = Document::new("Scratch frames", Size::new(2048, 256), ColorMode::Rgb, SampleType::U8); + let mut pixels = Layer::raster("Pixels", PixelFormat::RGBA8); + for i in 0..8 { + let mut bytes = pixels.surface_mut().unwrap().tile_mut(TileCoord::new(i, 0)).bytes_mut(); + for (j, b) in bytes.iter_mut().enumerate() { + *b = (j as u32).wrapping_mul(17).wrapping_add(i as u32 * 43) as u8; + } + } + doc.layers.push(pixels); + session.add_document(doc, None); + // The default (no alpha), an alpha choice and its ".png" spelling flatten the frame first; JPEG + // goes straight to the export pipeline. + let cases = [ + json!({"format": "png"}), + json!({"format": "png", "alpha": "straight"}), + json!({"format": ".png", "alpha": "premultipliedColor", "matte": "#00ff00"}), + json!({"format": "jpg"}), + ]; + for params in &cases { + assert_eq!(render(&session, params), (1, true), "{params} with readable tiles"); + } + + // Force every tile to disk, then damage only this test's scratch file, as + // `artboard_export_scratch` does (see there for why the budget is set again until it holds). + for _ in 0..20 { + spill::configure(Some(&scratch), 1).unwrap(); + spill::settle(); + if spill::stats().resident_bytes == 0 { + break; + } + } + assert_eq!(spill::stats().resident_bytes, 0); + let mut file = spill::scratch_handle_for_tests().unwrap(); + file.seek(SeekFrom::Start(0)).unwrap(); + let mut good = Vec::new(); + file.read_to_end(&mut good).unwrap(); + file.seek(SeekFrom::Start(0)).unwrap(); + file.write_all(&vec![0; good.len()]).unwrap(); + file.sync_all().unwrap(); + + for params in &cases { + assert_eq!(render(&session, params), (0, false), "{params} wrote a frame with unreadable tiles"); + } + + file.seek(SeekFrom::Start(0)).unwrap(); + file.write_all(&good).unwrap(); + file.sync_all().unwrap(); + drop((session, file)); + spill::configure(None, 0).unwrap(); + let _ = std::fs::remove_dir_all(scratch); +}