Merge #16651 into the merge queue batch

Render Video: Alpha Channel option for PNG sequences (#14163)
This commit is contained in:
David Mann committed 2026-11-25 17:31:40 +01:00
commit 92a7f23f42
5 files changed
+344 -8

No files matched your search

+8 -7
View File
@@ -1112,17 +1112,18 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result<Value> {
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<Self> {
pub(crate) fn new(doc: &'a Document) -> Result<Self> {
photocraft_compose::discard_unreadable_pixel_caches();
doc.scratch_health().map_err(EngineError::Other)?;
Ok(Self { doc, generation: photocraft_raster::spill::read_error_generation() })
@@ -1130,7 +1131,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)
}
}
+101 -1
View File
@@ -665,6 +665,7 @@ pub fn render_video_with(
) -> Result<Value> {
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,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. 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();
@@ -728,6 +734,14 @@ pub fn render_video_with(
t.current = f;
}
sync(&mut doc);
if let Some(alpha) = 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}")))?;
write(&path, &bytes)?;
@@ -739,6 +753,85 @@ 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: the colours are composited over black, so transparent areas are black.
None,
/// 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.
fn render_alpha(p: &Value) -> Result<RenderAlpha> {
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],
// `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) {
*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" | "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")),
}
}
/// `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<Document> {
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 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) {
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::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);
}
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 +874,16 @@ pub fn specs() -> Vec<CommandSpec> {
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;
@@ -0,0 +1,145 @@
//! Render Video's Alpha Channel option for image sequences (#14163).
use photocraft_codecs::{ChannelLayout, Image, SampleType};
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,
&params,
|_, 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<u32> {
(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");
}
}
}
/// 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);
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");
}
}
/// 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);
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": [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"}),
json!({"format": "gif", "alpha": "matte"}),
] {
let r = render_video_with(&s, &params, |_, _| Ok(()), |_, _| true);
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{params}: {r:?}");
}
}
+1
View File
@@ -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;
@@ -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);
}