diff --git a/Cargo.lock b/Cargo.lock index eee4fa3a0..1caddc14d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -617,6 +617,19 @@ dependencies = [ "no_std_io2", ] +[[package]] +name = "blake3" +version = "1.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "cpufeatures 0.3.1", +] + [[package]] name = "block" version = "0.1.6" @@ -1143,6 +1156,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + [[package]] name = "cookie-factory" version = "0.3.3" @@ -1406,10 +1425,12 @@ name = "craft-doc" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ + "blake3", "craft-ecproj-format", "craft-pcraft-format", "craft-vectorcraft-format", "flate2", + "ruzstd", "serde", "serde_json", "thiserror 2.0.21", @@ -2552,6 +2573,7 @@ name = "effectcraft-engine" version = "0.25.1" dependencies = [ "chrono", + "craft-doc", "craft-docpath", "effectcraft-aep", "effectcraft-color", @@ -2560,6 +2582,7 @@ dependencies = [ "effectcraft-interchange", "effectcraft-keyframe", "effectcraft-lottie", + "effectcraft-media", "effectcraft-model", "effectcraft-path", "effectcraft-pdf", @@ -2759,6 +2782,7 @@ version = "0.25.1" dependencies = [ "craft-audio", "craft-color", + "craft-doc", "craft-docpath", "craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21)", "craft-exr 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21)", @@ -7024,6 +7048,12 @@ dependencies = [ "wait-timeout", ] +[[package]] +name = "ruzstd" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69e4ce4a039f42bf25920b95667e4d789e98749ab11bbb8d2c2936f788421bb5" + [[package]] name = "ryu" version = "1.0.23" diff --git a/README.md b/README.md index ec18dde21..4ebf96f5b 100644 --- a/README.md +++ b/README.md @@ -217,7 +217,8 @@ cargo run --release -p effectcraft-cli -- render --out intro.mp4 # render the cargo xtask web --serve 8765 # the browser build on http://127.0.0.1:8765/ (docs/web.md) ``` -New to it? [docs/footage.md](docs/footage.md) covers importing footage and image sequences and +New to it? [docs/photocraft-import.md](docs/photocraft-import.md) describes PhotoCraft composites and saved layer pixels. +[docs/footage.md](docs/footage.md) covers importing footage and image sequences and Interpret Footage. To work on it: `cargo test --workspace`, and the checks for the crates you changed (`cargo xtask ci --affected`; the full `cargo xtask ci` covers format, lints, diff --git a/apps/effectcraft-web/src/files.rs b/apps/effectcraft-web/src/files.rs index f6aac5aa4..d33db6542 100644 --- a/apps/effectcraft-web/src/files.rs +++ b/apps/effectcraft-web/src/files.rs @@ -117,6 +117,15 @@ impl Services for WebServices { .map(|d| d.to_vec()) .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, format!("{path}: open it with File ▸ Open (or drop it on the page)"))) } + /// Checks the size before copying the stored bytes. + fn read_pcraft(&self, path: &str) -> std::io::Result> { + let data = + get(path).ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, format!("{path}: open it with File ▸ Open (or drop it on the page)")))?; + if data.len() as u64 > effectcraft_engine::PCRAFT_MAX_INPUT { + return Err(effectcraft_engine::pcraft_too_large()); + } + Ok(data.to_vec()) + } fn write_file(&self, path: &str, data: &[u8]) -> std::io::Result<()> { put(path, data.into()); let quiet = { diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index cd85c858d..14ea5e8a2 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -10,6 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] +craft-doc = { workspace = true } craft-docpath = { workspace = true } effectcraft-time = { workspace = true } effectcraft-geom = { workspace = true } @@ -41,6 +42,9 @@ image = { workspace = true } web-time = { workspace = true } exr = { workspace = true } +[dev-dependencies] +effectcraft-media = { workspace = true } + # Native file identity and SAM 2 inference; browsers keep the built-in engines. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] memory-stats = { workspace = true } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index af3942f64..72a2510a6 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -144,6 +144,20 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result { }; let p = p.clone(); let immediate_errors = pending.errors.clone(); + // Compositions made during preparation stay when the job is canceled, so their notes are + // shown now and returned in both results. The window keeps one notice at a time and shows + // its first line, so they go in one notice led by a summary, and the finished job's toast + // repeats them. + let immediate_warnings = std::mem::take(&mut pending.warnings); + let notes = match immediate_warnings.as_slice() { + [] => String::new(), + [one] => one.clone(), + [first, rest @ ..] => format!("{first} (and {} more)\n{}", rest.len(), immediate_warnings.join("\n")), + }; + if !notes.is_empty() { + s.events.push(crate::Event::Toast { message: notes.clone(), error: false }); + } + let job_warnings = immediate_warnings.clone(); let mut result = s.spawn_task("import", label, false, move |ctl| { let mut probed = Vec::with_capacity(total); for (k, src) in sources.iter().enumerate() { @@ -157,6 +171,9 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result { let apply: crate::jobs::Apply = Box::new(move |s: &mut Session| { let made = pending.comps.len() + probed.iter().filter(|r| r.is_ok()).count(); let mut r = add_footage(s, pending, probed)?; + if let Some(w) = r.get_mut("warnings").and_then(Value::as_array_mut) { + w.splice(0..0, job_warnings.into_iter().map(Value::from)); + } finish_import(s, &mut r, target, &p); let mut toast = format!("Imported {made} item{}", if made == 1 { "" } else { "s" }); let errors: Vec<&str> = r["errors"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); @@ -165,6 +182,9 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result { [one] => toast = format!("{toast}. {one}"), [first, rest @ ..] => toast = format!("{toast}. {first} (and {} more)\n{}", rest.len(), errors.join("\n")), } + if !notes.is_empty() { + toast = if errors.is_empty() { format!("{toast}. {notes}") } else { format!("{toast}\n{notes}") }; + } r["toast"] = json!(toast); Ok(r) }); @@ -174,6 +194,7 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result { // Report those failures now as well as in the eventual job result. if result["started"] == true { result["errors"] = json!(immediate_errors); + result["warnings"] = json!(immediate_warnings); } return Ok(result); } @@ -281,6 +302,8 @@ struct PendingImport { comps: Vec, items: Vec, errors: Vec, + /// Notes about compositions that imported, such as what a PhotoCraft composition leaves out. + warnings: Vec, /// EffectCraft projects merged in (`file.importProject` results); never added to a comp. projects: Vec, } @@ -331,6 +354,17 @@ impl Prober { Source::File(_) => importer.probe_noting(path).map_err(fail)?, _ => (crate::sequence::probe(importer.as_ref(), src, self.sequence_rate).map_err(fail)?, None), }; + // The composite has already probed successfully. Optional canvas metadata must + // not prevent Footage import when its read or outline exceeds another limit. + if f.codec == "PhotoCraft" + && let Ok(bytes) = self.services.read_pcraft(path) + && let Ok(outline) = craft_doc::outline(&bytes, &craft_doc::Limits::default()) + && let Some(canvas) = outline.canvas + && (canvas.width, canvas.height) != (f.width, f.height) + { + warning = + Some(format!("{name}: imported the saved {} × {} composite of a {} × {} PhotoCraft canvas", f.width, f.height, canvas.width, canvas.height)); + } // Settings ▸ Import ▸ Report Missing Frames (numbered sequences). if f.kind == FootageKind::Sequence && !f.alphabetical @@ -416,6 +450,7 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result { let mut comps = vec![]; let mut items = vec![]; let mut errors = vec![]; + let mut warnings = vec![]; // EffectCraft projects import as projects, as After Effects imports an .aep; so do After // Effects projects, refused when parts of them cannot come over. The app asks about those // before it gets here (`panels::aep_losses`); a script or agent gets the refusal. @@ -442,7 +477,22 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result { if let Some(retain) = retain { let mut rest = vec![]; for path in paths { - let bytes = match s.services.read_file(&path) { + // Only PhotoCraft reads have the input limit; a renamed bundle is checked after its + // read, before it is parsed. + let pcraft = path.to_ascii_lowercase().ends_with(".pcraft"); + let read = if pcraft { s.services.read_pcraft(&path) } else { s.services.read_file(&path) }; + let bytes = match read { + Ok(b) if pcraft || craft_doc::sniff(&b) == Some(craft_doc::Kind::PhotoCraft) => { + match import_pcraft_comp(s, &path, &b, retain) { + Ok((comp, made, notes)) => { + comps.push(comp); + items.extend(made); + warnings.extend(notes); + } + Err(e) => errors.push(format!("{path}: {e}")), + } + continue; + } Ok(b) if effectcraft_psd::is_psd(&b) => b, Ok(b) if effectcraft_pdf::sniff(&b).is_some() && !path.to_ascii_lowercase().ends_with(".svg") => { // PDF / Illustrator / EPS: one layer per file layer. @@ -455,6 +505,10 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result { } continue; } + Err(e) if pcraft => { + errors.push(format!("{path}: {e}")); + continue; + } _ => { rest.push(path); continue; @@ -496,15 +550,14 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result { page, psd_layer: p.get("layer").cloned(), }; - Ok(PendingImport { sources, prober, comps, items, errors, projects }) + Ok(PendingImport { sources, prober, comps, items, errors, warnings, projects }) } /// The last part of an import: add the probed files to the project (one undo step) and select /// everything the import made, so the Project panel shows it. fn add_footage(s: &mut Session, pending: PendingImport, probed: Vec>) -> Result { - let PendingImport { comps, mut items, mut errors, projects, .. } = pending; + let PendingImport { comps, mut items, mut errors, mut warnings, projects, .. } = pending; let mut found = vec![]; - let mut warnings = vec![]; for r in probed { match r { Ok(f) => { @@ -571,8 +624,26 @@ fn add_footage(s: &mut Session, pending: PendingImport, probed: Vec bool { let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); - matches!(ext.as_str(), "png" | "gif" | "webp" | "psd" | "psb" | "exr" | "svg" | "jpg" | "jpeg" | "ai" | "pdf" | "eps" | "vectorcraft") + matches!(ext.as_str(), "png" | "gif" | "webp" | "psd" | "psb" | "pcraft" | "exr" | "svg" | "jpg" | "jpeg" | "ai" | "pdf" | "eps" | "vectorcraft") || codec.eq_ignore_ascii_case("PSD") + || codec == "PhotoCraft" +} + +fn import_pcraft_comp(s: &mut Session, path: &str, bytes: &[u8], retain: bool) -> Result<(u64, Vec, Vec)> { + use crate::interchange::pcraft_import; + let doc = pcraft_import::read(bytes).map_err(EngineError::Other)?; + let name = std::path::Path::new(path).file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "PhotoCraft".into()); + let rate = effectcraft_time::FrameRate::FPS_29_97; + let secs = if s.prefs.import.still_footage == "seconds" { s.prefs.import.still_seconds } else { 10.0 }; + let duration = rate.snap_nearest(effectcraft_time::Tick::from_seconds_f64(secs)); + let r = s.edit("Import", None, |project, state| { + let r = pcraft_import::import(project, &doc, path, &name, retain, rate, duration); + state.project_selection = vec![r.comp]; + Ok(r) + })?; + let mut items = vec![r.folder.0]; + items.extend(r.items.iter().map(|id| id.0)); + Ok((r.comp.0, items, r.warnings)) } /// A Photoshop layer by index or name (pixel layers only). @@ -812,7 +883,7 @@ pub fn specs() -> Vec { "File...", ["File", "Import"], Some("Cmd+I"), - "{paths: [string] (files or folders), sequence?: bool (the Sequence checkbox: true imports numbered stills of one run as one image sequence, one picked file bringing its whole run and several picked files that range; default false: picked or dropped files import as stills, as in After Effects; folders' runs import as sequences; false imports stills and a folder's files individually), alphabetical?: bool (Force Alphabetical Order: every image of that type in the folder, by name), frameRate?: fps (image sequences; default Settings ▸ Import ▸ Sequence Footage), importAs?: footage|composition|compositionLayerSizes (Photoshop, PDF, Illustrator and EPS files), layer?: name|index (footage of one Photoshop layer), page?: number from 1 (PDF / Illustrator page), drag?: bool (dropped files: Settings ▸ Import ▸ Default Drag Import As; files import as stills unless sequence), addToComp?: bool (also add them to the active comp, at time?, index?, position? as in layer.addItem), newComp?: bool (make one new composition of the footage and solids imported, as file.newCompFromSelection with single; a layered file imported as a composition is that composition and gets no other; takes precedence over addToComp), background?: bool (probe the files in a background job, jobs.list / jobs.wait; returns {job})}", + "{paths: [string] (files or folders), sequence?: bool (the Sequence checkbox: true imports numbered stills of one run as one image sequence, one picked file bringing its whole run and several picked files that range; default false: picked or dropped files import as stills, as in After Effects; folders' runs import as sequences; false imports stills and a folder's files individually), alphabetical?: bool (Force Alphabetical Order: every image of that type in the folder, by name), frameRate?: fps (image sequences; default Settings ▸ Import ▸ Sequence Footage), importAs?: footage|composition|compositionLayerSizes (Photoshop, PhotoCraft, PDF, Illustrator and EPS files), layer?: name|index (footage of one Photoshop layer), page?: number from 1 (PDF / Illustrator page), drag?: bool (dropped files: Settings ▸ Import ▸ Default Drag Import As; files import as stills unless sequence), addToComp?: bool (also add them to the active comp, at time?, index?, position? as in layer.addItem), newComp?: bool (make one new composition of the footage and solids imported, as file.newCompFromSelection with single; a layered file imported as a composition is that composition and gets no other; takes precedence over addToComp), background?: bool (probe the files in a background job, jobs.list / jobs.wait; returns {job})}", always, import_cmd ), diff --git a/crates/engine/src/footage/media_browser.rs b/crates/engine/src/footage/media_browser.rs index bd125ad7a..a5a97259a 100644 --- a/crates/engine/src/footage/media_browser.rs +++ b/crates/engine/src/footage/media_browser.rs @@ -197,7 +197,7 @@ fn sort_entries(entries: &mut [Entry]) { entries.sort_by_cached_key(|e| (!e.is_dir, e.name.to_lowercase())); } -const IMAGE: &[&str] = &["png", "jpg", "jpeg", "tif", "tiff", "exr", "bmp", "webp", "psd", "psb", "svg", "tga", "dpx", "cin", "hdr", "vectorcraft"]; +const IMAGE: &[&str] = &["png", "jpg", "jpeg", "tif", "tiff", "exr", "bmp", "webp", "psd", "psb", "pcraft", "svg", "tga", "dpx", "cin", "hdr", "vectorcraft"]; const AUDIO: &[&str] = &["wav", "aif", "aiff", "mp3", "m4a", "aac", "flac", "ogg", "opus"]; const DATA: &[&str] = &["json", "csv", "tsv", "mgjson"]; const MODEL: &[&str] = &["gltf", "glb", "obj", "stl", "fbx"]; diff --git a/crates/engine/src/footage/sequence.rs b/crates/engine/src/footage/sequence.rs index 0d4c33453..12232312b 100644 --- a/crates/engine/src/footage/sequence.rs +++ b/crates/engine/src/footage/sequence.rs @@ -99,7 +99,7 @@ fn extension(path: &str) -> String { /// Stills that can form a sequence (not layered or vector documents, which import as comps). fn sequenceable(path: &str) -> bool { - crate::media_browser::kind_of(path) == Some("image") && !matches!(extension(path).as_str(), "svg" | "psd" | "psb" | "vectorcraft") + crate::media_browser::kind_of(path) == Some("image") && !matches!(extension(path).as_str(), "svg" | "psd" | "psb" | "pcraft" | "vectorcraft") } /// The run a still belongs to: (folder, name prefix, extension); alphabetical runs ignore the diff --git a/crates/engine/src/interchange.rs b/crates/engine/src/interchange.rs index 3b166b83e..a83090159 100644 --- a/crates/engine/src/interchange.rs +++ b/crates/engine/src/interchange.rs @@ -1,5 +1,6 @@ pub(crate) mod keyframe_text; pub(crate) mod keyframe_text_effects; +pub(crate) mod pcraft_import; pub mod psd_import; pub mod vector; pub mod xml_project; diff --git a/crates/engine/src/interchange/pcraft_import.rs b/crates/engine/src/interchange/pcraft_import.rs new file mode 100644 index 000000000..0f86d2557 --- /dev/null +++ b/crates/engine/src/interchange/pcraft_import.rs @@ -0,0 +1,178 @@ +//! PhotoCraft's layer outline as a composition of lazily decoded, canvas-sized pixel layers. + +use std::sync::Arc; + +use craft_doc::{Layer as InputLayer, Outline}; +use effectcraft_color::{BlendMode, Label}; +use effectcraft_keyframe::Value; +use effectcraft_project::{AlphaMode, Comp, Footage, FootageKind, ItemId, ItemKind, LayerSource, Project, SourceLayer, build}; +use effectcraft_time::{FrameRate, Tick}; + +// Each source group becomes a precomposition; match the renderer's nesting limit. +const MAX_GROUP_DEPTH: usize = 16; + +/// A group whose blend mode is Pass Through: it becomes a precomposition with Collapse +/// Transformations on, so its layers blend with the layers below the group. +fn passes_through(layer: &InputLayer) -> bool { + layer.kind == "group" && layer.blend.as_deref().is_some_and(|b| b.eq_ignore_ascii_case("PassThrough") || b.eq_ignore_ascii_case("Pass Through")) +} + +pub(crate) struct Document { + outline: Outline, + width: u32, + height: u32, +} + +/// Metadata only: source pixels remain media and are decoded when a frame needs them, as PSD +/// footage is. Bound the number of project items before creating their property groups. +pub(crate) fn read(bytes: &[u8]) -> Result { + if bytes.len() as u64 > effectcraft_project::PCRAFT_MAX_INPUT { + return Err("PhotoCraft bundle exceeds the 512 MiB input limit".into()); + } + fn count(layers: &[InputLayer], depth: usize, nodes: &mut usize, pixels: &mut usize) -> Result<(), String> { + if depth > MAX_GROUP_DEPTH { + return Err("PhotoCraft groups exceed 16 levels; import as Footage for the saved composite".into()); + } + for layer in layers { + if depth == MAX_GROUP_DEPTH && layer.kind == "group" { + return Err("PhotoCraft groups exceed 16 levels; import as Footage for the saved composite".into()); + } + // A pass-through group collapses into its parent only this deep in the renderer. + if depth > effectcraft_render::MAX_COLLAPSE_DEPTH && passes_through(layer) { + return Err("PhotoCraft pass-through groups exceed 13 levels; import as Footage for the saved composite".into()); + } + *nodes += 1; + if *nodes > 4096 { + return Err("PhotoCraft composition import exceeds 4096 layers; import as Footage for the saved composite".into()); + } + if matches!(layer.kind.as_str(), "raster" | "text" | "shape" | "smart") { + *pixels += 1; + } + if !layer.children.is_empty() { + if layer.kind != "group" { + return Err(format!("PhotoCraft {} layer has unsupported nested content", layer.kind)); + } + count(&layer.children, depth + 1, nodes, pixels)?; + } + } + Ok(()) + } + let outline = craft_doc::outline(bytes, &craft_doc::Limits::default()).map_err(|e| e.to_string())?; + let canvas = outline.canvas.as_ref().ok_or("not a PhotoCraft canvas")?; + let (width, height) = (canvas.width, canvas.height); + if width == 0 || height == 0 || width > effectcraft_project::limits::MAX_SIZE || height > effectcraft_project::limits::MAX_SIZE { + return Err(format!("PhotoCraft canvas {width} × {height} is outside the composition size limits")); + } + if u64::from(width) * u64::from(height) > 12 << 20 { + return Err( + "PhotoCraft layer decoding exceeds the 1 GiB working-buffer budget (12582912 canvas pixels); import as Footage for the saved composite".into() + ); + } + if matches!(canvas.mode.as_str(), "Cmyk" | "Lab") { + return Err(format!("PhotoCraft {} layer pixels are not supported; import as Footage for the saved composite", canvas.mode)); + } + let (mut nodes, mut pixels) = (0, 0); + count(&outline.layers, 0, &mut nodes, &mut pixels)?; + if nodes != 0 && pixels == 0 { + return Err("PhotoCraft document has no supported saved pixel layers; import as Footage for the saved composite".into()); + } + Ok(Document { outline, width, height }) +} + +pub(crate) struct Imported { + pub comp: ItemId, + pub folder: ItemId, + pub items: Vec, + pub warnings: Vec, +} + +struct Context<'a> { + doc: &'a Document, + path: &'a str, + folder: ItemId, + rate: FrameRate, + duration: Tick, + next: u32, + items: Vec, + warnings: Vec, +} + +pub(crate) fn import(project: &mut Project, doc: &Document, path: &str, name: &str, retain: bool, rate: FrameRate, duration: Tick) -> Imported { + let folder = project.add_item(&format!("{name} Layers"), Label::Yellow, None, ItemKind::Folder); + let mut ctx = Context { + doc, + path, + folder, + rate, + duration, + next: 0, + items: Vec::new(), + warnings: vec![ + "Layered PhotoCraft import uses saved pixels. Some masks, effects and profiles are unsupported; use Footage for the saved appearance.".into(), + ], + }; + if retain { + ctx.warnings.push("PhotoCraft layer footage uses the document canvas; Retain Layer Sizes keeps those canvas bounds.".into()); + } + let comp = build_comp(project, &mut ctx, name, &doc.outline.layers, None, 0); + Imported { comp, folder, items: ctx.items, warnings: ctx.warnings } +} + +fn build_comp(project: &mut Project, ctx: &mut Context, name: &str, layers: &[InputLayer], parent: Option, depth: usize) -> ItemId { + let mut comp = Comp::new(ctx.doc.width, ctx.doc.height, ctx.rate, ctx.duration); + let id = project.add_item(name, Label::Sandstone, parent, ItemKind::Comp(Arc::new(comp.clone()))); + ctx.items.push(id); + if depth <= MAX_GROUP_DEPTH { + for input in layers { + let index = ctx.next; + ctx.next = ctx.next.saturating_add(1); + let name = if input.name.is_empty() { format!("Layer {}", index + 1) } else { input.name.clone() }; + let source = if input.kind == "group" { + let folder = ctx.folder; + let sub = build_comp(project, ctx, &name, &input.children, Some(folder), depth + 1); + LayerSource::Comp { item: sub } + } else if matches!(input.kind.as_str(), "raster" | "text" | "shape" | "smart") { + let file = std::path::Path::new(ctx.path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let footage = Footage { + path: ctx.path.into(), + kind: FootageKind::Still, + width: ctx.doc.width, + height: ctx.doc.height, + has_video: true, + alpha: AlphaMode::Straight, + codec: "PhotoCraft".into(), + layer: Some(SourceLayer { index, name: name.clone(), layer_size: false, embedded: None, placed: false }), + ..Default::default() + }; + let item = project.add_item(&format!("{name}/{file}"), Label::Lavender, Some(ctx.folder), ItemKind::Footage(footage)); + ctx.items.push(item); + LayerSource::Footage { item } + } else { + ctx.warnings.push(format!("{name}: PhotoCraft {} content has no supported saved pixels and was skipped", input.kind)); + continue; + }; + let mut layer = build::layer(project, &comp, &name, source, (ctx.doc.width, ctx.doc.height), None); + layer.switches.video = input.visible; + if let Some(opacity) = layer.props.prop_mut("transform/opacity") { + opacity.value = Value::Scalar(f64::from(input.opacity.filter(|v| v.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0)) * 100.0); + } + if let Some(blend) = input.blend.as_deref() { + if passes_through(input) { + layer.switches.collapse = true; + } else if let Some(mode) = BlendMode::from_name(blend) { + layer.blend_mode = mode; + } else { + ctx.warnings.push(format!("{name}: PhotoCraft blend mode {blend} is not supported; using Normal")); + } + } + comp.layers.push(layer); + } + } + // PhotoCraft stores bottom first; EffectCraft stores the top layer first. Reverse + // after visiting the source so preorder pixel indexes still address the original tree. + comp.layers.reverse(); + if let Some(item) = project.item_mut(id) { + item.kind = ItemKind::Comp(Arc::new(comp)); + } + id +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 14a76bc1e..66ca04c13 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -98,7 +98,7 @@ pub use doc_state::{CompSelection, EditorState, KeyClip, KeyMove, KeyRef, LinkCl pub use error::{EngineError, Result}; pub use event::Event; pub use fonts::{FontRow, font_features, font_menu, font_preview, font_styles, text_families}; -pub use services::{FsServices, Importer, Services}; +pub use services::{FsServices, Importer, PCRAFT_MAX_INPUT, Services, pcraft_too_large}; pub use session::upgrade_effects; pub struct Session { diff --git a/crates/engine/src/services.rs b/crates/engine/src/services.rs index fe95f5300..ebbe4c3d4 100644 --- a/crates/engine/src/services.rs +++ b/crates/engine/src/services.rs @@ -1,8 +1,28 @@ use super::config; +/// The largest PhotoCraft bundle [`Services::read_pcraft`] reads. +pub use effectcraft_project::PCRAFT_MAX_INPUT; + +/// The error for a PhotoCraft bundle over [`PCRAFT_MAX_INPUT`]. +pub fn pcraft_too_large() -> std::io::Error { + std::io::Error::new(std::io::ErrorKind::InvalidData, "PhotoCraft bundle exceeds the 512 MiB input limit") +} + /// Host services (file access) injected by the frontend. pub trait Services: Send + Sync { fn read_file(&self, path: &str) -> std::io::Result>; + /// A PhotoCraft bundle's bytes: like [`Services::read_file`], but a file over + /// [`PCRAFT_MAX_INPUT`] is an error. Other files read with `read_file` have no such limit. + fn read_pcraft(&self, path: &str) -> std::io::Result> { + if self.stamp(path).is_some_and(|(len, _)| len > PCRAFT_MAX_INPUT) { + return Err(pcraft_too_large()); + } + let bytes = self.read_file(path)?; + if bytes.len() as u64 > PCRAFT_MAX_INPUT { + return Err(pcraft_too_large()); + } + Ok(bytes) + } /// [`Services::read_file`] for a copy that must not load an unbounded file: more than `max` /// bytes is an error. The native one opens the file once, reads its size from that handle and /// reads through a [`std::io::Read::take`] limit, so a file grown or swapped after the check @@ -64,17 +84,12 @@ impl Services for FsServices { /// Refuses what isn't a regular file: a project can name `/dev/zero` or a FIFO, and reading /// those never ends (#2134). fn read_file(&self, path: &str) -> std::io::Result> { - use std::io::Read; - let mut file = std::fs::File::open(path)?; - let meta = file.metadata()?; - if !meta.is_file() { - return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{path} is not a file"))); - } - let mut bytes = Vec::new(); - // A sparse file can claim far more than memory: an error, not an abort. - bytes.try_reserve_exact(usize::try_from(meta.len()).unwrap_or(usize::MAX)).map_err(|e| std::io::Error::new(std::io::ErrorKind::OutOfMemory, e))?; - file.read_to_end(&mut bytes)?; - Ok(bytes) + read_regular_file(path, None) + } + /// Checks the size before reserving the buffer, and stops reading a file that grows past + /// the limit while it is read. + fn read_pcraft(&self, path: &str) -> std::io::Result> { + read_regular_file(path, Some(PCRAFT_MAX_INPUT)) } fn read_file_bounded(&self, path: &str, max: u64) -> std::io::Result> { use std::io::Read; @@ -101,6 +116,27 @@ impl Services for FsServices { } } +/// A regular file's bytes; with `limit`, a file larger than `limit` bytes is an error. +fn read_regular_file(path: &str, limit: Option) -> std::io::Result> { + use std::io::Read; + let file = std::fs::File::open(path)?; + let meta = file.metadata()?; + if !meta.is_file() { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{path} is not a file"))); + } + if limit.is_some_and(|max| meta.len() > max) { + return Err(pcraft_too_large()); + } + let mut bytes = Vec::new(); + // A sparse file can claim far more than memory: an error, not an abort. + bytes.try_reserve_exact(usize::try_from(meta.len()).unwrap_or(usize::MAX)).map_err(|e| std::io::Error::new(std::io::ErrorKind::OutOfMemory, e))?; + file.take(limit.map_or(u64::MAX, |max| max.saturating_add(1))).read_to_end(&mut bytes)?; + if limit.is_some_and(|max| bytes.len() as u64 > max) { + return Err(pcraft_too_large()); + } + Ok(bytes) +} + /// Imports media files into the project (implemented by the media layer). pub trait Importer: Send + Sync { /// Probe one file and return footage metadata. Image sequences are the engine's @@ -136,6 +172,26 @@ mod tests { let _ = std::fs::remove_file(f); } + /// Templates and dotLottie files are ZIP archives too: only PhotoCraft reads have the + /// 512 MiB input limit. A file over it is refused from its length, which is set without + /// writing the data, so nothing is read; the same read with a smaller limit, and with none, + /// shows where the limit applies. + #[test] + fn only_photocraft_reads_have_the_input_limit() { + let f = std::env::temp_dir().join(format!("ec-services-large-{}.zip", std::process::id())); + std::fs::write(&f, b"PK\x03\x04").unwrap(); + std::fs::OpenOptions::new().write(true).open(&f).unwrap().set_len(super::PCRAFT_MAX_INPUT + 1).unwrap(); + let path = f.to_string_lossy().to_string(); + let error = FsServices.read_pcraft(&path).unwrap_err(); + assert!(error.to_string().contains("512 MiB input limit"), "{error}"); + std::fs::OpenOptions::new().write(true).open(&f).unwrap().set_len(4).unwrap(); + assert_eq!(FsServices.read_file(&path).unwrap(), b"PK\x03\x04"); + assert_eq!(FsServices.read_pcraft(&path).unwrap(), b"PK\x03\x04"); + assert!(super::read_regular_file(&path, Some(3)).is_err(), "one byte over a limit"); + assert_eq!(super::read_regular_file(&path, None).unwrap(), b"PK\x03\x04"); + let _ = std::fs::remove_file(f); + } + /// The limit is inclusive and cannot overflow: `u64::MAX` reads the file, one byte too many /// is an error, and nothing past it is read. #[test] diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 835c4cb6c..729d24582 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24,6 +24,7 @@ mod fidelity; mod frame_export; mod fuzz_open; mod history; +mod import_photocraft; mod import_project; mod instance3d; mod key_metadata_order; diff --git a/crates/engine/src/tests/import_photocraft.rs b/crates/engine/src/tests/import_photocraft.rs new file mode 100644 index 000000000..b135774c5 --- /dev/null +++ b/crates/engine/src/tests/import_photocraft.rs @@ -0,0 +1,386 @@ +//! PhotoCraft bundles written from synthetic manifest data. + +use effectcraft_color::BlendMode; +use effectcraft_project::{ItemId, ItemKind, LayerSource}; +use serde_json::{Value, json}; + +use crate::Session; + +struct Import; + +impl crate::Importer for Import { + fn probe(&self, path: &str) -> Result { + effectcraft_media::probe(path).map_err(|e| e.to_string()) + } +} + +fn surface(color: &str) -> Value { + json!({"format":{"mode":"Rgb","sample":"U8","alpha":true},"default":color,"tiles":[]}) +} + +fn layer(name: &str, visible: bool, opacity: f32, blend: &str, content: Value) -> Value { + json!({"name":name,"visible":visible,"opacity":opacity,"blend":blend,"content":content}) +} + +fn bundle(layers: Value) -> Vec { + bundle_sized(layers, (8, 6)) +} + +fn bundle_sized(layers: Value, size: (u32, u32)) -> Vec { + let manifest = json!({"format_version":1,"generator":"synthetic PhotoCraft fixture", + "document":{"size":{"width":size.0,"height":size.1},"resolution_dpi":72.0,"mode":"Rgb","depth":"U8","layers":layers}, + "thumbnail":null,"composite":"composite/preview.png"}); + let mut png = std::io::Cursor::new(Vec::new()); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(4, 3, image::Rgba([20, 30, 40, 255]))).write_to(&mut png, image::ImageFormat::Png).unwrap(); + effectcraft_lottie::zip::store(&[("manifest.json".into(), serde_json::to_vec(&manifest).unwrap()), ("composite/preview.png".into(), png.into_inner())]) +} + +fn fixture(name: &str, layers: Value) -> String { + fixture_bytes(name, bundle(layers)) +} + +fn fixture_bytes(name: &str, bytes: Vec) -> String { + let dir = std::env::temp_dir().join(format!("effectcraft-pcraft-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(name); + std::fs::write(&path, bytes).unwrap(); + path.to_string_lossy().into_owned() +} + +#[test] +fn photocraft_composite_imports_as_footage() { + let path = fixture("composite.pcraft", json!([])); + let mut s = Session { importer: Some(std::sync::Arc::new(Import)), ..Default::default() }; + let r = s.execute("file.import", json!({"paths":[path]})).unwrap(); + assert!(r["errors"].as_array().unwrap().is_empty(), "{r}"); + let id = ItemId(r["items"][0].as_u64().unwrap()); + let ItemKind::Footage(f) = &s.project.item(id).unwrap().kind else { panic!("not footage") }; + assert_eq!((f.path.as_str(), f.width, f.height, f.codec.as_str()), (path.as_str(), 4, 3, "PhotoCraft")); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains("4 × 3") && w.contains("8 × 6"))), "{r}"); + let image = effectcraft_media::MediaPool::new().frame_at(f, effectcraft_time::Tick::ZERO).unwrap(); + assert_eq!((image.width, image.height), (4, 3)); + assert!((image.data[0][0] - 20.0 / 255.0).abs() < 1e-6); + assert_eq!(crate::media_browser::kind_of("shot_001.pcraft"), Some("image")); + assert!(crate::sequence::sequences(s.services.as_ref(), &["/shot_001.pcraft".into(), "/shot_002.pcraft".into()], false).is_empty()); + assert!(effectcraft_media::is_importable(std::path::Path::new("shot.PCRAFT"))); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn photocraft_composition_keeps_layer_names_visibility_opacity_and_blend() { + let layers = json!([ + layer("Bottom", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("ff0000ff")})), + layer("Hidden", false, 0.25, "Multiply", json!({"kind":"text","cache":surface("00ff0080")})), + layer( + "Group", + true, + 1.0, + "Normal", + json!({"kind":"group","children":[ + layer("Nested", true, 0.5, "Screen", json!({"kind":"shape","cache":surface("0000ffff")})) + ]}) + ) + ]); + let path = fixture("layered.pcraft", layers); + let mut s = Session::default(); + let before = s.project.items.len(); + let r = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); + assert_eq!(r["comps"].as_array().unwrap().len(), 1, "{r}"); + assert!(r["errors"].as_array().unwrap().is_empty(), "{r}"); + assert!( + r["warnings"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains("Some masks, effects and profiles are unsupported"))), + "{r}" + ); + let cid = ItemId(r["comps"][0].as_u64().unwrap()); + let c = s.project.comp(cid).unwrap(); + assert_eq!((c.width, c.height), (8, 6)); + let bottom = c.layers.iter().find(|l| l.name == "Bottom").unwrap(); + assert!(matches!(bottom.source, LayerSource::Footage { .. })); + let hidden = c.layers.iter().find(|l| l.name == "Hidden").unwrap(); + assert!(!hidden.switches.video); + assert_eq!(hidden.blend_mode, BlendMode::Multiply); + assert_eq!(hidden.props.prop("transform/opacity").unwrap().value.as_f64(), 25.0); + let group = c.layers.iter().find(|l| l.name == "Group").unwrap(); + let LayerSource::Comp { item } = group.source else { panic!("group is not a precomposition") }; + let nested = &s.project.comp(item).unwrap().layers[0]; + assert_eq!(nested.name, "Nested"); + assert_eq!(nested.blend_mode, BlendMode::Screen); + assert_eq!(nested.props.prop("transform/opacity").unwrap().value.as_f64(), 50.0); + let LayerSource::Footage { item } = nested.source else { panic!("nested layer is not footage") }; + let ItemKind::Footage(f) = &s.project.item(item).unwrap().kind else { panic!("not footage") }; + assert_eq!(f.layer.as_ref().unwrap().index, 3); + let image = effectcraft_media::MediaPool::new().frame_at(f, effectcraft_time::Tick::ZERO).unwrap(); + assert_eq!((image.width, image.height), (8, 6)); + assert_eq!(image.data[0], [0.0, 0.0, 1.0, 1.0]); + let saved = s.project.to_json(); + let limits = craft_doc::Limits::default(); + assert_eq!(craft_doc::info(saved.as_bytes(), &limits).unwrap().kind, craft_doc::Kind::EffectCraft); + let written = craft_doc::outline(saved.as_bytes(), &limits).unwrap(); + assert!(written.pages.iter().any(|p| p.layers.iter().any(|l| l.name == "Hidden"))); + assert!(craft_doc::renditions(saved.as_bytes(), &limits).unwrap().is_empty()); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.project.items.len(), before); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn photocraft_composition_notes_arrive_before_a_background_footage_job() { + let layered = fixture("background-layered.pcraft", json!([layer("Bottom", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("ff0000ff")}))])); + let mut png = std::io::Cursor::new(Vec::new()); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(2, 2, image::Rgba([1, 2, 3, 255]))).write_to(&mut png, image::ImageFormat::Png).unwrap(); + let still = fixture_bytes("background-still.png", png.into_inner()); + let mut s = Session { importer: Some(std::sync::Arc::new(Import)), ..Default::default() }; + let r = s.execute("file.import", json!({"paths":[layered, still],"importAs":"composition","background":true})).unwrap(); + assert!(r["errors"].as_array().unwrap().is_empty(), "{r}"); + let notes = |r: &Value| r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains("Some masks, effects and profiles"))); + assert!(notes(&r), "the composition already exists, so a canceled job must not hide its notes: {r}"); + let toast = s.drain_events().into_iter().find_map(|e| match e { + crate::Event::Toast { message, error } if message.contains("Some masks, effects and profiles") => Some(error), + _ => None, + }); + assert_eq!(toast, Some(false), "the composition was imported, so its notes are shown as a notice, not an error"); + s.execute("jobs.wait", json!({})).unwrap(); + let done = s.drain_events().into_iter().find_map(|e| match e { + crate::Event::Toast { message, error } if message.starts_with("Imported") => Some((message, error)), + _ => None, + }); + let (done, error) = done.expect("the finished job shows its own toast"); + assert!(!error, "{done}"); + let shown = done.lines().next().unwrap_or_default(); + assert!( + shown.contains("Some masks, effects and profiles"), + "the job's toast replaces the notice in the window, so its first line repeats the notes: {done}" + ); + std::fs::remove_file(layered).unwrap(); + std::fs::remove_file(still).unwrap(); +} + +#[test] +fn photocraft_composition_notes_from_several_files_share_one_notice() { + let first = fixture("background-first.pcraft", json!([layer("Bottom", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("ff0000ff")}))])); + let second = fixture("background-second.pcraft", json!([layer("Bottom", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("00ff00ff")}))])); + let mut png = std::io::Cursor::new(Vec::new()); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(2, 2, image::Rgba([1, 2, 3, 255]))).write_to(&mut png, image::ImageFormat::Png).unwrap(); + let still = fixture_bytes("background-third.png", png.into_inner()); + let mut s = Session { importer: Some(std::sync::Arc::new(Import)), ..Default::default() }; + let r = s.execute("file.import", json!({"paths":[first, second, still],"importAs":"composition","background":true})).unwrap(); + assert_eq!(r["warnings"].as_array().unwrap().len(), 2, "{r}"); + let notices: Vec = s + .drain_events() + .into_iter() + .filter_map(|e| match e { + crate::Event::Toast { message, error: false } => Some(message), + _ => None, + }) + .collect(); + let [notice] = notices.as_slice() else { panic!("one notice for both compositions: {notices:?}") }; + assert!(notice.lines().next().unwrap_or_default().ends_with("(and 1 more)"), "the shown line says another note is on hover: {notice}"); + assert_eq!(notice.lines().count(), 3, "{notice}"); + s.execute("jobs.wait", json!({})).unwrap(); + for path in [first, second, still] { + std::fs::remove_file(path).unwrap(); + } +} + +#[test] +fn photocraft_optional_canvas_metadata_does_not_block_probed_footage() { + struct Metadata(bool); + impl crate::Services for Metadata { + fn read_file(&self, _: &str) -> std::io::Result> { + if self.0 { + Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "metadata unavailable")) + } else { + Ok(b"invalid optional metadata".to_vec()) + } + } + fn write_file(&self, _: &str, _: &[u8]) -> std::io::Result<()> { + Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "read only")) + } + } + for unreadable in [true, false] { + let path = fixture(&format!("optional-metadata-{unreadable}.pcraft"), json!([])); + let mut s = Session { services: std::sync::Arc::new(Metadata(unreadable)), importer: Some(std::sync::Arc::new(Import)), ..Default::default() }; + let result = s.execute("file.import", json!({"paths":[path]})).unwrap(); + assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); + assert_eq!(result["items"].as_array().unwrap().len(), 1, "a successful media probe must survive an optional warning failure"); + let id = ItemId(result["items"][0].as_u64().unwrap()); + let ItemKind::Footage(f) = &s.project.item(id).unwrap().kind else { panic!("not footage") }; + assert_eq!((f.width, f.height), (4, 3)); + assert_eq!( + effectcraft_media::MediaPool::new().frame_at(f, effectcraft_time::Tick::ZERO).unwrap().data[0], + [20.0 / 255.0, 30.0 / 255.0, 40.0 / 255.0, 1.0] + ); + std::fs::remove_file(path).unwrap(); + } +} + +#[test] +fn photocraft_masks_and_sample_depths_decode_through_the_media_pool() { + use effectcraft_project::{AlphaMode, Footage, SourceLayer}; + for (sample, color, expected) in [ + ("U8", "ff0000ff", 1.0), + ("U16", "ffff00000000ffff", 1.0), + ("F32", "0000803e00000000000000000000803f", 0.5370987), + ("F32", "0000c07f00000000000000000000803f", 0.0), + ] { + let content = json!({"kind":"raster","surface":{"format":{"mode":"Rgb","sample":sample,"alpha":true},"default":color,"tiles":[]}}); + let mut raster = layer("Masked", true, 1.0, "Normal", content); + raster["mask"] = json!({"enabled":true,"density":0.5,"feather":if sample == "U16" { 0.75 } else { 0.0 }, + "surface":{"format":{"mode":"Grayscale","sample":"U8","alpha":false},"default":"80","tiles":[]}}); + let path = fixture(&format!("masked-{sample}.pcraft"), json!([raster])); + let mut f = Footage { + path: path.clone(), + width: 8, + height: 6, + has_video: true, + alpha: AlphaMode::Straight, + layer: Some(SourceLayer { index: 0, name: "Masked".into(), layer_size: false, embedded: None, placed: false }), + ..Default::default() + }; + let pool = effectcraft_media::MediaPool::new(); + let image = pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap(); + let coverage = 1.0 - 0.5 * (1.0 - 128.0 / 255.0); + assert!((image.data[0][0] - expected * coverage).abs() < 1e-5, "{sample}: {:?}", image.data[0]); + assert!((image.data[0][3] - coverage).abs() < 1e-6); + f.alpha = AlphaMode::Premultiplied; + let image = pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap(); + assert!((image.data[0][0] - expected * coverage).abs() < 1e-5, "masked premultiplied {sample}: {:?}", image.data[0]); + assert!((image.data[0][3] - coverage).abs() < 1e-6); + f.alpha = AlphaMode::Ignore; + let image = pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap(); + assert!((image.data[0][0] - expected).abs() < 1e-5); + assert_eq!(image.data[0][3], 1.0, "Ignore Alpha includes the source mask"); + std::fs::remove_file(path).unwrap(); + } +} + +#[test] +fn photocraft_overlapping_layers_render_in_source_stack_order() { + let path = fixture( + "stack-order.pcraft", + json!([ + layer("Bottom", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("ff0000ff")})), + layer( + "Group", + true, + 1.0, + "Normal", + json!({"kind":"group","children":[ + layer("Group bottom", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("00ff00ff")})), + layer("Group top", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("0000ffff")})) + ]}) + ) + ]), + ); + let mut s = Session { footage: std::sync::Arc::new(effectcraft_media::MediaPool::new()), ..Default::default() }; + let result = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); + let comp = ItemId(result["comps"][0].as_u64().unwrap()); + let image = s.render(comp, effectcraft_time::Tick::ZERO, Default::default()); + assert_eq!(image.data[0], [0.0, 0.0, 1.0, 1.0], "the source's top layer must cover both lower layers"); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn photocraft_bad_metadata_and_missing_layer_pixels_report_errors() { + use effectcraft_project::{AlphaMode, Footage, SourceLayer}; + for (name, bytes) in [ + ("empty-side.pcraft", bundle_sized(json!([]), (0, 6))), + ("large-canvas.pcraft", bundle_sized(json!([]), (30_000, 30_000))), + ("unsupported-fill.pcraft", bundle(json!([layer("Fill", true, 1.0, "Normal", json!({"kind":"fill"}))]))), + ("truncated.pcraft", b"PK\x03\x04broken".to_vec()), + ] { + let path = fixture_bytes(name, bytes); + let mut s = Session::default(); + let before = s.project.items.len(); + let result = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); + assert!(result["comps"].as_array().unwrap().is_empty(), "{name}: {result}"); + assert!(!result["errors"].as_array().unwrap().is_empty(), "{name}: {result}"); + assert_eq!(s.project.items.len(), before); + std::fs::remove_file(path).unwrap(); + } + let path = fixture("missing-cache.pcraft", json!([layer("Text", true, 1.0, "Normal", json!({"kind":"text"}))])); + let mut f = Footage { + path: path.clone(), + width: 8, + height: 6, + has_video: true, + alpha: AlphaMode::Straight, + layer: Some(SourceLayer { index: 0, name: "Text".into(), layer_size: false, embedded: None, placed: false }), + ..Default::default() + }; + let pool = effectcraft_media::MediaPool::new(); + assert!(pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap_err().to_string().contains("no saved pixels")); + f.layer.as_mut().unwrap().index = 99; + assert!(pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap_err().to_string().contains("no PhotoCraft layer")); + std::fs::remove_file(path).unwrap(); +} + +#[test] +#[cfg(unix)] // Sparse length checks exercise the guard without writing half a GiB. +fn photocraft_large_files_are_rejected_before_reading() { + let path = fixture_bytes("large-sparse.pcraft", b"PK\x03\x04".to_vec()); + std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_len((512 << 20) + 1).unwrap(); + assert!(effectcraft_media::probe(&path).unwrap_err().to_string().contains("512 MiB input limit")); + let mut s = Session::default(); + let before = s.project.items.len(); + let r = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); + assert_eq!(s.project.items.len(), before); + assert!(r["errors"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains("512 MiB input limit"))), "{r}"); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn photocraft_layer_buffers_are_bounded_before_decoding_pixels() { + use effectcraft_project::{AlphaMode, Footage, SourceLayer}; + // An invalid source sample proves the budget is checked before the pixel reader. + let mut raster = layer("Large masked layer", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("invalid-pixel-sample")})); + raster["mask"] = json!({"enabled":true,"density":1.0,"feather":4.0, + "surface":{"format":{"mode":"Grayscale","sample":"U8","alpha":false},"default":"ff","tiles":[]}}); + let path = fixture_bytes("mask-budget.pcraft", bundle_sized(json!([raster]), (4097, 3072))); + let f = Footage { + path: path.clone(), + width: 4097, + height: 3072, + has_video: true, + alpha: AlphaMode::Straight, + layer: Some(SourceLayer { index: 0, name: "Large masked layer".into(), layer_size: false, embedded: None, placed: false }), + ..Default::default() + }; + let error = effectcraft_media::MediaPool::new().frame_at(&f, effectcraft_time::Tick::ZERO).unwrap_err().to_string(); + assert!(error.contains("1 GiB working-buffer budget") && error.contains("Footage"), "{error}"); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn photocraft_group_nesting_stays_within_the_composition_renderer_limit() { + // Pass-through groups collapse into their parents only 13 levels deep in the renderer, so a + // deeper one is refused instead of blending as a flattened group. + let cases = [ + (16, "Normal", None), + (13, "PassThrough", None), + (14, "PassThrough", Some("13 levels")), + (17, "Normal", Some("16 levels")), + (17, "PassThrough", Some("13 levels")), + ]; + for (depth, blend, refused) in cases { + let mut layers = json!([layer("Deep pixels", true, 1.0, "Normal", json!({"kind":"raster","surface":surface("0000ffff")}))]); + for index in 0..depth { + layers = json!([layer(&format!("Group {index}"), true, 1.0, blend, json!({"kind":"group","children":layers}))]); + } + let path = fixture(&format!("nesting-{depth}-{blend}.pcraft"), layers); + let mut s = Session { footage: std::sync::Arc::new(effectcraft_media::MediaPool::new()), ..Default::default() }; + let before = s.project.items.len(); + let result = s.execute("file.import", json!({"paths":[path],"importAs":"composition"})).unwrap(); + if let Some(levels) = refused { + assert_eq!(s.project.items.len(), before, "unsupported nesting must not create a composition with disappearing artwork"); + assert!( + result["errors"].as_array().unwrap().iter().any(|e| e.as_str().is_some_and(|e| e.contains(levels) && e.contains("Footage"))), + "{depth} {blend}: {result}" + ); + } else { + let comp = ItemId(result["comps"][0].as_u64().unwrap()); + assert_eq!(s.render(comp, effectcraft_time::Tick::ZERO, Default::default()).data[0], [0.0, 0.0, 1.0, 1.0], "{depth} {blend}"); + } + std::fs::remove_file(path).unwrap(); + } +} diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 26c6801e0..59e0a3f4b 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -10,6 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] +craft-doc = { workspace = true, features = ["pcraft-pixels"] } craft-docpath = { workspace = true } effectcraft-time = { workspace = true } effectcraft-color = { workspace = true } diff --git a/crates/media/src/convert.rs b/crates/media/src/convert.rs index dd3a46801..61e5b77e4 100644 --- a/crates/media/src/convert.rs +++ b/crates/media/src/convert.rs @@ -38,6 +38,21 @@ impl AlphaOp { pub(crate) fn float_curve(self) -> FloatCurve { self.float } + /// A source sample, with float RGB encoded the same way as a floating-point image. + pub(crate) fn rgba(self, rgb: [f32; 3], alpha: f32, floating: bool, coverage: f32) -> Px { + let rgb = if floating && self.mode == AlphaMode::Premultiplied { + let inv = if alpha > 0.0 { 1.0 / alpha } else { 0.0 }; + rgb.map(|v| self.float(v * inv) * alpha) + } else if floating { + rgb.map(|v| self.float(v)) + } else { + rgb + }; + let pixel = self.apply(rgb, alpha); + // Interpret the source against its original alpha and matte before applying the + // mask. Ignore Alpha deliberately ignores both source and mask coverage. + if self.mode == AlphaMode::Ignore { pixel } else { pixel.map(|v| v * coverage) } + } /// A linear float value as the compositor takes it. #[inline(always)] fn float(self, v: f32) -> f32 { diff --git a/crates/media/src/layered.rs b/crates/media/src/layered.rs index 68edd9808..351c32514 100644 --- a/crates/media/src/layered.rs +++ b/crates/media/src/layered.rs @@ -44,11 +44,14 @@ fn is_pdf_like(path: &str, bytes: &[u8]) -> bool { /// Whether `bytes` (the first 64 KiB suffice) are a Photoshop or vector file [`probe`] handles. #[cfg_attr(not(any(unix, windows)), allow(dead_code))] pub(crate) fn sniff(path: &str, bytes: &[u8]) -> bool { - effectcraft_psd::is_psd(bytes) || is_svg(path, bytes) || is_pdf_like(path, bytes) + effectcraft_psd::is_psd(bytes) || crate::pcraft::sniff(path, bytes) || is_svg(path, bytes) || is_pdf_like(path, bytes) } /// Footage for a Photoshop or vector file (`None` for other formats). pub(crate) fn probe(path: &str, bytes: &[u8]) -> Result> { + if crate::pcraft::sniff(path, bytes) { + return crate::pcraft::probe(path, bytes).map(Some); + } if effectcraft_psd::is_psd(bytes) { let psd = effectcraft_psd::Psd::parse(bytes.to_vec()).map_err(|e| MediaError::Decode(format!("{path}: {e}")))?; let mut f = crate::probe::still_footage(path, psd.width, psd.height, image::ImageFormat::Png, true); @@ -77,6 +80,9 @@ pub(crate) fn probe(path: &str, bytes: &[u8]) -> Result> { /// Decode a Photoshop or SVG still (`None` for other formats). pub(crate) fn decode(path: &str, bytes: &[u8], footage: &Footage, op: AlphaOp) -> Result> { + if crate::pcraft::sniff(path, bytes) { + return crate::pcraft::decode(path, bytes, footage, op).map(Some); + } if effectcraft_psd::is_psd(bytes) { let psd = effectcraft_psd::Psd::parse(bytes.to_vec()).map_err(|e| MediaError::Decode(format!("{path}: {e}")))?; // A smart object's embedded file: an embedded document's merged image, or an image. diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index 5d3f376d0..9f172588f 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -11,7 +11,8 @@ //! AV1, ProRes, DNxHD, MPEG-2, MJPEG; AAC, Opus, PCM, MP3/FLAC/Vorbis) come from FilmCraft's pure-Rust crates (git dependency, //! pinned; `plan/adr/0001`). FilmCraft types never leave this crate. Stills use the `image` crate //! (PNG, JPEG, GIF, WebP, TIFF, BMP, OpenEXR, Targa, Radiance HDR); Photoshop documents (merged image or one layer) come -//! from `effectcraft-psd` and SVG from `effectcraft-svg` (rasterised at any scale). +//! from `effectcraft-psd`, PhotoCraft composites and saved layer pixels from `craft-doc`, and SVG +//! from `effectcraft-svg` (rasterised at any scale). #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -27,6 +28,7 @@ mod exr_read; mod gif_anim; mod layered; mod localize; +mod pcraft; pub use layered::vector_doc; mod pool; mod probe; @@ -82,7 +84,7 @@ impl From for MediaError { /// File extensions recognised as stills. pub const STILL_EXTENSIONS: &[&str] = - &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "tga", "hdr", "psd", "psb", "svg", "pdf", "ai", "eps", "vectorcraft"]; + &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "tga", "hdr", "psd", "psb", "pcraft", "svg", "pdf", "ai", "eps", "vectorcraft"]; /// File extensions recognised as audio-only files. pub const AUDIO_EXTENSIONS: &[&str] = craft_media_source::AUDIO_EXTENSIONS; pub use effectcraft_project::VIDEO_EXTENSIONS; @@ -117,13 +119,31 @@ pub(crate) fn read_regular_file_stamped(path: &std::path::Path) -> std::io::Resu if !meta.is_file() { return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{} is not a file", path.display()))); } + // A renamed bundle is checked after its read, before it is parsed. + let limit = input_limit(path); + if limit.is_some_and(|max| meta.len() > max) { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "PhotoCraft bundle exceeds the 512 MiB input limit")); + } let mut bytes = Vec::new(); // A sparse file can claim far more than memory: an error, not an abort. bytes.try_reserve_exact(usize::try_from(meta.len()).unwrap_or(usize::MAX)).map_err(|e| std::io::Error::new(std::io::ErrorKind::OutOfMemory, e))?; - file.read_to_end(&mut bytes)?; + if let Some(max) = limit { + file.take(max.saturating_add(1)).read_to_end(&mut bytes)?; + if bytes.len() as u64 > max { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "PhotoCraft bundle grew beyond the 512 MiB input limit")); + } + } else { + file.read_to_end(&mut bytes)?; + } Ok((bytes, effectcraft_render::reads::FileStamp::of_metadata(&meta))) } +/// The most bytes a read of `path` takes before it fails: `.pcraft` files have the PhotoCraft +/// input limit; other files, ZIP-based templates and dotLottie files included, have none. +fn input_limit(path: &std::path::Path) -> Option { + (ext_of(path) == "pcraft").then_some(pcraft::MAX_INPUT_BYTES) +} + #[cfg(test)] static OPENS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); @@ -190,4 +210,26 @@ mod read_tests { assert_eq!(super::read_regular_file(&f).unwrap(), b"abc"); let _ = std::fs::remove_file(f); } + + /// Templates and dotLottie files are ZIP archives too: only `.pcraft` files have the + /// 512 MiB input limit. A `.pcraft` file over it is refused from its length, which is set + /// without writing the data, so nothing is read. + #[test] + fn large_zip_files_other_than_photocraft_are_read_whole() { + let max = crate::pcraft::MAX_INPUT_BYTES; + for name in ["a.zip", "a.lottie", "a.json", "a"] { + assert_eq!(super::input_limit(std::path::Path::new(name)), None, "{name}"); + } + for name in ["a.pcraft", "a.PCraft"] { + assert_eq!(super::input_limit(std::path::Path::new(name)), Some(max), "{name}"); + } + let f = std::env::temp_dir().join(format!("ec-read-large-{}.pcraft", std::process::id())); + std::fs::write(&f, b"PK\x03\x04").unwrap(); + std::fs::OpenOptions::new().write(true).open(&f).unwrap().set_len(max + 1).unwrap(); + let error = super::read_regular_file(&f).unwrap_err(); + assert!(error.to_string().contains("512 MiB input limit"), "{error}"); + std::fs::OpenOptions::new().write(true).open(&f).unwrap().set_len(4).unwrap(); + assert_eq!(super::read_regular_file(&f).unwrap(), b"PK\x03\x04"); + let _ = std::fs::remove_file(f); + } } diff --git a/crates/media/src/pcraft.rs b/crates/media/src/pcraft.rs new file mode 100644 index 000000000..ab8b0b74f --- /dev/null +++ b/crates/media/src/pcraft.rs @@ -0,0 +1,177 @@ +//! PhotoCraft's saved composite and canvas-sized raster or cached layer pixels. + +use craft_doc::{Layer, RenditionKind, Samples}; +use effectcraft_project::{AlphaMode, Footage}; +use effectcraft_raster::Image; + +use crate::convert::{AlphaOp, dynamic_to_image}; +use crate::{MediaError, Result}; + +/// Keep the decoded float frame and its conversion buffers within the still-image budget. +const MAX_PIXELS: u64 = 16 << 20; +// Conservatively count source RGBA (16 B), raw mask samples (4 B), mask image +// (16 B), two blur images (32 B) and output (16 B), even where lifetimes do not +// overlap. Twelve Mi pixels fit within a 1 GiB working-buffer budget (84 B/pixel). +const MAX_LAYER_PIXELS: u64 = 12 << 20; +pub(crate) const MAX_INPUT_BYTES: u64 = effectcraft_project::PCRAFT_MAX_INPUT; + +pub(crate) fn sniff(path: &str, bytes: &[u8]) -> bool { + path.to_ascii_lowercase().ends_with(".pcraft") || craft_doc::sniff(bytes) == Some(craft_doc::Kind::PhotoCraft) +} + +fn error(path: &str, e: impl std::fmt::Display) -> MediaError { + MediaError::Decode(format!("{path}: {e}")) +} + +fn check_size(path: &str, width: u32, height: u32) -> Result<()> { + if width == 0 || height == 0 || u64::from(width) * u64::from(height) > MAX_PIXELS { + return Err(error(path, format!("PhotoCraft image {width} × {height} exceeds the {MAX_PIXELS}-pixel decoding limit or has an empty side"))); + } + Ok(()) +} + +fn composite(path: &str, bytes: &[u8]) -> Result> { + check_input(path, bytes)?; + craft_doc::renditions(bytes, &craft_doc::Limits::default()) + .map_err(|e| error(path, e))? + .into_iter() + .find(|r| r.kind == RenditionKind::Composite) + .map(|r| r.bytes) + .ok_or_else(|| error(path, "PhotoCraft document has no saved composite")) +} + +fn check_input(path: &str, bytes: &[u8]) -> Result<()> { + if bytes.len() as u64 > MAX_INPUT_BYTES { + return Err(error(path, "PhotoCraft bundle exceeds the 512 MiB input limit")); + } + Ok(()) +} + +fn png_size(path: &str, bytes: &[u8]) -> Result<(u32, u32)> { + let size = image::ImageReader::with_format(std::io::Cursor::new(bytes), image::ImageFormat::Png).into_dimensions().map_err(|e| error(path, e))?; + check_size(path, size.0, size.1)?; + Ok(size) +} + +pub(crate) fn probe(path: &str, bytes: &[u8]) -> Result { + let png = composite(path, bytes)?; + let (w, h) = png_size(path, &png)?; + let mut f = crate::probe::still_footage(path, w, h, image::ImageFormat::Png, true); + f.codec = "PhotoCraft".into(); + f.alpha = AlphaMode::Straight; + Ok(f) +} + +/// Preorder indexes include groups and unsupported layers, so a reload addresses the same +/// outline entry used by the composition importer. +fn layer_path(layers: &[Layer], wanted: u32) -> Option> { + fn find(layers: &[Layer], wanted: u32, next: &mut u32, path: &mut Vec, depth: usize) -> Option> { + if depth > 100 { + return None; + } + for (index, layer) in layers.iter().enumerate() { + path.push(index); + let current = *next; + *next = next.checked_add(1)?; + if current == wanted { + return Some(path.clone()); + } + if let Some(found) = find(&layer.children, wanted, next, path, depth + 1) { + return Some(found); + } + path.pop(); + } + None + } + find(layers, wanted, &mut 0, &mut Vec::new(), 0) +} + +fn mask_image(path: &str, width: u32, height: u32, samples: Samples) -> Result { + let count = usize::try_from(u64::from(width) * u64::from(height)).map_err(|e| error(path, e))?; + if samples.len() != count { + return Err(error(path, "PhotoCraft mask size does not match the canvas")); + } + let mut data = Vec::new(); + data.try_reserve_exact(count).map_err(|e| error(path, e))?; + let pixel = |v: f32| [if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; 4]; + match samples { + Samples::U8(v) => data.extend(v.into_iter().map(|v| pixel(f32::from(v) / 255.0))), + Samples::U16(v) => data.extend(v.into_iter().map(|v| pixel(f32::from(v) / 65535.0))), + Samples::F32(v) => data.extend(v.into_iter().map(pixel)), + _ => return Err(error(path, "unsupported PhotoCraft mask sample type")), + } + Ok(Image { width, height, data }) +} + +pub(crate) fn decode(path: &str, bytes: &[u8], footage: &Footage, op: AlphaOp) -> Result { + check_input(path, bytes)?; + let Some(layer) = &footage.layer else { + let png = composite(path, bytes)?; + png_size(path, &png)?; + let image = crate::probe::load_oriented(&png, Some(image::ImageFormat::Png)).map_err(|e| error(path, e))?; + return Ok(dynamic_to_image(&image, op)); + }; + if layer.layer_size || layer.embedded.is_some() || layer.placed { + return Err(error(path, "PhotoCraft layer footage supports canvas-sized saved pixels, not cropped or embedded-file sources")); + } + let outline = craft_doc::outline(bytes, &craft_doc::Limits::default()).map_err(|e| error(path, e))?; + let canvas = outline.canvas.ok_or_else(|| error(path, "PhotoCraft document has no canvas"))?; + check_size(path, canvas.width, canvas.height)?; + if u64::from(canvas.width) * u64::from(canvas.height) > MAX_LAYER_PIXELS { + return Err(error(path, "PhotoCraft layer exceeds the 1 GiB working-buffer budget; import as Footage for the saved composite")); + } + let indexes = layer_path(&outline.layers, layer.index).ok_or_else(|| error(path, format!("no PhotoCraft layer {}", layer.index)))?; + let pixels = craft_doc::pcraft_layer_rgba(bytes, &indexes, &craft_doc::Limits::default()) + .map_err(|e| error(path, e))? + .ok_or_else(|| error(path, format!("PhotoCraft layer {} has no saved pixels", layer.name)))?; + let (w, h) = (pixels.width, pixels.height); + let count = usize::try_from(u64::from(w) * u64::from(h)).map_err(|e| error(path, e))?; + if count.checked_mul(4) != Some(pixels.rgba.len()) { + return Err(error(path, "PhotoCraft layer sample count does not match the canvas")); + } + let mask = if let Some(mask) = pixels.mask.filter(|m| m.enabled) { + let mut alpha = mask_image(path, w, h, mask.alpha)?; + let sigma = if mask.feather.is_finite() { f64::from(mask.feather.clamp(0.0, 1000.0)) } else { 0.0 }; + if sigma > 0.0 { + alpha = if effectcraft_raster::gaussian_is_exact(sigma, sigma) { + effectcraft_raster::gaussian_blur_exact(&alpha, sigma, sigma, true) + } else { + effectcraft_raster::gaussian_blur(&alpha, sigma, sigma, true) + }; + } + let density = if mask.density.is_finite() { mask.density.clamp(0.0, 1.0) } else { 1.0 }; + Some((alpha, density)) + } else { + None + }; + let mut data = Vec::new(); + data.try_reserve_exact(count).map_err(|e| error(path, e))?; + let mut push = |index: usize, rgba: [f32; 4], floating: bool| -> Result<()> { + let rgba = rgba.map(|v| if v.is_finite() { v } else { 0.0 }); + let coverage = match &mask { + Some((alpha, density)) => 1.0 - density * (1.0 - alpha.data.get(index).ok_or_else(|| error(path, "PhotoCraft mask pixel is missing"))?[3]), + None => 1.0, + }; + data.push(op.rgba([rgba[0], rgba[1], rgba[2]], rgba[3].clamp(0.0, 1.0), floating, coverage)); + Ok(()) + }; + match pixels.rgba { + Samples::U8(v) => { + for (index, [r, g, b, a]) in v.as_chunks::<4>().0.iter().enumerate() { + push(index, [f32::from(*r), f32::from(*g), f32::from(*b), f32::from(*a)].map(|v| v / 255.0), false)?; + } + } + Samples::U16(v) => { + for (index, [r, g, b, a]) in v.as_chunks::<4>().0.iter().enumerate() { + push(index, [f32::from(*r), f32::from(*g), f32::from(*b), f32::from(*a)].map(|v| v / 65535.0), false)?; + } + } + Samples::F32(v) => { + for (index, [r, g, b, a]) in v.as_chunks::<4>().0.iter().enumerate() { + push(index, [*r, *g, *b, *a], true)?; + } + } + _ => return Err(error(path, "unsupported PhotoCraft layer sample type")), + } + Ok(Image { width: w, height: h, data }) +} diff --git a/crates/project/src/footage.rs b/crates/project/src/footage.rs index 462772dc4..107e5effc 100644 --- a/crates/project/src/footage.rs +++ b/crates/project/src/footage.rs @@ -49,6 +49,10 @@ impl FieldOrder { /// by this list. pub const VIDEO_EXTENSIONS: &[&str] = &["mp4", "m4v", "mov", "mkv", "webm", "mxf", "avi"]; +/// The largest PhotoCraft bundle that is read for import, in bytes. The engine's +/// `Services::read_pcraft` and `effectcraft_media`'s file reader both use it. +pub const PCRAFT_MAX_INPUT: u64 = 512 << 20; + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum AlphaMode { #[default] diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs index 9f5f399e0..fe8146b9b 100644 --- a/crates/project/src/lib.rs +++ b/crates/project/src/lib.rs @@ -40,7 +40,9 @@ mod reach; mod settings; pub use comp::{Comp, Guide, Renderer, Resolution}; -pub use footage::{AlphaMode, CineonSettings, CineonUnits, FieldOrder, Footage, FootageKind, Proxy, Solid, SourceLayer, VIDEO_EXTENSIONS, cineon_log_to_lin}; +pub use footage::{ + AlphaMode, CineonSettings, CineonUnits, FieldOrder, Footage, FootageKind, PCRAFT_MAX_INPUT, Proxy, Solid, SourceLayer, VIDEO_EXTENSIONS, cineon_log_to_lin, +}; pub use item::NO_LAYER; pub use item::{Heard, Item, ItemId, ItemKind, LayerId}; pub use layer::{ diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 3cabab4e3..2408c3cf1 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -66,6 +66,10 @@ pub use opts::{LayerTiming, RenderOpts}; use opts::{MAX_THROUGH, Through}; pub use pipeline::{Collapsed, FootagePicture, MediaOverride, PropertyOverride}; +/// The deepest nested comp whose precomp layers still collapse their transformations: a layer +/// with Collapse Transformations in a comp nested deeper than this is rendered flattened. +pub const MAX_COLLAPSE_DEPTH: usize = 12; + pub struct Renderer<'a> { pub project: &'a Project, pub footage: &'a dyn FootageSource, diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 65d728ad3..362ce069e 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -365,7 +365,7 @@ impl<'a> Renderer<'a> { /// Properties overrides travel with it and are applied as the nested layers are evaluated, /// so the nested comp is not rasterised at its frame. pub fn collapsed(&self, ctx: &EvalCtx, layer: &Layer) -> Option { - if !layer.switches.collapse || layer.switches.adjustment || self.depth > 12 { + if !layer.switches.collapse || layer.switches.adjustment || self.depth > super::MAX_COLLAPSE_DEPTH { return None; } let LayerSource::Comp { item } = &layer.source else { return None }; diff --git a/crates/ui-egui/src/menus/frontend.rs b/crates/ui-egui/src/menus/frontend.rs index 9f2590db0..077a4b139 100644 --- a/crates/ui-egui/src/menus/frontend.rs +++ b/crates/ui-egui/src/menus/frontend.rs @@ -680,7 +680,7 @@ pub(super) fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> // Importable files besides movies. const MEDIA: &[&str] = &[ "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "dpx", "cin", "wav", "aif", "aiff", "mp3", "flac", "ogg", "opus", "svg", "pdf", "ai", - "eps", "psd", "psb", "tga", "hdr", "gltf", "glb", "obj", "stl", "fbx", "json", "csv", "tsv", + "eps", "psd", "psb", "pcraft", "tga", "hdr", "gltf", "glb", "obj", "stl", "fbx", "json", "csv", "tsv", ]; // VectorCraft documents, read through the PDF they carry. let media = [MEDIA, &["vectorcraft"]].concat(); diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index e06979243..54f0c4c52 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -647,7 +647,7 @@ fn every_import_item_asks_through_the_shared_dialog_path() { } #[test] -fn tga_is_available_in_import_replace_and_proxy_dialogs() { +fn tga_is_available_in_import_replace_and_proxy_and_pcraft_in_import_replace() { use std::sync::{Arc, Mutex}; let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); let ctx = egui::Context::default(); @@ -658,6 +658,9 @@ fn tga_is_available_in_import_replace_and_proxy_dialogs() { assert_eq!(invoke(&mut app, &ctx, command, json!({})).unwrap(), json!({"dialog": command})); let crate::FileDialog::Open { exts, .. } = pending.lock().unwrap().pop().unwrap() else { panic!("not an open dialog") }; assert!(exts.iter().any(|ext| ext == "tga"), "{command}: {exts:?}"); + if command != "file.setProxy" { + assert!(exts.iter().any(|ext| ext == "pcraft"), "{command}: {exts:?}"); + } } } diff --git a/crates/ui-egui/src/panels/forms.rs b/crates/ui-egui/src/panels/forms.rs index cd3ed0aca..c5a37cd7a 100644 --- a/crates/ui-egui/src/panels/forms.rs +++ b/crates/ui-egui/src/panels/forms.rs @@ -507,6 +507,11 @@ fn transform_form(p: &Value, layer: Option<&effectcraft_engine::project::Layer>, (title.into(), fields) } +/// The Import dialog's note on how a PhotoCraft file imports as a composition. +fn pcraft_note() -> Field { + Field::note("pcraftNote", "Composition uses canvas-sized saved pixels. Masks, effects and profiles may differ; use Footage for the saved appearance.") +} + /// If `id` is a dialog command invoked without its parameters, open its form and return true. pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool { let s = &app.session; @@ -516,6 +521,17 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool { let lt = layer.map(|l| l.layer_time(t)).unwrap_or(t); let mut base = p.clone(); let (title, fields): (String, Vec) = match id { + "file.import" if !has(p, &["importAs"]) && imports_ext(p, &["pcraft"]) && !is_layered(p) => { + let drag = p.get("drag").and_then(Value::as_bool).unwrap_or(false); + let sel = usize::from(drag && s.prefs.drag_import_as() != "footage"); + let mut fields = + vec![Field::choice("importAs", "Import Kind", &[("Footage", json!("footage")), ("Composition", json!("composition"))], sel), pcraft_note()]; + // A PDF or Illustrator file picked with it keeps its Page field. + if is_pdf(p) && !has(p, &["page"]) { + fields.push(Field::num("page", "Page", 1.0)); + } + ("Import PhotoCraft File".into(), fields) + } // Photoshop files: Import Kind (Footage / Composition / – Retain Layer Sizes). Dropped // files start at Settings ▸ Import ▸ Default Drag Import As. "file.import" if !has(p, &["importAs"]) && is_layered(p) => { @@ -523,7 +539,10 @@ pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool { [("Footage", json!("footage")), ("Composition", json!("composition")), ("Composition - Retain Layer Sizes", json!("compositionLayerSizes"))]; let drag = p.get("drag").and_then(Value::as_bool).unwrap_or(false); let sel = if drag { kinds.iter().position(|(_, v)| v.as_str() == Some(s.prefs.drag_import_as())).unwrap_or(0) } else { 1 }; - ("Import Photoshop File".into(), vec![Field::choice("importAs", "Import Kind", &kinds, sel)]) + let mut fields = vec![Field::choice("importAs", "Import Kind", &kinds, sel)]; + // A PhotoCraft file picked with it keeps its compatibility note. + fields.extend(imports_ext(p, &["pcraft"]).then(pcraft_note)); + ("Import Photoshop File".into(), fields) } // PDF / Illustrator files: Import Kind and the page. "file.import" if !has(p, &["importAs", "page"]) && is_pdf(p) => ( @@ -1056,6 +1075,51 @@ pub fn show_view_options(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Toke mod tests { use super::*; + #[test] + fn photocraft_import_offers_footage_or_canvas_sized_layers() { + for (pref, expected) in [("footage", "footage"), ("comp", "composition"), ("compLayerSizes", "composition")] { + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + app.session.prefs.import.drag_import_as = pref.into(); + let reply = crate::menus::invoke(&mut app, &egui::Context::default(), "file.import", json!({"paths":["/picked.pcraft"],"drag":true})).unwrap(); + assert_eq!(reply["dialog"], "file.import"); + assert_eq!(app.dialog_state.form.title, "Import PhotoCraft File"); + assert_eq!(app.dialog_state.form.params()["importAs"], expected); + assert!(app.dialog_state.form.params().get("pcraftNote").is_none()); + let FieldKind::Choice { options, .. } = &app.dialog_state.form.fields[0].kind else { panic!("no import choices") }; + assert_eq!(options.len(), 2, "Retain Layer Sizes is not offered for canvas-sized PhotoCraft pixels"); + assert!(app.dialog_state.form.params().get("page").is_none(), "no page without a PDF"); + } + } + + #[test] + fn photocraft_import_with_a_pdf_keeps_the_page_field() { + for pdf in ["/picked.pdf", "/picked.ai"] { + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + let reply = + crate::menus::invoke(&mut app, &egui::Context::default(), "file.import", json!({"paths": ["/picked.pcraft", pdf], "drag": true})).unwrap(); + assert_eq!(reply["dialog"], "file.import"); + assert_eq!(app.dialog_state.form.title, "Import PhotoCraft File"); + assert_eq!(app.dialog_state.form.params()["page"], json!(1.0), "{pdf}"); + } + } + + #[test] + fn photocraft_import_with_a_photoshop_file_keeps_the_note() { + let has_note = |paths: Value| { + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + let reply = crate::menus::invoke(&mut app, &egui::Context::default(), "file.import", json!({"paths": paths, "drag": true})).unwrap(); + assert_eq!(reply["dialog"], "file.import"); + assert_eq!(app.dialog_state.form.title, "Import Photoshop File"); + let FieldKind::Choice { options, .. } = &app.dialog_state.form.fields[0].kind else { panic!("no import choices") }; + assert_eq!(options.len(), 3); + app.dialog_state.form.fields.iter().any(|f| f.key == "pcraftNote") + }; + for psd in ["/picked.psd", "/picked.psb"] { + assert!(has_note(json!(["/picked.pcraft", psd])), "{psd}"); + assert!(!has_note(json!([psd])), "{psd}"); + } + } + #[test] fn renderer_form_keeps_descriptive_labels_and_stable_option_values() { crate::i18n::set_current("en"); diff --git a/crates/ui-egui/src/prefs_live.rs b/crates/ui-egui/src/prefs_live.rs index e5a09159d..e4a4b45f3 100644 --- a/crates/ui-egui/src/prefs_live.rs +++ b/crates/ui-egui/src/prefs_live.rs @@ -146,7 +146,7 @@ pub fn dropped_files(app: &mut EffectcraftApp, ui: &egui::Ui, bounds: Rect) { let alt = ctx.input(|i| i.modifiers.alt); // A dropped Photoshop file asks how to import it (the Import Photoshop File dialog, its // Import Kind starting at Default Drag Import As), as File ▸ Import ▸ File… does (#678). - let layered = rest.iter().any(|p| p.rsplit('.').next().is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "psd" | "psb"))); + let layered = rest.iter().any(|p| p.rsplit('.').next().is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "psd" | "psb" | "pcraft"))); let mut params = json!({ "paths": rest, "drag": true, diff --git a/docs/photocraft-import.md b/docs/photocraft-import.md new file mode 100644 index 000000000..20ebf49b2 --- /dev/null +++ b/docs/photocraft-import.md @@ -0,0 +1,27 @@ +# Import PhotoCraft documents + +Choose **File ▸ Import ▸ File…** and select a `.pcraft` document. Numbered PhotoCraft documents import individually, rather than as an image sequence. + +**Footage** reads the document's saved composite as one still image. Its dimensions are the saved image's actual dimensions. The currently pinned shared reader exposes PhotoCraft's saved preview, which can be smaller than the canvas. Import reports both sizes when they differ. Full-resolution composite selection requires a later shared-reader update. + +**Composition** creates a composition with canvas-sized layer footage. It preserves layer names, visibility, opacity, recognized blend modes and group nesting. Groups become precompositions; pass-through groups use Collapse Transformations. Raster layers and saved pixel caches for text, shapes and smart objects remain linked to the source file. Text, shapes and smart objects are imported as pixels, without their native editing controls. + +Layer pixels decode when a frame needs them. Missing caches or unsupported pixel data produce media decoding errors when used. Layered import supports RGB and grayscale pixels with 8-bit, 16-bit or floating-point samples. Enabled raster masks apply their density and feather. Native effects, vector and group masks, and embedded color profiles are unsupported, so a layered composition can differ from the saved appearance. Choose Footage when that appearance matters. + +The dialog offers Footage and Composition. The command API also accepts `compositionLayerSizes`, but reports that PhotoCraft layers retain the full canvas bounds. A drag preference for retaining layer sizes selects Composition in this dialog. + +## Command API + +```json +{"command":"file.import","params":{"paths":["/path/artwork.pcraft"],"importAs":"footage"}} +``` + +Use `"importAs":"composition"` for layers. Import uses the existing still-footage duration preference and creates one undoable import operation for each layered document. Compatibility messages accompany the command's import results. + +## Limits + +PhotoCraft input is limited to 512 MiB. A `.pcraft` file is checked before it is read. A PhotoCraft bundle with another extension is checked after it is read and before it is parsed. Other ZIP-based files, such as templates and dotLottie files, do not have this limit. Decoded composites are limited to 16,777,216 pixels and layer canvases to 12,582,912 pixels. Composition import also respects EffectCraft's composition size limit, allows up to 4,096 layers and 16 levels of group nesting, and rejects unsupported CMYK or Lab layer data. Footage can still import a supported saved composite when the document's layers exceed those limits. + +Unsupported layer kinds are skipped with a message naming the layer. A nonempty document with no supported pixel layers cannot import as a composition; the error recommends Footage. Invalid input reports an error before adding a composition. + +Layer decoding has a separate limit of 12,582,912 canvas pixels, checked before reading source samples. A conservative budget counts the source, raw mask, mask image, both feathering intermediates and output together, within 1 GiB of working buffers. Larger canvases report an error recommending Footage before decoding layer pixels. This includes masked and unmasked layers; saved composites retain the 16,777,216-pixel limit.