EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust
Merge main into IO-2/SHP-5/OUT-2/PRV-2 work
Brandon Thomas36683d95ee6a
diff --cc ATTRIBUTION.mdindex d0b936b8b,f89c0e87b..d52b19c7c--- a/ATTRIBUTION.md+++ b/ATTRIBUTION.md@@@ -36,8 -36,10 +36,12 @@@ iconography, images or other Adobe asse| `crates/lottie/tests/fixtures/shapes-gradient.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (star, rectangle, gradient fill, dashed stroke, trim paths) | MIT OR Apache-2.0 || `crates/lottie/tests/fixtures/precomp-matte-text.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (precomp, track matte, parented text) | MIT OR Apache-2.0 || `crates/lottie/tests/fixtures/legacy-masks.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (legacy keyframes, masks) | MIT OR Apache-2.0 |+| `crates/svg/tests/fixtures/basic-shapes.svg` | EffectCraft contributors | Original work: hand-written SVG test fixture (basic shapes, groups, transforms) | MIT OR Apache-2.0 |+| `crates/svg/tests/fixtures/paths-gradients.svg` | EffectCraft contributors | Original work: hand-written SVG test fixture (path data, gradients, CSS, use) | MIT OR Apache-2.0 |+ | `crates/model/tests/fixtures/quad.gltf` | EffectCraft contributors | Original work: glTF 2.0 test fixture (textured quad, node hierarchy, translation animation; data URIs) | MIT OR Apache-2.0 |+ | `crates/model/tests/fixtures/quad.glb` | EffectCraft contributors | Original work: binary glTF test fixture (the same quad with its texture in the BIN chunk) | MIT OR Apache-2.0 |+ | `crates/model/tests/fixtures/cube.obj` | EffectCraft contributors | Original work: Wavefront OBJ test fixture (unit cube, two materials) | MIT OR Apache-2.0 |+ | `crates/model/tests/fixtures/cube.mtl` | EffectCraft contributors | Original work: MTL test fixture (materials of cube.obj) | MIT OR Apache-2.0 |## Screenshotsdiff --cc Cargo.lockindex 9b28b8ace,c2468e13b..785988e2a--- a/Cargo.lock+++ b/Cargo.lock@@@ -1196,12 -1197,11 +1197,13 @@@ dependencies ="effectcraft-geom","effectcraft-keyframe","effectcraft-lottie",+ "effectcraft-model","effectcraft-path","effectcraft-project",+ "effectcraft-psd","effectcraft-raster","effectcraft-render",+ "effectcraft-svg","effectcraft-text","effectcraft-time","effectcraft-track",@@@ -1294,10 -1289,7 +1296,11 @@@ dependencies ="effectcraft-expr","effectcraft-media","effectcraft-project",+ "effectcraft-psd",+ "effectcraft-raster",+ "effectcraft-script",+ "effectcraft-svg",+ "effectcraft-time","serde_json",]@@@ -1334,12 -1326,12 +1337,14 @@@ dependencies =name = "effectcraft-media"version = "0.1.0"dependencies = [+ "effectcraft-model","effectcraft-project",+ "effectcraft-psd","effectcraft-raster","effectcraft-render",+ "effectcraft-svg","effectcraft-time",+ "exr","filmcraft-codecs","filmcraft-color","filmcraft-frame",@@@ -1417,18 -1410,21 +1435,33 @@@ dependencies ="web-time",]+ [[package]]+ name = "effectcraft-script"+ version = "0.1.0"+ dependencies = [+ "boa_engine",+ "effectcraft-engine",+ "effectcraft-expr",+ "effectcraft-keyframe",+ "effectcraft-path",+ "effectcraft-project",+ "effectcraft-render",+ "effectcraft-time",+ "serde_json",+ ]++[[package]]+name = "effectcraft-svg"+version = "0.1.0"+dependencies = [+ "effectcraft-geom",+ "effectcraft-path",+ "effectcraft-raster",+ "kurbo",+ "rayon",+ "roxmltree",+]+[[package]]name = "effectcraft-text"version = "0.1.0"diff --cc Cargo.tomlindex dc2ce073c,23fb4f292..22709f60d--- a/Cargo.toml+++ b/Cargo.toml@@@ -35,7 -33,7 +36,8 @@@ effectcraft-engine = { path = "crates/eeffectcraft-host = { path = "crates/host" }effectcraft-ui-egui = { path = "crates/ui-egui" }effectcraft-automation = { path = "crates/automation" }+effectcraft-opusenc = { path = "crates/opusenc" }+ effectcraft-script = { path = "crates/script" }# foundationthiserror = "2"diff --cc crates/engine/Cargo.tomlindex 0830c78d9,a60242bb4..45508a716--- a/crates/engine/Cargo.toml+++ b/crates/engine/Cargo.toml@@@ -21,10 -21,8 +21,11 @@@ effectcraft-text = { workspace = trueeffectcraft-effects = { workspace = true }effectcraft-render = { workspace = true }effectcraft-track = { workspace = true }+ effectcraft-model = { workspace = true }effectcraft-lottie = { workspace = true }+effectcraft-psd = { workspace = true }+kurbo = { workspace = true }+effectcraft-svg = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }thiserror = { workspace = true }diff --cc crates/engine/src/commands/stubs.rsindex f8bca154a,8b244bf68..a15b6851e--- a/crates/engine/src/commands/stubs.rs+++ b/crates/engine/src/commands/stubs.rs@@@ -32,8 -32,7 +32,6 @@@ pub fn specs() -> Vec<CommandSpec>// Mask options not in the mask model yet; pen / vertex editing (timeline milestone).// Time (timeline milestone).stub!("layer.alignVideoToData", "Align Video to Data", ["Layer", "Time"], "{}"),- stub!("layer.environment", "Environment Layer", ["Layer"], "{}"),- stub!("layer.create", "Create", [], "{op}"),stub!("layer.autoTrace", "Auto-trace...", ["Layer"], "{}"),stub!("layer.sceneEditDetection", "Scene Edit Detection...", ["Layer"], "{}"),// Cameras / lights / materials / 3D views (3D milestone).diff --cc crates/engine/src/tests_model3d.rsindex 000000000,51f9173d0..1dcaea405mode 000000,100644..100644--- a/crates/engine/src/tests_model3d.rs+++ b/crates/engine/src/tests_model3d.rs@@@ -1,0 -1,194 +1,195 @@@+ //! Advanced 3D commands: model import → model layers, primitives, the renderer switch with+ //! Geometry Options, Environment Layer and Material commands (undo/redo, serde).++ use std::sync::Arc;++ use effectcraft_keyframe::Value as KV;+ use effectcraft_project::{Footage, FootageKind, ItemId, LayerId, LayerSource, PrimitiveKind, Project, Renderer};+ use effectcraft_render::FootageSource;+ use effectcraft_time::{FrameRate, Tick};+ use serde_json::json;++ use crate::{Importer, Session};++ fn fixture(name: &str) -> String {+ format!("{}/../model/tests/fixtures/{name}", env!("CARGO_MANIFEST_DIR"))+ }++ /// Loads models from disk (what `effectcraft-media` does in the app).+ struct DiskModels;++ impl FootageSource for DiskModels {+ fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option<Arc<effectcraft_raster::Image>> {+ None+ }+ fn model(&self, _: ItemId, f: &Footage) -> Option<Arc<effectcraft_model::Model>> {+ let dir = std::path::Path::new(&f.path).parent()?.to_path_buf();+ let bytes = std::fs::read(&f.path).ok()?;+ effectcraft_model::load(&f.path, &bytes, &|u| std::fs::read(dir.join(u)).ok()).ok().map(Arc::new)+ }+ }++ struct ModelImporter;++ impl Importer for ModelImporter {+ fn probe(&self, path: &str) -> Result<Footage, String> {+ effectcraft_model::format_of(path).ok_or("not a model")?;+ Ok(Footage {+ path: path.into(),+ kind: FootageKind::Model,+ width: 0,+ height: 0,+ pixel_aspect: 1.0,+ frame_rate: FrameRate::FPS_30,+ native_rate: None,+ duration: Tick::ZERO,+ has_video: false,+ has_audio: false,+ alpha: Default::default(),+ premul_color: [0.0; 3],+ loop_count: 1,+ codec: "glTF".into(),+ missing: false,+ sequence: vec![],+ color_profile: None,++ layer: None,+ })+ }+ }++ fn session() -> Session {+ let mut s = Session { footage: Arc::new(DiskModels), importer: Some(Arc::new(ModelImporter)), ..Default::default() };+ s.execute("comp.new", json!({"name": "C", "width": 640, "height": 360, "duration": 2})).unwrap();+ s+ }++ fn layer(s: &Session, id: u64) -> effectcraft_project::Layer {+ s.active_comp().unwrap().layer(LayerId(id)).unwrap().clone()+ }++ #[test]+ fn import_gltf_and_add_model_layer() {+ let mut s = session();+ let r = s.execute("file.import", json!({"paths": [fixture("quad.gltf")]})).unwrap();+ let item = r["items"][0].as_u64().unwrap();+ assert_eq!(s.project.item(ItemId(item)).unwrap().type_name(), "3D Model");+ // Adding the item to the comp makes a model layer (3D, fitted, with the clip popup).+ let id = s.execute("layer.addItem", json!({"item": item})).unwrap()["layer"].as_u64().unwrap();+ let l = layer(&s, id);+ assert_eq!(l.source, LayerSource::Model { item: ItemId(item) });+ assert!(l.switches.three_d);+ assert!(l.props.sub("masks").is_none() && l.props.sub("materialOptions").is_some());+ // Bounds 2 units tall → half the comp height.+ let scale = l.props.prop("geometryOptions/unitScale").unwrap().value.as_f64();+ assert!((scale - 90.0).abs() < 1e-6, "{scale}");+ let anim = l.props.prop("geometryOptions/animation").unwrap();+ assert_eq!(anim.value, KV::Enum(1));+ match &anim.ui {+ effectcraft_project::ParamUi::Popup { options } => assert_eq!(options, &vec!["None".to_string(), "Move".to_string()]),+ u => panic!("{u:?}"),+ }+ s.undo();+ assert!(s.active_comp().unwrap().layers.is_empty());+ s.redo();+ assert_eq!(s.active_comp().unwrap().layers.len(), 1);+ // layer.newModel imports and places in one step.+ let r = s.execute("layer.newModel", json!({"path": fixture("cube.obj")})).unwrap();+ assert!(r["layer"].as_u64().is_some());+ assert!(s.execute("layer.newModel", json!({"path": "/nonexistent/thing.png"})).is_err());+ }++ #[test]+ fn primitives_commands() {+ let mut s = session();+ for k in PrimitiveKind::ALL {+ let r = s.execute("layer.new3dPrimitive", json!({"kind": k.label().to_lowercase()})).unwrap();+ let l = layer(&s, r["layer"].as_u64().unwrap());+ assert_eq!(l.source, LayerSource::Primitive { kind: k });+ assert_eq!(l.name, k.label());+ assert!(l.switches.three_d);+ assert!(l.props.sub("geometryOptions").is_some());+ }+ let r = s+ .execute("layer.newPrimitive", json!({"kind": "sphere", "radius": 80, "segments": 12, "baseColor": [1, 0, 0], "metallic": 100, "castsShadows": "on"}))+ .unwrap();+ let l = layer(&s, r["layer"].as_u64().unwrap());+ assert_eq!(l.props.prop("geometryOptions/radius").unwrap().value.as_f64(), 80.0);+ assert_eq!(l.props.prop("materialOptions/metallic").unwrap().value.as_f64(), 100.0);+ assert_eq!(l.props.prop("materialOptions/castsShadows").unwrap().value, KV::Enum(1));+ assert!(s.execute("layer.newPrimitive", json!({"kind": "teapot"})).is_err());+ let n = s.active_comp().unwrap().layers.len();+ s.undo();+ assert_eq!(s.active_comp().unwrap().layers.len(), n - 1);+ // Menu entries point at the real command now.+ assert!(s.is_enabled("layer.new3dPrimitive"));+ }++ #[test]+ fn renderer_switch_adds_geometry_options() {+ let mut s = session();+ let t = s.execute("layer.newText", json!({"text": "Hi"})).unwrap()["layer"].as_u64().unwrap();+ assert!(layer(&s, t).props.sub("geometryOptions").is_none());+ s.execute("comp.renderer", json!({"renderer": "advanced3d"})).unwrap();+ assert_eq!(s.active_comp().unwrap().renderer, Renderer::Advanced3D);+ let g = layer(&s, t);+ let g = g.props.sub("geometryOptions").unwrap();+ let ids: Vec<&str> = g.children.iter().map(|c| c.match_id()).collect();+ assert_eq!(ids, vec!["bevelStyle", "bevelDepth", "holeBevelDepth", "extrusionDepth"]);+ // New shape layers in the Advanced 3D comp get them too.+ let sh = s.execute("layer.newShape", json!({})).unwrap()["layer"].as_u64().unwrap();+ assert!(layer(&s, sh).props.sub("geometryOptions").is_some());+ assert_eq!(s.execute("comp.renderer", json!({})).unwrap()["renderer"], "advanced3d");+ s.undo();+ s.undo();+ assert_eq!(s.active_comp().unwrap().renderer, Renderer::Classic3D);+ assert!(layer(&s, t).props.sub("geometryOptions").is_none());+ s.redo();+ assert_eq!(s.active_comp().unwrap().renderer, Renderer::Advanced3D);+ assert!(s.execute("comp.renderer", json!({"renderer": "raytraced"})).is_err());+ // Extrusion values are ordinary properties.+ s.execute("prop.set", json!({"layer": t, "path": "geometryOptions/extrusionDepth", "value": 40})).unwrap();+ assert_eq!(layer(&s, t).props.prop("geometryOptions/extrusionDepth").unwrap().value.as_f64(), 40.0);+ }++ #[test]+ fn environment_layer_toggle() {+ let mut s = session();+ let id = s.execute("layer.newSolid", json!({"width": 64, "height": 32})).unwrap()["layer"].as_u64().unwrap();+ s.execute("layer.environment", json!({"layer": id})).unwrap();+ assert!(layer(&s, id).environment && layer(&s, id).switches.three_d);+ s.execute("layer.environment", json!({"layer": id})).unwrap();+ assert!(!layer(&s, id).environment);+ s.undo();+ assert!(layer(&s, id).environment);+ let cam = s.execute("layer.newCamera", json!({})).unwrap()["layer"].as_u64().unwrap();+ assert!(s.execute("layer.environment", json!({"layer": cam})).is_err());+ // An Environment light sources a layer.+ let li = s.execute("layer.newLight", json!({"kind": "Environment"})).unwrap()["layer"].as_u64().unwrap();+ assert!(layer(&s, li).props.prop("lightOptions/source").is_some());+ }++ #[test]+ fn material_commands_and_serde() {+ let mut s = session();+ let a = s.execute("layer.newPrimitive", json!({"kind": "cube"})).unwrap()["layer"].as_u64().unwrap();+ let b = s.execute("layer.newPrimitive", json!({"kind": "torus"})).unwrap()["layer"].as_u64().unwrap();+ s.execute("material.set", json!({"layers": [a], "baseColor": "#3366ff", "roughness": 20, "acceptsLights": false})).unwrap();+ assert_eq!(layer(&s, a).props.prop("materialOptions/roughness").unwrap().value.as_f64(), 20.0);+ assert!(s.execute("material.set", json!({"layers": [a], "castsShadows": "sometimes"})).is_err());+ s.execute("material.duplicateAssign", json!({"layers": [a, b]})).unwrap();+ assert_eq!(layer(&s, b).props.prop("materialOptions/roughness").unwrap().value.as_f64(), 20.0);+ assert_eq!(layer(&s, b).props.prop("materialOptions/acceptsLights").unwrap().value, KV::Bool(false));+ s.execute("material.reset", json!({"layers": [a]})).unwrap();+ assert_eq!(layer(&s, a).props.prop("materialOptions/roughness").unwrap().value.as_f64(), 50.0);+ s.undo();+ assert_eq!(layer(&s, a).props.prop("materialOptions/roughness").unwrap().value.as_f64(), 20.0);+ assert!(s.execute("material.revealSource", json!({"layer": a})).is_err());+ // The project (model and primitive sources, environment flag) round-trips through JSON.+ let r = s.execute("file.import", json!({"paths": [fixture("quad.glb")]})).unwrap();+ let item = r["items"][0].as_u64().unwrap();+ let m = s.execute("layer.addItem", json!({"item": item})).unwrap()["layer"].as_u64().unwrap();+ assert_eq!(s.execute("material.revealSource", json!({"layer": m})).unwrap()["item"], item);+ let json = s.project.to_json();+ let back = Project::from_json(&json).unwrap();+ assert_eq!(&back, &*s.project);+ }diff --cc crates/media/Cargo.tomlindex 6e83c9495,adc3edcef..10998031f--- a/crates/media/Cargo.toml+++ b/crates/media/Cargo.toml@@@ -14,8 -14,7 +14,9 @@@ effectcraft-time = { workspace = trueeffectcraft-project = { workspace = true }effectcraft-raster = { workspace = true }effectcraft-render = { workspace = true }+effectcraft-psd = { workspace = true }+effectcraft-svg = { workspace = true }+ effectcraft-model = { workspace = true }filmcraft-codecs = { workspace = true }filmcraft-media = { workspace = true }filmcraft-frame = { workspace = true }diff --cc crates/media/src/lib.rsindex 246054b3b,862fbfc20..6c67f50f5--- a/crates/media/src/lib.rs+++ b/crates/media/src/lib.rs@@@ -10,11 -10,10 +10,12 @@@//! Video containers (MP4/MOV, Matroska/WebM) and codecs (H.264, HEVC, VP9, AV1, ProRes, DNxHD,//! 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).+//! (PNG, JPEG, GIF, WebP, TIFF, BMP, OpenEXR); Photoshop documents (merged image or one layer) come+//! from `effectcraft-psd` and SVG from `effectcraft-svg` (rasterised at any scale).mod convert;+ pub mod exr_channels;+mod layered;mod pool;mod probe;diff --cc crates/media/src/pool.rsindex b5d94299f,b6632fbac..f604a69af--- a/crates/media/src/pool.rs+++ b/crates/media/src/pool.rs@@@ -359,12 -386,7 +386,12 @@@ impl Innerlet i = Self::frame_index(footage.frame_rate, t, footage.sequence.len() as i64, footage.loop_count);Loc { key: key(&footage.sequence[i as usize], 0), media_t: None }}+ // A layer of a layered still is keyed by its layer index and size mode.+ FootageKind::Still if footage.layer.is_some() => {+ let l = footage.layer.as_ref().map_or(0, |l| 1 + l.index as i64 * 2 + l.layer_size as i64);+ Loc { key: key(&footage.path, l), media_t: None }+ }- FootageKind::Still | FootageKind::Sequence => Loc { key: key(&footage.path, 0), media_t: None },+ FootageKind::Still | FootageKind::Sequence | FootageKind::Model => Loc { key: key(&footage.path, 0), media_t: None },FootageKind::Video | FootageKind::Audio => {let rate = footage.frame_rate;let n = Self::frame_count(rate, footage.duration);@@@ -478,14 -503,18 +511,26 @@@ impl FootageSource for MediaPool}}+ fn vector_frame(&self, _item: ItemId, footage: &Footage, scale: f64) -> Option<Arc<Image>> {+ if footage.missing || !effectcraft_render::is_vector_footage(footage) {+ return None;+ }+ let bytes = self.inner.read(&footage.path).ok()?;+ crate::layered::rasterize_svg(&bytes, scale).map(Arc::new)+ }++ fn aux(&self, _item: ItemId, footage: &Footage, t: Tick) -> Option<Arc<effectcraft_raster::AuxChannels>> {+ if footage.missing || !footage.has_video {+ return None;+ }+ let loc = Inner::locate(footage, t);+ if loc.media_t.is_some() || !loc.key.path.to_ascii_lowercase().ends_with(".exr") {+ return None;+ }+ let path = loc.key.path.clone();+ crate::exr_channels::cached(&path, || self.inner.read(&path).ok())+ }+fn audio(&self, _item: ItemId, footage: &Footage, t: Tick, frames: usize, rate: u32) -> Option<Vec<f32>> {if !footage.has_audio || footage.missing {return None;diff --cc crates/media/src/probe.rsindex 23432cc6b,e97544dbe..a658765c3--- a/crates/media/src/probe.rs+++ b/crates/media/src/probe.rs@@@ -31,11 -35,43 +35,47 @@@ pub fn probe_single(path: impl AsRef<Paprobe_bytes(&path.to_string_lossy(), bytes.into())}+ /// Probe a 3D model (glTF 2.0 / OBJ): a [`FootageKind::Model`] item whose duration is its+ /// longest animation. `resolve` reads sibling resources.+ pub fn probe_model(path: &str, bytes: &[u8], resolve: &dyn Fn(&str) -> Option<Vec<u8>>) -> Result<Footage> {+ let m = effectcraft_model::load(path, bytes, resolve).map_err(|e| MediaError::Decode(format!("{path}: {e}")))?;+ let s = m.summary();+ let dur = s.animations.iter().map(|a| a.1).fold(0.0f64, f64::max);+ let codec = match effectcraft_model::format_of(path) {+ Some("obj") => "OBJ",+ Some("glb") => "GLB",+ _ => "glTF",+ };+ Ok(Footage {+ path: path.to_string(),+ kind: FootageKind::Model,+ width: 0,+ height: 0,+ pixel_aspect: 1.0,+ frame_rate: DEFAULT_SEQUENCE_RATE,+ native_rate: None,+ duration: Tick::from_seconds_f64(dur),+ has_video: false,+ has_audio: false,+ alpha: AlphaMode::Straight,+ premul_color: [0.0; 3],+ loop_count: 1,+ codec: format!("{codec} ({} meshes, {} triangles)", s.meshes, s.triangles),+ missing: false,+ sequence: Vec::new(),+ color_profile: None,++ layer: None,+ })+ }+/// Probe in-memory file contents; `path` names the footage (and is stored as `Footage::path`).pub fn probe_bytes(path: &str, bytes: Arc<[u8]>) -> Result<Footage> {+ if let Some(f) = crate::layered::probe(path, &bytes)? {+ return Ok(f);+ }+ if crate::MODEL_EXTENSIONS.contains(&ext_of(Path::new(path)).as_str()) {+ return probe_model(path, &bytes, &|_| None);+ }if let Ok(fmt) = image::guess_format(&bytes) {return probe_still_bytes(path, &bytes, fmt);}diff --cc crates/render/Cargo.tomlindex cdaa85c16,80e304558..db2fa9dd0--- a/crates/render/Cargo.toml+++ b/crates/render/Cargo.toml@@@ -19,7 -19,7 +19,8 @@@ effectcraft-raster = { workspace = trueffectcraft-path = { workspace = true }effectcraft-text = { workspace = true }effectcraft-effects = { workspace = true }+lz4_flex = { version = "0.11", default-features = false, features = ["std", "safe-encode", "safe-decode", "checked-decode"] }+ effectcraft-model = { workspace = true }kurbo = { workspace = true }rayon = { workspace = true }web-time = { workspace = true }diff --cc crates/render/src/disk_cache.rsindex 1afc9bbb2,000000000..50c3d1d73mode 100644,000000..100644--- a/crates/render/src/disk_cache.rs+++ b/crates/render/src/disk_cache.rs@@@ -1,829 -1,0 +1,831 @@@+//! The persistent disk cache (Settings ▸ Media & Disk Cache ▸ Disk Cache): RAM-preview frames+//! and layer cache entries kept on disk between sessions, like After Effects' disk cache.+//!+//! * Entries are files keyed by a 128-bit content hash (`<folder>/v1/<kind>/<2 hex>/<32 hex>.ecc`):+//! frames by the hash of the composition's content (the comp and everything it uses, footage+//! files' size and modification time included) plus frame, scale and view; layer buffers by+//! the layer cache's content key salted with the project's footage fingerprint. A changed+//! project therefore never reads stale pixels: its keys simply change.+//! * Payloads are LZ4-compressed (`lz4_flex`, MIT): frames as 8-bit premultiplied RGBA, layer+//! buffers as `f32` RGBA with the bytes shuffled into planes (exact, so cached and fresh+//! renders are bit-identical). Every file ends in a checksum; damaged files read as misses and+//! are deleted.+//! * Size limit with least-recently-used eviction. The in-memory index is rebuilt from the+//! folder when the cache opens (file modification times order it), so the cache survives+//! restarts; reads refresh a file's time.+//! * Safe concurrent access: writes go to a unique temporary file that is renamed into place+//! (atomic on every desktop OS), so readers in this or another process never see a partial+//! entry; a missing or damaged file is just a miss. Writes run on a background thread with a+//! bounded queue (a full queue drops the write rather than stalling rendering).++use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{Arc, Condvar, Mutex};++use effectcraft_effects::Buf;+use effectcraft_raster::Image;++/// File format version (part of the folder layout).+const VERSION: &str = "v1";+const MAGIC: &[u8; 4] = b"ECDC";+/// Pending writes before new ones are dropped.++#[cfg(not(target_arch = "wasm32"))]+const QUEUE_LIMIT: usize = 64;++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum Kind {+ Frame,+ Layer,+}++impl Kind {+ fn dir(self) -> &'static str {+ match self {+ Kind::Frame => "frames",+ Kind::Layer => "layers",+ }+ }+ fn tag(self) -> u8 {+ match self {+ Kind::Frame => 1,+ Kind::Layer => 2,+ }+ }+}++/// A cached viewer frame: 8-bit premultiplied RGBA.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Frame8 {+ pub width: u32,+ pub height: u32,+ pub rgba: Vec<u8>,+}++/// Counters for tests, the Info panel and `cache.diskStats`.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct DiskStats {+ pub entries: usize,+ pub bytes: u64,+ pub max_bytes: u64,+ pub hits: u64,+ pub misses: u64,+ pub writes: u64,+ pub evictions: u64,+ pub dropped: u64,+}++struct Meta {+ bytes: u64,+ last_use: u64,+}++#[derive(Default)]+struct Index {+ map: HashMap<(Kind, u128), Meta>,+ total: u64,+ clock: u64,+}+++#[cfg_attr(target_arch = "wasm32", allow(dead_code))]+enum Job {+ Write(Kind, u128, Vec<u8>),+}++struct Queue {+ jobs: std::collections::VecDeque<Job>,+ busy: bool,+}++pub struct DiskCache {+ dir: PathBuf,+ index: Mutex<Index>,+ max_bytes: AtomicU64,+ hits: AtomicU64,+ misses: AtomicU64,+ writes: AtomicU64,+ evictions: AtomicU64,+ dropped: AtomicU64,+ tmp_counter: AtomicU64,+ queue: Arc<(Mutex<Queue>, Condvar)>,+ /// Layer buffers that took less than this to render are not written (ms).+ min_layer_ms: AtomicU64,+}++/// FNV-1a 128-bit (content keys).+#[derive(Clone, Copy)]+pub struct Hash128(u128);++impl Default for Hash128 {+ fn default() -> Self {+ Hash128(0x6c62_272e_07bb_0142_62b8_2175_6295_c58d)+ }+}++impl Hash128 {+ pub fn write(&mut self, bytes: &[u8]) {+ for &b in bytes {+ self.0 ^= b as u128;+ self.0 = self.0.wrapping_mul(0x0000_0000_0100_0000_0000_0000_0000_013b);+ }+ }+ pub fn write_u64(&mut self, v: u64) {+ self.write(&v.to_le_bytes());+ }+ pub fn finish(&self) -> u128 {+ self.0+ }+}++fn checksum(data: &[u8]) -> u64 {+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;+ for &b in data {+ h ^= b as u64;+ h = h.wrapping_mul(0x0000_0100_0000_01b3);+ }+ h+}++/// The platform's default disk cache folder.+pub fn default_folder() -> PathBuf {+ let home = std::env::var_os("HOME").map(PathBuf::from);+ if cfg!(target_os = "macos")+ && let Some(h) = &home+ {+ return h.join("Library/Caches/EffectCraft/Disk Cache");+ }+ if cfg!(windows)+ && let Some(l) = std::env::var_os("LOCALAPPDATA")+ {+ return PathBuf::from(l).join("EffectCraft").join("Disk Cache");+ }+ if let Some(x) = std::env::var_os("XDG_CACHE_HOME") {+ return PathBuf::from(x).join("effectcraft/disk-cache");+ }+ home.map(|h| h.join(".cache/effectcraft/disk-cache")).unwrap_or_else(|| std::env::temp_dir().join("effectcraft-disk-cache"))+}++impl DiskCache {+ /// Open (or create) the cache in `folder`, holding at most `max_bytes`.+ pub fn open(folder: impl AsRef<Path>, max_bytes: u64) -> std::io::Result<Arc<DiskCache>> {+ let dir = folder.as_ref().join(VERSION);+ std::fs::create_dir_all(&dir)?;+ let dc = Arc::new(DiskCache {+ dir,+ index: Mutex::new(Index::default()),+ max_bytes: AtomicU64::new(max_bytes),+ hits: AtomicU64::new(0),+ misses: AtomicU64::new(0),+ writes: AtomicU64::new(0),+ evictions: AtomicU64::new(0),+ dropped: AtomicU64::new(0),+ tmp_counter: AtomicU64::new(0),+ queue: Arc::new((Mutex::new(Queue { jobs: Default::default(), busy: false }), Condvar::new())),+ min_layer_ms: AtomicU64::new(30),+ });+ dc.rescan();+ dc.evict();+ #[cfg(not(target_arch = "wasm32"))]+ {+ let weak = Arc::downgrade(&dc);+ let q = dc.queue.clone();+ std::thread::Builder::new().name("ec-disk-cache".into()).spawn(move || writer(weak, q))?;+ }+ Ok(dc)+ }++ pub fn folder(&self) -> &Path {+ self.dir.parent().unwrap_or(&self.dir)+ }++ /// Rebuild the index from the folder (oldest files first).+ pub fn rescan(&self) {+ let mut found: Vec<(std::time::SystemTime, Kind, u128, u64)> = vec![];+ for kind in [Kind::Frame, Kind::Layer] {+ let Ok(shards) = std::fs::read_dir(self.dir.join(kind.dir())) else { continue };+ for shard in shards.flatten() {+ let Ok(files) = std::fs::read_dir(shard.path()) else { continue };+ for f in files.flatten() {+ let p = f.path();+ let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");+ if name.contains(".tmp") {+ // A writer that died mid-write; old temporaries are removed.+ if f.metadata().and_then(|m| m.modified()).is_ok_and(|t| t.elapsed().is_ok_and(|e| e.as_secs() > 600)) {+ let _ = std::fs::remove_file(&p);+ }+ continue;+ }+ let Some(hex) = name.strip_suffix(".ecc") else { continue };+ let Ok(key) = u128::from_str_radix(hex, 16) else { continue };+ let Ok(md) = f.metadata() else { continue };+ found.push((md.modified().unwrap_or(std::time::UNIX_EPOCH), kind, key, md.len()));+ }+ }+ }+ found.sort_by_key(|e| e.0);+ let mut idx = Index::default();+ for (_, kind, key, bytes) in found {+ idx.clock += 1;+ let clock = idx.clock;+ idx.total += bytes;+ idx.map.insert((kind, key), Meta { bytes, last_use: clock });+ }+ if let Ok(mut g) = self.index.lock() {+ *g = idx;+ }+ }++ fn path(&self, kind: Kind, key: u128) -> PathBuf {+ let hex = format!("{key:032x}");+ self.dir.join(kind.dir()).join(&hex[..2]).join(format!("{hex}.ecc"))+ }++ pub fn max_bytes(&self) -> u64 {+ self.max_bytes.load(Ordering::Relaxed)+ }++ /// Change the size limit (evicts the least recently used entries when shrinking).+ pub fn set_max_bytes(&self, b: u64) {+ self.max_bytes.store(b, Ordering::Relaxed);+ self.evict();+ }++ /// Layer buffers faster to render than this are not worth a disk write.+ pub fn set_min_layer_ms(&self, ms: u64) {+ self.min_layer_ms.store(ms, Ordering::Relaxed);+ }++ pub fn min_layer_ms(&self) -> u64 {+ self.min_layer_ms.load(Ordering::Relaxed)+ }++ pub fn contains(&self, kind: Kind, key: u128) -> bool {+ self.index.lock().is_ok_and(|g| g.map.contains_key(&(kind, key)))+ }++ /// Keys of one kind (unordered).+ pub fn keys(&self, kind: Kind) -> Vec<u128> {+ self.index.lock().map(|g| g.map.keys().filter(|k| k.0 == kind).map(|k| k.1).collect()).unwrap_or_default()+ }++ pub fn stats(&self) -> DiskStats {+ let (entries, bytes) = self.index.lock().map(|g| (g.map.len(), g.total)).unwrap_or_default();+ DiskStats {+ entries,+ bytes,+ max_bytes: self.max_bytes(),+ hits: self.hits.load(Ordering::Relaxed),+ misses: self.misses.load(Ordering::Relaxed),+ writes: self.writes.load(Ordering::Relaxed),+ evictions: self.evictions.load(Ordering::Relaxed),+ dropped: self.dropped.load(Ordering::Relaxed),+ }+ }++ /// Delete every entry (Edit ▸ Purge ▸ All Disk Cache / Empty Disk Cache).+ pub fn clear(&self) {+ self.flush();+ if let Ok(mut g) = self.index.lock() {+ *g = Index::default();+ }+ for kind in [Kind::Frame, Kind::Layer] {+ let _ = std::fs::remove_dir_all(self.dir.join(kind.dir()));+ }+ }++ /// Wait until queued writes are on disk.+ pub fn flush(&self) {+ let (m, cv) = &*self.queue;+ let Ok(mut q) = m.lock() else { return };+ #[cfg(target_arch = "wasm32")]+ {+ q.jobs.clear();+ }+ while !q.jobs.is_empty() || q.busy {+ q = match cv.wait(q) {+ Ok(q) => q,+ Err(_) => return,+ };+ }+ }++ fn read(&self, kind: Kind, key: u128) -> Option<Vec<u8>> {+ if !self.contains(kind, key) {+ self.misses.fetch_add(1, Ordering::Relaxed);+ return None;+ }+ let path = self.path(kind, key);+ let data = std::fs::read(&path).ok();+ let ok = data.as_deref().and_then(|d| verify(d, kind));+ match ok {+ Some(payload) => {+ let payload = payload.to_vec();+ self.hits.fetch_add(1, Ordering::Relaxed);+ if let Ok(mut g) = self.index.lock() {+ g.clock += 1;+ let c = g.clock;+ if let Some(m) = g.map.get_mut(&(kind, key)) {+ m.last_use = c;+ }+ }+ // Persist the recency for the next session (best effort).+ if let Ok(f) = std::fs::File::options().append(true).open(&path) {+ let _ = f.set_modified(std::time::SystemTime::now());+ }+ Some(payload)+ }+ None => {+ self.misses.fetch_add(1, Ordering::Relaxed);+ // Gone (another process evicted it) or damaged: forget it.+ if data.is_some() {+ let _ = std::fs::remove_file(&path);+ }+ self.forget(kind, key);+ None+ }+ }+ }++ fn forget(&self, kind: Kind, key: u128) {+ if let Ok(mut g) = self.index.lock()+ && let Some(m) = g.map.remove(&(kind, key))+ {+ g.total -= m.bytes;+ }+ }++ fn enqueue(&self, kind: Kind, key: u128, payload: Vec<u8>) {+ #[cfg(target_arch = "wasm32")]+ {+ self.write_now(kind, key, &payload);+ }+ #[cfg(not(target_arch = "wasm32"))]+ {+ let (m, cv) = &*self.queue;+ let Ok(mut q) = m.lock() else { return };+ if q.jobs.len() >= QUEUE_LIMIT {+ self.dropped.fetch_add(1, Ordering::Relaxed);+ return;+ }+ q.jobs.push_back(Job::Write(kind, key, payload));+ cv.notify_all();+ }+ }++ /// Write an entry now (atomic rename), then evict down to the limit.+ fn write_now(&self, kind: Kind, key: u128, payload: &[u8]) {+ if self.contains(kind, key) {+ return;+ }+ let path = self.path(kind, key);+ let Some(parent) = path.parent() else { return };+ if std::fs::create_dir_all(parent).is_err() {+ return;+ }+ let mut data = Vec::with_capacity(payload.len() + 16);+ data.extend_from_slice(MAGIC);+ data.push(kind.tag());+ data.extend_from_slice(&[0, 0, 0]);+ data.extend_from_slice(payload);+ let sum = checksum(&data);+ data.extend_from_slice(&sum.to_le_bytes());+ let n = self.tmp_counter.fetch_add(1, Ordering::Relaxed);+ let tmp = parent.join(format!("{key:032x}.tmp.{}.{n}", std::process::id()));+ if std::fs::write(&tmp, &data).is_err() {+ let _ = std::fs::remove_file(&tmp);+ return;+ }+ if std::fs::rename(&tmp, &path).is_err() {+ let _ = std::fs::remove_file(&tmp);+ return;+ }+ self.writes.fetch_add(1, Ordering::Relaxed);+ if let Ok(mut g) = self.index.lock() {+ g.clock += 1;+ let c = g.clock;+ let bytes = data.len() as u64;+ if let Some(old) = g.map.insert((kind, key), Meta { bytes, last_use: c }) {+ g.total -= old.bytes;+ }+ g.total += bytes;+ }+ self.evict();+ }++ /// Remove least recently used entries until the cache fits its limit.+ fn evict(&self) {+ let max = self.max_bytes();+ let victims: Vec<(Kind, u128)> = {+ let Ok(mut g) = self.index.lock() else { return };+ if g.total <= max {+ return;+ }+ let mut by_age: Vec<(u64, (Kind, u128), u64)> = g.map.iter().map(|(k, m)| (m.last_use, *k, m.bytes)).collect();+ by_age.sort_unstable_by_key(|e| e.0);+ let mut out = vec![];+ for (_, k, bytes) in by_age {+ if g.total <= max {+ break;+ }+ g.map.remove(&k);+ g.total -= bytes;+ out.push(k);+ }+ out+ };+ for (kind, key) in victims {+ let _ = std::fs::remove_file(self.path(kind, key));+ self.evictions.fetch_add(1, Ordering::Relaxed);+ }+ }++ // ------------------------------------------------------------ typed entries++ pub fn get_frame(&self, key: u128) -> Option<Frame8> {+ let p = self.read(Kind::Frame, key)?;+ decode_frame(&p)+ }++ /// Queue a frame for writing (8-bit premultiplied RGBA, `width * height * 4` bytes).+ pub fn put_frame(&self, key: u128, width: u32, height: u32, rgba: &[u8]) {+ if self.contains(Kind::Frame, key) || rgba.len() != width as usize * height as usize * 4 {+ return;+ }+ self.enqueue(Kind::Frame, key, encode_frame(width, height, rgba));+ }++ pub fn get_layer(&self, key: u128) -> Option<Buf> {+ let p = self.read(Kind::Layer, key)?;+ decode_layer(&p)+ }++ /// Queue a layer buffer for writing.+ pub fn put_layer(&self, key: u128, buf: &Buf) {+ if self.contains(Kind::Layer, key) {+ return;+ }+ self.enqueue(Kind::Layer, key, encode_layer(buf));+ }++ /// Write a layer buffer synchronously (tests).+ pub fn put_layer_now(&self, key: u128, buf: &Buf) {+ self.write_now(Kind::Layer, key, &encode_layer(buf));+ }++ /// Write a frame synchronously (tests).+ pub fn put_frame_now(&self, key: u128, width: u32, height: u32, rgba: &[u8]) {+ self.write_now(Kind::Frame, key, &encode_frame(width, height, rgba));+ }+}++#[cfg(not(target_arch = "wasm32"))]+fn writer(dc: std::sync::Weak<DiskCache>, q: Arc<(Mutex<Queue>, Condvar)>) {+ let (m, cv) = &*q;+ loop {+ let job = {+ let Ok(mut g) = m.lock() else { return };+ loop {+ if let Some(j) = g.jobs.pop_front() {+ g.busy = true;+ break j;+ }+ if dc.strong_count() == 0 {+ return;+ }+ g = match cv.wait_timeout(g, std::time::Duration::from_millis(500)) {+ Ok((g, _)) => g,+ Err(_) => return,+ };+ }+ };+ let Some(cache) = dc.upgrade() else { return };+ match job {+ Job::Write(kind, key, payload) => cache.write_now(kind, key, &payload),+ }+ drop(cache);+ if let Ok(mut g) = m.lock() {+ g.busy = false;+ }+ cv.notify_all();+ }+}++/// Check magic, kind and checksum; returns the payload.+fn verify(d: &[u8], kind: Kind) -> Option<&[u8]> {+ if d.len() < 16 || &d[..4] != MAGIC || d[4] != kind.tag() {+ return None;+ }+ let (body, sum) = d.split_at(d.len() - 8);+ let mut s = [0u8; 8];+ s.copy_from_slice(sum);+ (checksum(body) == u64::from_le_bytes(s)).then_some(&body[8..])+}++fn encode_frame(w: u32, h: u32, rgba: &[u8]) -> Vec<u8> {+ let mut out = Vec::with_capacity(rgba.len() / 2 + 16);+ out.extend_from_slice(&w.to_le_bytes());+ out.extend_from_slice(&h.to_le_bytes());+ out.extend_from_slice(&lz4_flex::compress_prepend_size(rgba));+ out+}++fn decode_frame(p: &[u8]) -> Option<Frame8> {+ if p.len() < 8 {+ return None;+ }+ let w = u32::from_le_bytes(p[0..4].try_into().ok()?);+ let h = u32::from_le_bytes(p[4..8].try_into().ok()?);+ let rgba = lz4_flex::decompress_size_prepended(&p[8..]).ok()?;+ (rgba.len() == w as usize * h as usize * 4).then_some(Frame8 { width: w, height: h, rgba })+}++fn encode_layer(b: &Buf) -> Vec<u8> {+ let (w, h) = (b.img.width, b.img.height);+ let n = b.img.data.len();+ // Byte planes: all first bytes of every float, then all second bytes… (compresses well).+ let mut planes = vec![0u8; n * 16];+ for (i, px) in b.img.data.iter().enumerate() {+ for c in 0..4 {+ let bytes = px[c].to_le_bytes();+ for (k, byte) in bytes.iter().enumerate() {+ planes[(k * 4 + c) * n + i] = *byte;+ }+ }+ }+ let mut out = Vec::with_capacity(planes.len() / 4 + 40);+ out.extend_from_slice(&w.to_le_bytes());+ out.extend_from_slice(&h.to_le_bytes());+ out.extend_from_slice(&b.offset[0].to_le_bytes());+ out.extend_from_slice(&b.offset[1].to_le_bytes());+ out.extend_from_slice(&b.scale.to_le_bytes());+ out.extend_from_slice(&lz4_flex::compress_prepend_size(&planes));+ out+}++fn decode_layer(p: &[u8]) -> Option<Buf> {+ if p.len() < 32 {+ return None;+ }+ let w = u32::from_le_bytes(p[0..4].try_into().ok()?);+ let h = u32::from_le_bytes(p[4..8].try_into().ok()?);+ let f = |i: usize| -> Option<f64> { Some(f64::from_le_bytes(p[i..i + 8].try_into().ok()?)) };+ let offset = [f(8)?, f(16)?];+ let scale = f(24)?;+ let planes = lz4_flex::decompress_size_prepended(&p[32..]).ok()?;+ let n = w as usize * h as usize;+ if planes.len() != n * 16 {+ return None;+ }+ let mut img = Image::new(w, h);+ for (i, px) in img.data.iter_mut().enumerate() {+ for c in 0..4 {+ let mut bytes = [0u8; 4];+ for (k, byte) in bytes.iter_mut().enumerate() {+ *byte = planes[(k * 4 + c) * n + i];+ }+ px[c] = f32::from_le_bytes(bytes);+ }+ }+ Some(Buf { img, offset, scale })+}++// ---------------------------------------------------------------- content keys++/// Bump when rendering changes in a way that makes old disk entries wrong.+const RENDER_VERSION: &str = "effectcraft-render-1";++fn hash_debug(h: &mut Hash128, v: &impl std::fmt::Debug) {+ h.write(format!("{v:?}").as_bytes());+ h.write(&[0xff]);+}++/// A file's size and modification time (so edited footage gets new keys).+fn file_stamp(h: &mut Hash128, path: &str) {+ if path.is_empty() {+ return;+ }+ if let Ok(md) = std::fs::metadata(path) {+ h.write_u64(md.len());+ if let Ok(t) = md.modified()+ && let Ok(d) = t.duration_since(std::time::UNIX_EPOCH)+ {+ h.write_u64(d.as_nanos() as u64);+ }+ }+}++fn footage_stamp(h: &mut Hash128, f: &effectcraft_project::Footage) {+ file_stamp(h, &f.path);+ for p in &f.sequence {+ file_stamp(h, p);+ }+}++/// Salt for layer cache keys on disk: the renderer version and every footage file's identity+/// (layer keys name footage items, not file contents).+pub fn footage_salt(project: &effectcraft_project::Project) -> u64 {+ let mut h = Hash128::default();+ h.write(RENDER_VERSION.as_bytes());+ for (id, it) in &project.items {+ if let effectcraft_project::ItemKind::Footage(f) = &it.kind {+ h.write_u64(id.0);+ hash_debug(&mut h, f);+ footage_stamp(&mut h, f);+ }+ }+ let v = h.finish();+ (v as u64) ^ ((v >> 64) as u64)+}++/// Content key of a composition's pixels: project render settings, the comp and everything it+/// uses (nested comps, footage, solids, footage files' size and time). With expressions in play+/// (which can read any comp) the whole project counts.+pub fn comp_content_key(project: &effectcraft_project::Project, comp: effectcraft_project::ItemId) -> u128 {+ use effectcraft_project::{ItemKind, LayerSource};+ let mut h = Hash128::default();+ h.write(RENDER_VERSION.as_bytes());+ hash_debug(&mut h, &project.settings);+ let mut seen = std::collections::BTreeSet::new();+ let mut stack = vec![comp];+ let mut expressions = false;+ while let Some(id) = stack.pop() {+ if !seen.insert(id) {+ continue;+ }+ let Some(it) = project.item(id) else { continue };+ if let ItemKind::Comp(c) = &it.kind {+ for l in &c.layers {+ if let LayerSource::Comp { item } | LayerSource::Footage { item } | LayerSource::Solid { item } = l.source {+ stack.push(item);+ }+ if !expressions {+ l.props.walk("", &mut |_, p| expressions |= p.expr.is_some());+ }+ }+ }+ }+ let ids: Vec<effectcraft_project::ItemId> = if expressions { project.items.keys().copied().collect() } else { seen.into_iter().collect() };+ for id in ids {+ let Some(it) = project.item(id) else { continue };+ h.write_u64(id.0);+ h.write(it.name.as_bytes());+ hash_debug(&mut h, &it.kind);+ if let ItemKind::Footage(f) = &it.kind {+ footage_stamp(&mut h, f);+ }+ }+ h.write_u64(comp.0);+ h.finish()+}++/// Disk key of one viewer frame.+pub fn frame_key(content: u128, frame: i64, scale_milli: u32, view: u64) -> u128 {+ let mut h = Hash128::default();+ h.write(&content.to_le_bytes());+ h.write_u64(frame as u64);+ h.write_u64(scale_milli as u64);+ h.write_u64(view);+ h.finish()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn tmpdir(name: &str) -> PathBuf {+ let d = std::env::temp_dir().join(format!("effectcraft-disk-cache-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ d+ }++ fn buf(seed: u32, w: u32, h: u32) -> Buf {+ let mut img = Image::new(w, h);+ for (i, p) in img.data.iter_mut().enumerate() {+ let v = ((i as u32).wrapping_mul(2654435761u32).wrapping_add(seed) % 1000) as f32 / 999.0;+ *p = [v, v * 0.5, 1.0 - v, if i % 7 == 0 { 0.0 } else { 1.0 }];+ }+ Buf { img, offset: [1.5, -2.25], scale: 0.5 }+ }++ #[test]+ fn hit_miss_and_exact_round_trip() {+ let dir = tmpdir("hit");+ let dc = DiskCache::open(&dir, 1 << 30).unwrap();+ assert!(dc.get_layer(42).is_none());+ let b = buf(1, 33, 17);+ dc.put_layer(42, &b);+ dc.flush();+ let back = dc.get_layer(42).unwrap();+ assert_eq!(back.img, b.img);+ assert_eq!((back.offset, back.scale), (b.offset, b.scale));+ let rgba: Vec<u8> = (0..20 * 10 * 4).map(|i| (i % 251) as u8).collect();+ dc.put_frame(7, 20, 10, &rgba);+ dc.flush();+ assert_eq!(dc.get_frame(7).unwrap().rgba, rgba);+ let st = dc.stats();+ assert_eq!((st.entries, st.hits, st.misses, st.writes), (2, 2, 1, 2));+ // Wrong kind is a miss.+ assert!(dc.get_frame(42).is_none());+ }++ #[test]+ fn persists_across_restarts_and_clears() {+ let dir = tmpdir("persist");+ {+ let dc = DiskCache::open(&dir, 1 << 30).unwrap();+ dc.put_layer_now(1, &buf(1, 8, 8));+ dc.put_frame_now(2, 2, 2, &[9; 16]);+ }+ let dc = DiskCache::open(&dir, 1 << 30).unwrap();+ assert_eq!(dc.stats().entries, 2);+ assert!(dc.contains(Kind::Layer, 1) && dc.contains(Kind::Frame, 2));+ assert_eq!(dc.get_frame(2).unwrap().rgba, vec![9; 16]);+ dc.clear();+ assert_eq!(dc.stats().entries, 0);+ assert!(dc.get_frame(2).is_none());+ let again = DiskCache::open(&dir, 1 << 30).unwrap();+ assert_eq!(again.stats().entries, 0);+ }++ #[test]+ fn lru_eviction_respects_the_limit() {+ let dir = tmpdir("lru");+ let dc = DiskCache::open(&dir, u64::MAX).unwrap();+ for k in 0..6u128 {+ dc.put_layer_now(k, &buf(k as u32, 64, 64));+ }+ let per = dc.stats().bytes / 6;+ // Touch 0 so it is the most recently used.+ assert!(dc.get_layer(0).is_some());+ dc.set_max_bytes(per * 3 + per / 2);+ let st = dc.stats();+ assert!(st.bytes <= per * 3 + per / 2, "{st:?}");+ assert_eq!(st.entries, 3);+ assert!(dc.contains(Kind::Layer, 0), "recently used survives");+ assert!(!dc.contains(Kind::Layer, 1) && !dc.contains(Kind::Layer, 2) && !dc.contains(Kind::Layer, 3));+ assert_eq!(st.evictions, 3);+ // Files are really gone.+ let files = walk(&dir);+ assert_eq!(files, 3);+ // New writes keep evicting.+ dc.put_layer_now(99, &buf(9, 64, 64));+ assert!(dc.stats().bytes <= per * 3 + per / 2);+ }++ fn walk(d: &Path) -> usize {+ let mut n = 0;+ if let Ok(rd) = std::fs::read_dir(d) {+ for e in rd.flatten() {+ let p = e.path();+ if p.is_dir() {+ n += walk(&p);+ } else if p.extension().is_some_and(|x| x == "ecc") {+ n += 1;+ }+ }+ }+ n+ }++ #[test]+ fn damaged_files_are_misses() {+ let dir = tmpdir("damaged");+ let dc = DiskCache::open(&dir, 1 << 30).unwrap();+ dc.put_frame_now(5, 4, 4, &[1; 64]);+ let p = dc.path(Kind::Frame, 5);+ let mut d = std::fs::read(&p).unwrap();+ let n = d.len();+ d[n / 2] ^= 0xff;+ std::fs::write(&p, d).unwrap();+ assert!(dc.get_frame(5).is_none());+ assert!(!dc.contains(Kind::Frame, 5));+ assert!(!p.exists());+ }++ #[test]+ fn concurrent_readers_and_writers() {+ let dir = tmpdir("concurrent");+ let a = DiskCache::open(&dir, 1 << 30).unwrap();+ // A second instance on the same folder (another process, in effect).+ let b = DiskCache::open(&dir, 1 << 30).unwrap();+ std::thread::scope(|s| {+ for t in 0..4u32 {+ let (a, b) = (a.clone(), b.clone());+ s.spawn(move || {+ for i in 0..20u128 {+ let k = i % 5;+ let w = if t % 2 == 0 { &a } else { &b };+ w.put_layer_now(k, &buf(k as u32, 16, 16));+ if let Some(x) = w.get_layer(k) {+ assert_eq!(x.img, buf(k as u32, 16, 16).img);+ }+ }+ });+ }+ });+ b.rescan();+ for k in 0..5u128 {+ assert_eq!(b.get_layer(k).unwrap().img, buf(k as u32, 16, 16).img);+ }+ }+}diff --cc crates/ui-egui/src/menus.rsindex 7ebadbf41,8e345d18c..b01bad33a--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@@ -716,7 -716,7 +716,7 @@@ fn file_dialog(app: &mut EffectcraftApplet Some(f) = app.hooks.pick_files.as_ref() else { return Some(Err("no file dialog available (pass `paths`)".into())) };let paths = f(&["mp4", "mov", "m4v", "mkv", "webm", "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "wav", "aif", "aiff", "mp3", "flac",- "ogg", "opus", "svg", "psd", "psb",- "ogg", "opus", "svg", "gltf", "glb", "obj",++ "ogg", "opus", "svg", "psd", "psb", "gltf", "glb", "obj",]);match (paths.is_empty(), key) {(true, _) => None,diff --cc docs/architecture.mdindex 096c75bda,039bce3b8..23c9d7fa9--- a/docs/architecture.md+++ b/docs/architecture.md@@@ -25,12 -22,12 +25,13 @@@ cpal or muda. Everything in L0 to L4, t| L2 | `project` | The document: items, compositions, layers, the property tree, render queue model, `.ecproj` serde || L2 | `text` | Fonts, shaping, layout, per-glyph geometry, text animators and selectors || L2 | `effects` | The effect registry (241 effects) and their CPU implementations |+| L2 | `svg` | SVG import (W3C SVG 1.1/2 static subset: shapes, paths, transforms, `use`, CSS, gradients) and rasterisation at any scale |+ | L2 | `model` | 3D models for Advanced 3D: glTF 2.0 (`.gltf`/`.glb`) and OBJ/MTL import (meshes, PBR metallic-roughness materials and textures, node hierarchy, skins, animations), parametric primitives, extruded/bevelled outline meshes and polygon triangulation || L2 | `track` | Motion tracking: feature/search region point tracking (pyramid normalized cross-correlation, Lucas–Kanade sub-pixel refinement), confidence, homography/affine/similarity solves || L3 | `render` | Evaluation and compositing: sources, masks, effects, transforms, 3D, motion blur, mattes, blending, layer cache, audio mixdown |-| L3 | `media` | Footage decoding (FilmCraft's pure-Rust codecs), image sequences, frame cache |+| L3 | `media` | Footage decoding (FilmCraft's pure-Rust codecs), image sequences, Photoshop and SVG stills, frame cache || L3 | `expr` | The expression engine (JavaScript via boa) with the After Effects object model |-| L3 | `export` | Render queue encoding: H.264, ProRes, PNG/JPEG/TIFF/EXR sequences, GIF, audio |+| L3 | `export` | Render queue encoding: H.264, ProRes, WebM (VP9 + alpha, Opus), PNG/JPEG/TIFF/EXR sequences, GIF, WAV/AIFF || L3 | `gpu` | The GPU compositor and GPU effects on wgpu compute shaders (Metal, Vulkan, Direct3D 12, WebGPU), checked against the CPU renderer || L3 | `lottie` | Lottie JSON / dotLottie import and export (layers, precomps, eased and spatial keyframes, shapes, masks, mattes) with a warnings list for what Lottie cannot express || L4 | `engine` | `Session`: project, undo history, editor state, the command registry and menus |diff --cc docs/parity.mdindex 5d291ca70,f468ba0f4..e16b6adff--- a/docs/parity.md+++ b/docs/parity.md@@@ -74,20 -74,20 +74,20 @@@ library groundwork for mask tracking an| Wall clock, five parallel agents | 42–50 h | **≈ 8–10 h at today's measured pace; ≈ 25 h by the audit's conservative figures** |What is left is concentrated in large systems: Roto Brush and Refine Edge, the 3D camera tracker,- Advanced 3D (models, PBR, image-based lighting), the Warp Stabilizer and mask-tracking UI on top of- the new tracking library, a JavaScript scripting object model,- the missing effect categories (3D Channel, Immersive Video, OCIO), native macOS menus, and- wasm threads.+ the Warp Stabilizer and mask-tracking UI on top of-the new tracking library, SVG/PSD import, WebM, a disk cache,++the new tracking library,+ native macOS menus, and wasm threads. (The missing effect categories, 3D Channel, Immersive Video+ and OCIO, landed in M9.11; the scripting object model in M14.4.)## By area| Area | Weighted parity | Remaining (agent-hours) | Biggest gaps ||---|---|---|---|| Layers | 88% | 4.8 | frame blending, collapse transformations, slip edit |-| Output | 85% | 4.2 | multiple output modules, pre-render, WebM, audio-only |+| Output | 90% | 3.0 | multiple output modules, pre-render (WebM with VP9 alpha + Opus and WAV/AIFF audio-only landed: VP9 is intra-only, Opus CELT-only) || Audio | 85% | 0.5 | audio to keyframes |-| Import | 78% | 4.5 | PSD, SVG as shapes, Lottie |+| Import | 88% | 2.0 | AI/EPS/PDF vector footage, PSD smart objects and 3D layers (PSD as footage/composition/retain layer sizes, SVG footage and Create Shapes from Vector Layer landed) |- | Automation | 76% | 3.3 | a JavaScript scripting object model |+ | Automation | ≈ 90% | 0.8 | scripting covers the documented core object model (AUT-2, M14.4: `app`, project items, comps, layers, properties and keyframes, text documents, markers, render queue, Script Console, `effectcraft-cli script`, MCP `run_script`); still missing: ScriptUI panels/dialogs, `.jsxbin`, sockets || Shapes | 68% | 3.9 | taper and wave strokes (pen tool for shape paths and vertex editing landed in M6.5) || Compositions | 67% | 7.4 | marker dialog, flowchart, Essential Graphics || Animation | 65% | 10.4 | puppet, Wiggler/Smoother/Motion Sketch (motion-path handles and the graph editor transform box landed in M5.8) |@@@ -98,8 -98,8 +98,8 @@@| Interface | 55% | 10.4 | drag-to-dock and floating panels, preferences, native macOS menus (viewer rulers/snapping/channels/snapshots landed in M0.13) || Project | 53% | 8.1 | 8/16/32-bit pipeline and colour management, auto-save, proxies, folder moves || Masks & roto | 52% | 10.0 | Roto Brush, variable-width mask feather points (mask tracking and Mask Interpolation landed in M6.6) |-| Preview | 55% | 6.1 | GPU 3D and adjustment layers, disk cache (region of interest, snapshots, exposure and Fast Previews landed in M0.13) |+| Preview | 62% | 5.0 | GPU 3D and adjustment layers (persistent disk cache with the blue cache bar landed; region of interest, snapshots, exposure and Fast Previews landed in M0.13) |- | Tracking | ≈ 70% | 4.0 | 3D camera tracker, face tracking, Subspace Warp's mesh warp and rolling-shutter repair (point tracker, mask tracking and Warp Stabilizer landed in M6.x / M12.5) |+ | Tracking | ≈ 70% | 4.0 | 3D camera tracker, face tracking and Subspace Warp's mesh warp (Rolling Shutter Repair landed in M9.11; point tracker, mask tracking and Warp Stabilizer landed in M6.x / M12.5) || Paint | 0% | 4.0 | Brush, Clone Stamp, Eraser |## Effects still missingdiff --cc xtask/src/main.rsindex d822a1b96,2e2172e1d..217e055af--- a/xtask/src/main.rs+++ b/xtask/src/main.rs@@@ -34,7 -31,7 +34,8 @@@ const LAYERS: &[(&str, u8)] = &("text", 2),("effects", 2),("track", 2),+ ("svg", 2),+ ("model", 2),("render", 3),("media", 3),("expr", 3),