diff --git a/Cargo.lock b/Cargo.lock index b37d8dc1a..150e848c0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1335,7 +1335,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2 [[package]] name = "craft-exr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e" dependencies = [ "exr", "flate2", @@ -1484,7 +1484,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e1fc4b1376148197c2cfd2381eeb400e2731269a#e1fc4b1376148197c2cfd2381eeb400e2731269a" +source = "git+https://github.com/storytold/craft-libs?rev=fa4741d0bbba8da303dd1bb1a93cbcb78e7747a0#fa4741d0bbba8da303dd1bb1a93cbcb78e7747a0" dependencies = [ "encoding_rs", "flate2", @@ -2100,6 +2100,7 @@ dependencies = [ "image", "kurbo", "log", + "memory-stats", "rayon", "same-file", "serde", @@ -2114,6 +2115,7 @@ name = "effectcraft-export" version = "0.24.1" dependencies = [ "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", + "craft-exr", "craft-gif", "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", @@ -2303,6 +2305,7 @@ dependencies = [ "filmcraft-media", "filmcraft-time", "gif", + "half", "image", "log", "rayon", @@ -2416,6 +2419,7 @@ dependencies = [ "effectcraft-raster", "effectcraft-text", "effectcraft-time", + "half", "kurbo", "log", "lz4_flex", @@ -4385,6 +4389,16 @@ dependencies = [ "autocfg", ] +[[package]] +name = "memory-stats" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c73f5c649995a115e1a0220b35e4df0a1294500477f97a91d0660fb5abeb574a" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + [[package]] name = "minicov" version = "0.3.8" @@ -5135,7 +5149,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.45.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index b5d7cedc0..3be1d787b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,9 +19,9 @@ craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } -craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } +craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3b8e426a260695af840a2cd79a064d40778f939e" } craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } -craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e1fc4b1376148197c2cfd2381eeb400e2731269a" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "fa4741d0bbba8da303dd1bb1a93cbcb78e7747a0" } craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77686f24fe8665c21369f1b593f4d65a973e2a45" } craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } @@ -69,6 +69,8 @@ thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = { version = "1", features = ["float_roundtrip"] } log = "0.4" +# The process's own memory use for the memory accountant (#3301; MIT OR Apache-2.0). +memory-stats = "1.2" # All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md). chrono = { version = "0.4.45", default-features = false, features = ["std"] } rayon = "1" diff --git a/apps/effectcraft-cli/src/main.rs b/apps/effectcraft-cli/src/main.rs index f52401a00..d671a6345 100644 --- a/apps/effectcraft-cli/src/main.rs +++ b/apps/effectcraft-cli/src/main.rs @@ -470,10 +470,11 @@ fn backend(args: &Args, default_demo: bool) -> Result { Ok(b) } -/// A wired session; `--gpu` attaches the GPU compositor (renders then follow the project's -/// renderer setting, GPU Acceleration by default). +/// A wired session whose caches share the budget of the installed RAM (#3941); `--gpu` attaches +/// the GPU compositor (renders then follow the project's renderer setting, GPU Acceleration by +/// default). fn session(args: &Args) -> Result { - let mut s = effectcraft_host::session(); + let mut s = effectcraft_host::headless_session(); if args.flag("--autosave") { let dir = effectcraft_host::config_dir().ok_or_else(|| Failure::Error("--autosave: no config directory; set EFFECTCRAFT_CONFIG_DIR".into()))?; // Read only auto-save settings. Opting in must not change headless rendering or load diff --git a/apps/effectcraft-cli/tests/it/cli.rs b/apps/effectcraft-cli/tests/it/cli.rs index 4510f16c9..3bdda82a7 100644 --- a/apps/effectcraft-cli/tests/it/cli.rs +++ b/apps/effectcraft-cli/tests/it/cli.rs @@ -40,6 +40,21 @@ fn tmp(name: &str) -> PathBuf { canonical(&d).unwrap_or(d).join(name) } +/// #3941: a command-line session reads the system's memory at start, so its caches share the +/// budget of the installed RAM (as in the desktop app), not the budget for unknown RAM. +#[test] +fn the_caches_follow_the_installed_ram() { + let Some(memory) = effectcraft_engine::sysinfo::memory() else { + eprintln!("the system's memory can't be read here: not checked"); + return; + }; + let v = ok_json(&["exec", "help.systemReport", r#"{"quiet":true}"#, "--empty"]); + let reduced = v["caches"]["reduced"].as_bool().unwrap(); + let want = effectcraft_engine::prefs::Prefs::default().memory_budget(Some(memory), reduced).bytes; + let gb = |b: usize| format!("{:.1} GB", b as f64 / (1u64 << 30) as f64); + assert_eq!(v["caches"]["budget"], gb(want), "{v}"); +} + #[test] fn info_and_commands() { let v = ok_json(&["info"]); diff --git a/apps/effectcraft-web/src/diskcache.rs b/apps/effectcraft-web/src/diskcache.rs index 72e9a9e11..6c2c93a8b 100644 --- a/apps/effectcraft-web/src/diskcache.rs +++ b/apps/effectcraft-web/src/diskcache.rs @@ -116,6 +116,7 @@ pub(crate) fn name_of(kind: Kind, key: u128) -> String { Kind::Frame => disk_cache::entry_name(key), Kind::Layer => format!("layers/{}", disk_cache::entry_name(key)), Kind::Matte => format!("mattes/{}", disk_cache::entry_name(key)), + Kind::Plane => format!("planes/{}", disk_cache::entry_name(key)), } } @@ -126,6 +127,9 @@ fn parse_name(name: &str) -> Option<(Kind, u128)> { if let Some(n) = name.strip_prefix("mattes/") { return Some((Kind::Matte, disk_cache::parse_entry_name(n)?)); } + if let Some(n) = name.strip_prefix("planes/") { + return Some((Kind::Plane, disk_cache::parse_entry_name(n)?)); + } Some((Kind::Frame, disk_cache::parse_entry_name(name)?)) } diff --git a/contributors/people.toml b/contributors/people.toml index beb91a413..4f77ce8d1 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -138,3 +138,8 @@ sync_github_name = true [people.andreaaazo] sync_github_name = true + +[people.nicolafalcier99] +real_name = "Nicola Falcier" +display_name = "Nicola Falcier" +sync_github_name = false diff --git a/crates/aep/src/import/effects.rs b/crates/aep/src/import/effects.rs index f92d6c255..7c9be6cd4 100644 --- a/crates/aep/src/import/effects.rs +++ b/crates/aep/src/import/effects.rs @@ -123,6 +123,15 @@ pub(crate) fn import_effects<'f, 'a>( import_param(&fx, map, p, cx, &shown, ParamOut { group: &mut group, refs: &mut *refs, col: &mut *col }); } } + // Channel selection is static, as in After Effects (which can't animate it either): a + // key or an expression there can't come from After Effects; defensively, the first + // value is kept and the rest reported. + for name in effectcraft_effects::migrate::static_channel_params(spec, &mut group) { + col.lose( + LossCategory::Effects, + format!("{}: '{}' effect '{shown}': keyframes or an expression on the channel selection {name} are not imported (it can't be animated), first value used", cx.comp, cx.layer), + ); + } col.imported.effects = col.imported.effects.saturating_add(1); target.children.push(Node::Group(group)); } diff --git a/crates/automation/src/confine.rs b/crates/automation/src/confine.rs index dda0a406c..70586b798 100644 --- a/crates/automation/src/confine.rs +++ b/crates/automation/src/confine.rs @@ -482,6 +482,14 @@ impl FootageSource for ConfinedFootage { fn frame_with(&self, item: ItemId, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve) -> Option> { self.readable(footage).then(|| self.inner.frame_with(item, footage, t, size, float)).flatten() } + /// Some rows of the frame, or `None` when the footage lies outside the allowed roots. + fn frame_rows(&self, item: ItemId, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve, rows: (i64, i64)) -> Option> { + self.readable(footage).then(|| self.inner.frame_rows(item, footage, t, size, float, rows)).flatten() + } + /// Whether the inner source reads only the rows asked for (footage outside the roots: no). + fn reads_rows(&self, footage: &Footage, t: Tick) -> bool { + self.readable(footage) && self.inner.reads_rows(footage, t) + } /// The frame as 8-bit levels, or `None` when the footage lies outside the allowed roots. fn frame8(&self, item: ItemId, footage: &Footage, t: Tick, float: FloatCurve) -> Option> { self.readable(footage).then(|| self.inner.frame8(item, footage, t, float)).flatten() @@ -494,10 +502,34 @@ impl FootageSource for ConfinedFootage { fn aux(&self, item: ItemId, footage: &Footage, t: Tick) -> Option> { self.readable(footage).then(|| self.inner.aux(item, footage, t)).flatten() } + /// The channels `need` reads of the footage frame, or `None` when the footage lies outside the allowed roots. + fn aux_for(&self, item: ItemId, footage: &Footage, t: Tick, need: &effectcraft_engine::raster::channels3d::AuxNeed) -> Option> { + self.readable(footage).then(|| self.inner.aux_for(item, footage, t, need)).flatten() + } + /// The channel names of the footage frame, or `None` when the footage lies outside the allowed roots. + fn aux_names(&self, item: ItemId, footage: &Footage, t: Tick) -> Option> { + self.readable(footage).then(|| self.inner.aux_names(item, footage, t)).flatten() + } /// Forwards the auxiliary footage paths to the inner source. fn set_aux_footage(&self, paths: &[String]) { self.inner.set_aux_footage(paths) } + /// Forwards the localizer settings to the inner source. + fn set_localizer(&self, config: Option) { + self.inner.set_localizer(config) + } + /// The inner source's localizer state. + fn localize_status(&self) -> Option { + self.inner.localize_status() + } + /// Forwards the disk cache to the inner source. + fn set_disk_cache(&self, cache: Option>) { + self.inner.set_disk_cache(cache) + } + /// Forwards what effects read of each auxiliary footage to the inner source. + fn set_aux_needs(&self, needs: &[(String, effectcraft_engine::raster::channels3d::AuxNeed)]) { + self.inner.set_aux_needs(needs) + } /// The 3D model for the footage, or `None` when the footage lies outside the allowed roots. fn model(&self, item: ItemId, footage: &Footage) -> Option> { self.readable(footage).then(|| self.inner.model(item, footage)).flatten() diff --git a/crates/effects/src/channel3d.rs b/crates/effects/src/channel3d.rs index b84b89ebb..c83e0caf5 100644 --- a/crates/effects/src/channel3d.rs +++ b/crates/effects/src/channel3d.rs @@ -13,13 +13,15 @@ //! 3D layer's render. //! //! Aux pixels are looked up nearest-neighbour (IDs must not be interpolated) at each buffer -//! pixel's layer position, so render scale and layer padding are respected. +//! pixel's layer position, so render scale and layer padding are respected. Cryptomatte makes its +//! finished matte from the unscaled channels first and box-filters only that below render scale 1 +//! ([`crypto_plane`]). use std::sync::Arc; use effectcraft_keyframe::Value; use effectcraft_project::ParamUi; -use effectcraft_raster::channels3d::{BACKGROUND_DEPTH, crypto_hash}; +use effectcraft_raster::channels3d::{AuxLookup, BACKGROUND_DEPTH, crypto_hash}; use effectcraft_raster::{AuxChannels, Image, Px, gaussian_blur}; use rayon::prelude::*; @@ -43,12 +45,89 @@ const READS_AUX: [&str; 8] = [ "ec.3d.identifier", ]; +/// The parameters that pick which channels or which Cryptomatte layer an effect reads. They +/// can't be animated (no stopwatch, no keyframes, no expression), as in After Effects: the +/// channels a frame needs are known before it renders, from these values alone (#3271). +const CHANNEL_PARAMS: [(&str, &[&str]); 5] = [ + ("ec.3d.channelextract", &["channel"]), + ("ec.3d.cryptomatte", &["layer", "layerName"]), + ("ec.3d.extractor", &["red", "green", "blue", "alpha"]), + ("ec.3d.idmatte", &["auxChannel"]), + ("ec.3d.identifier", &["channelType"]), +]; + +/// Does parameter `param` of effect `effect` pick the channels it reads ([`CHANNEL_PARAMS`])? +pub fn selects_channels(effect: &str, param: &str) -> bool { + CHANNEL_PARAMS.iter().any(|(e, ps)| *e == effect && ps.contains(¶m)) +} + /// Does effect `id` read its layer's auxiliary channels ([`crate::EffectHost::aux`])? The media /// layer then decodes the footage's picture together with its channels (#474). pub fn reads_aux(id: &str) -> bool { READS_AUX.contains(&id) } +/// What effect `id` reads of its layer's auxiliary channels with `params`, declared before the +/// render (#3271): the lookups it makes on the planes, which the footage resolves against the +/// file's channel names to read only those channels (with the picture's, in one pass). `None` +/// for an effect that doesn't say: all channels are read. +pub fn aux_needs(id: &str, params: &crate::Params) -> Option> { + use effectcraft_raster::channels3d::{COVERAGE_NAMES, DEPTH_NAMES, MATERIAL_ID_NAMES, OBJECT_ID_NAMES}; + let find = AuxLookup::find; + // (as `id_channel` picks) + let ids = |which: u32| if which == 1 { find(&MATERIAL_ID_NAMES) } else { find(&OBJECT_ID_NAMES) }; + Some(match id { + // (as `channel_extract_at` looks them up, fallbacks included) + "ec.3d.channelextract" => match params.e("channel") { + 0 => vec![find(&DEPTH_NAMES)], + 1 => vec![find(&OBJECT_ID_NAMES)], + 7 => vec![find(&MATERIAL_ID_NAMES)], + 4 => vec![find(&COVERAGE_NAMES)], + 2 => vec![find(&["UV.U", "U", "uv.x"]), find(&["UV.V", "V", "uv.y"]), find(&["UV.W", "W", "uv.z"])], + 3 => vec![find(&["N.X", "Normal.X", "normals.x"]), find(&["N.Y", "Normal.Y", "normals.y"]), find(&["N.Z", "Normal.Z", "normals.z"])], + 5 => vec![find(&["BG.R", "Background.R"]), find(&["BG.G", "Background.G"]), find(&["BG.B", "Background.B"])], + _ => vec![find(&["R"]), find(&["G"]), find(&["B"])], + }, + "ec.3d.depthmatte" | "ec.3d.depthoffield" | "ec.3d.fog3d" => vec![find(&DEPTH_NAMES)], + // (Use Coverage can be animated, as in After Effects: its channel is read whatever its + // value, so the need doesn't change over time) + "ec.3d.idmatte" => vec![ids(params.e("auxChannel")), find(&COVERAGE_NAMES)], + "ec.3d.identifier" => vec![ids(params.e("channelType"))], + "ec.3d.cryptomatte" => vec![AuxLookup::Crypto { name: params.s("layerName").to_string(), index: params.e("layer") as usize }], + // (an empty name reads the layer's own channel) + "ec.3d.extractor" => { + // (`(copy)` reads the input's own channel, no footage channel) + ["red", "green", "blue", "alpha"] + .iter() + .map(|k| params.s(k).trim()) + .filter(|n| !n.is_empty() && !is_extractor_copy(n)) + .map(|n| AuxLookup::Name(n.to_string())) + .collect() + } + _ => return None, + }) +} + +/// [`aux_needs`] as an [`AuxNeed`]: what effect `id` reads, nothing for an effect that reads no +/// channels (every effect that does declares its lookups; a test holds them to it). +pub fn aux_need(id: &str, params: &crate::Params) -> effectcraft_raster::channels3d::AuxNeed { + effectcraft_raster::channels3d::AuxNeed::Lookups(aux_needs(id, params).unwrap_or_default()) +} + +/// How far effect `id` with `params` reaches around a pixel of its layer (layer pixels), for +/// reading only the footage rows a region of interest shows (#3271): `Some(0)` for effects whose +/// pixel depends on that pixel alone, `None` for every other (it may read anywhere). +pub fn pixel_margin(id: &str, params: &crate::Params) -> Option { + match id { + "ec.3d.channelextract" | "ec.3d.depthmatte" | "ec.3d.identifier" | "ec.3d.cryptomatte" | "ec.3d.extractor" => Some(0.0), + // (its Gradient Layer reads another layer) + "ec.3d.fog3d" if params.f("layerContribution") <= 0.0 => Some(0.0), + // (Feather blurs the matte) + "ec.3d.idmatte" if params.f("feather") <= 0.0 => Some(0.0), + _ => None, + } +} + fn aux(ctx: &EffectCtx) -> Option> { ctx.env.host?.aux() } @@ -409,67 +488,9 @@ pub fn selection_hashes(sel: &str, manifest: Option<&[(String, u32)]>) -> Vec Vec<(usize, &str)> { - let mut out: Vec<(usize, &str)> = vec![]; - let mut custom = CRYPTO_LAYERS.len(); - for l in layers { - match CRYPTO_LAYERS.iter().position(|w| l == w || l.ends_with(w)) { - Some(i) if !out.iter().any(|(j, _)| *j == i) => out.push((i, l)), - _ => { - out.push((custom, l)); - custom += 1; - } - } - } - out.sort_by_key(|(i, _)| *i); - out -} - -/// What the Layer popup lists for the footage `aux`: the Cryptomatte layers the file has, as -/// (stored value, name), or the three standard ones when there is none (no footage, not an -/// OpenEXR, no Cryptomatte channels). -pub fn crypto_layer_choices(aux: Option<&AuxChannels>) -> Vec<(usize, String)> { - crypto_layer_menu(aux, 0).0 -} - -/// The Layer popup for the stored value `index`: [`crypto_layer_choices`], and the name of the -/// entry the effect reads (the first when `index` names none, as the effect does). -pub fn crypto_layer_menu(aux: Option<&AuxChannels>, index: usize) -> (Vec<(usize, String)>, Option) { - let layers = aux.map(AuxChannels::crypto_layers).unwrap_or_default(); - if layers.is_empty() { - let all: Vec<(usize, String)> = CRYPTO_LAYERS.iter().enumerate().map(|(i, n)| (i, n.to_string())).collect(); - let shown = all.iter().find(|c| c.0 == index).or(all.first()).map(|c| c.1.clone()); - return (all, shown); - } - let slots = crypto_layer_slots(&layers); - let shown = slots.iter().find(|(i, _)| *i == index).map(|(_, n)| n.to_string()).or_else(|| layers.first().cloned()); - (slots.into_iter().map(|(i, n)| (i, n.to_string())).collect(), shown) -} - -/// The Cryptomatte layer the effect reads: the one called `name` when the footage has it (Layer -/// Name, the layer an imported After Effects project names), else [`crypto_layer_name`]'s. -pub fn crypto_layer_named(aux: &AuxChannels, name: &str, index: usize) -> Option { - aux.resolve_crypto_layer_named(name, &crypto_layer_name(aux, index)?) -} - -/// The Cryptomatte layer of `aux` that the stored Layer value `index` reads: its slot's layer, else -/// the first layer (what a file without that layer has always shown). `None` without any. -pub fn crypto_layer_name(aux: &AuxChannels, index: usize) -> Option { - if aux.crypto_layers().is_empty() { - return None; - } - crypto_layer_menu(Some(aux), index).1 -} +/// The Cryptomatte Layer popup and the layer the effect reads (the slot rules live with +/// [`AuxChannels`], so a declared need resolves the layer as the effect does, #3271). +pub use effectcraft_raster::channels3d::{CRYPTO_LAYERS, crypto_layer_choices, crypto_layer_menu, crypto_layer_name, crypto_layer_named}; /// Rank planes as [`AuxChannels::crypto_rank_planes`] returns them. type RankPlanes<'a> = [(&'a [f32], &'a [f32])]; @@ -531,45 +552,259 @@ fn crypto_colors(planes: &RankPlanes, i: usize, memo: &mut IdColorMemo) -> [f32; } /// Per aux pixel of Cryptomatte layer `layer`: the coverage-weighted ID colours (RGB) and the -/// selection's coverage (A), computed in parallel with the rank planes resolved once. The GPU -/// effect uploads this image and samples it per layer pixel. +/// selection's coverage (A), computed in parallel with the rank planes resolved once: the +/// per-pixel reduction the effect's planes ([`crypto_plane`]) are made of. pub fn crypto_aux_image(a: &AuxChannels, layer: &str, sel: &[u32]) -> Image { - crypto_aux_image_with(a, layer, sel, CryptoAux::ColorsAndMatte) -} - -/// What [`crypto_aux_image_with`] computes per aux pixel. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum CryptoAux { - /// The coverage-weighted ID colours (RGB) and the selection's coverage (A). - ColorsAndMatte, - /// Only the selection's coverage (A); the RGB stays 0. - MatteOnly, -} - -impl CryptoAux { - /// What the Cryptomatte effect reads for `display` and Matte Only: the ID colours are only - /// read by the Colors display (0) without Matte Only; Matte, Preview and Matte Only need the - /// matte alone. - pub fn for_display(display: u32, matte_only: bool) -> Self { - if display == 0 && !matte_only { Self::ColorsAndMatte } else { Self::MatteOnly } - } -} - -/// [`crypto_aux_image`]; with [`CryptoAux::MatteOnly`] the RGB stays 0 and only the matte (A) is -/// computed, for the displays that never read the ID colours. -pub fn crypto_aux_image_with(a: &AuxChannels, layer: &str, sel: &[u32], what: CryptoAux) -> Image { let planes = a.crypto_rank_planes(layer); let mut img = Image::new(a.width, a.height); img.data.par_iter_mut().enumerate().for_each_init(IdColorMemo::default, |memo, (i, px)| { - let c = match what { - CryptoAux::ColorsAndMatte => crypto_colors(&planes, i, memo), - CryptoAux::MatteOnly => [0.0; 3], - }; + let c = crypto_colors(&planes, i, memo); *px = [c[0], c[1], c[2], crypto_matte(&planes, sel, i)]; }); img } +/// The Colors display's pixel for coverage-weighted ID colours `c` and matte `m`: the colours, +/// the selection brighter, over alpha 1. The CPU effect and [`crypto_plane`] both make it here. +#[inline] +fn crypto_colors_px(c: [f32; 3], m: f32) -> Px { + let c = c.map(|v| v * (1.0 - 0.5 * m) + 0.5 * m); + [c[0], c[1], c[2], 1.0] +} + +/// What a finished Cryptomatte plane ([`crypto_plane`]) holds. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum CryptoOutput { + /// The selection's coverage, one value per pixel: what Matte, Preview and Matte Only read. + Matte, + /// The Colors display's finished pixel (RGBA, alpha 1). + Colors, +} + +impl CryptoOutput { + /// What the Cryptomatte effect reads for `display` and Matte Only: the ID colours only for + /// the Colors display (0) without Matte Only; Matte, Preview and Matte Only need the matte + /// alone. + pub fn for_display(display: u32, matte_only: bool) -> Self { + if display == 0 && !matte_only { Self::Colors } else { Self::Matte } + } + + /// Values per pixel. + pub fn channels(self) -> usize { + match self { + Self::Matte => 1, + Self::Colors => 4, + } + } +} + +/// A finished Cryptomatte output (#3334): the matte, or the Colors display's pixels, made from +/// the unscaled ID and coverage channels at source resolution and only then, below render +/// scale 1, box-filtered down. ID and coverage channels are never resampled: interpolating +/// hashed IDs makes IDs that don't exist, and picking one rank's pixel loses coverage at edges. +#[derive(Clone, Debug, PartialEq)] +pub struct CryptoPlane { + pub width: u32, + pub height: u32, + /// Plane pixels per layer pixel (as [`AuxChannels::scale`]). + pub scale: f64, + pub output: CryptoOutput, + /// [`CryptoOutput::channels`] values per pixel, row by row. + pub data: Vec, +} + +impl CryptoPlane { + /// The plane pixel at layer point (`lx`, `ly`), with [`AuxChannels::index_at`]'s arithmetic. + pub fn index_at(&self, lx: f64, ly: f64) -> Option { + let x = (lx * self.scale).floor(); + let y = (ly * self.scale).floor(); + if x < 0.0 || y < 0.0 || x >= self.width as f64 || y >= self.height as f64 { + return None; + } + Some(y as usize * self.width as usize + x as usize) + } + + /// The bytes its values take. + pub fn bytes(&self) -> usize { + self.data.len().saturating_mul(std::mem::size_of::()) + } + + /// The effect's pixel for buffer pixel `px` over plane pixel `k` (`None`: outside the aux + /// image, where the matte is 0 and Colors shows black). + fn shade(&self, px: Px, k: Option, display: u32, matte_only: bool, in_alpha: bool) -> Px { + match self.output { + CryptoOutput::Colors => { + let at = k.and_then(|k| k.checked_mul(4)).and_then(|i| self.data.get(i..i.saturating_add(4))); + at.and_then(|c| <[f32; 4]>::try_from(c).ok()).unwrap_or([0.0, 0.0, 0.0, 1.0]) + } + CryptoOutput::Matte => { + let m = k.and_then(|k| self.data.get(k)).copied().unwrap_or(0.0); + crypto_matte_px(px, m, display, matte_only, in_alpha) + } + } + } +} + +/// The effect's pixel for buffer pixel `px` and matte `m` in the displays that read the matte +/// alone (Matte, Preview, and every display with Matte Only). +#[inline] +fn crypto_matte_px(px: Px, m: f32, display: u32, matte_only: bool, in_alpha: bool) -> Px { + if matte_only { + return matte_only_px(m, in_alpha); + } + match display { + // Matte: the layer keyed by the selection (each pixel only reads itself, so no copy). + 1 => px.map(|v| v * m), + // Preview: the layer with the selection tinted. + _ => [px[0] * (1.0 - 0.5 * m) + 0.5 * m * px[3], px[1] * (1.0 - 0.5 * m) + 0.5 * m * px[3], px[2] * (1.0 - 0.5 * m), px[3]], + } +} + +/// The render scale a Cryptomatte plane is box-filtered to ([`crypto_plane`]): `None` at render +/// scale 1 and above, where the plane stays at source resolution and is looked up +/// nearest-neighbour, as every 3D Channel effect looks up its channels. +pub fn crypto_box_scale(render_scale: f64) -> Option { + (render_scale.is_finite() && render_scale > 0.0 && render_scale < 1.0 - 1e-9).then_some(render_scale) +} + +/// The most pixels a box-filtered plane may have (a footage item claiming a far larger size +/// than its file would otherwise allocate a huge one); beyond it the plane stays unscaled. +const MAX_BOX_PIXELS: usize = 1 << 27; + +/// Cryptomatte layer `layer`'s output for selection `sel` (hashes) at `render_scale` (#3334): +/// [`CryptoPlane`]. The matte (or the Colors pixel) is made per aux pixel from every rank's ID +/// and coverage; below render scale 1 the finished plane is box-filtered to the render's pixel +/// grid (coverage is linear, so the filtered matte is exactly the coverage of the larger pixel; +/// the Colors pixels are coloured first and filtered after). +pub fn crypto_plane(a: &AuxChannels, layer: &str, sel: &[u32], output: CryptoOutput, render_scale: f64) -> CryptoPlane { + let src = crypto_source_plane(a, layer, sel, output); + match crypto_box_scale(render_scale) { + Some(s) => crypto_box(src, s), + None => src, + } +} + +/// [`crypto_plane`] at source resolution: one value (or pixel) per aux pixel. +fn crypto_source_plane(a: &AuxChannels, layer: &str, sel: &[u32], output: CryptoOutput) -> CryptoPlane { + let planes = a.crypto_rank_planes(layer); + let n = (a.width as usize).saturating_mul(a.height as usize); + let data = match output { + CryptoOutput::Matte => (0..n).into_par_iter().map(|i| crypto_matte(&planes, sel, i)).collect(), + CryptoOutput::Colors => { + let mut d = vec![0.0f32; n.saturating_mul(4)]; + d.par_chunks_mut(4).enumerate().for_each_init(IdColorMemo::default, |memo, (i, px)| { + let c = crypto_colors_px(crypto_colors(&planes, i, memo), crypto_matte(&planes, sel, i)); + px.copy_from_slice(&c); + }); + d + } + }; + CryptoPlane { width: a.width, height: a.height, scale: a.scale, output, data } +} + +/// For each output pixel of one axis of a box filter by `k` layer pixels: the source pixels it +/// covers and how much of each (layer pixel `x` reads source pixel `⌊(x + ½) · src_scale⌋`, the +/// pixel render scale 1 shows there). +fn box_axis(layer_len: usize, src_len: usize, src_scale: f64, k: f64, out_len: usize) -> Vec> { + (0..out_len) + .map(|j| { + let (x0, x1) = (j as f64 * k, (j as f64 + 1.0) * k); + let last = (x1.ceil() as usize).min(layer_len); + (x0.floor() as usize..last) + .filter_map(|x| { + let w = x1.min(x as f64 + 1.0) - x0.max(x as f64); + let s = ((x as f64 + 0.5) * src_scale).floor(); + (w > 0.0 && s >= 0.0 && s < src_len as f64).then_some((s as usize, w)) + }) + .collect() + }) + .collect() +} + +/// `src` (at source resolution) box-filtered to render scale `s`: each pixel of the result is +/// the mean of the render-scale-1 pixels it covers (the layer's pixels outside the aux image +/// count as 0, as the effect shows them; the Colors display's alpha is 1 everywhere). +fn crypto_box(src: CryptoPlane, s: f64) -> CryptoPlane { + crypto_box_within(src, s, MAX_BOX_PIXELS) +} + +/// The sizes of a box filter of a source plane to a render scale. +struct BoxSize { + /// Layer pixels per output pixel. + k: f64, + /// The layer's width in pixels. + lw: usize, + /// The layer's height in pixels. + lh: usize, + /// The result's width in pixels. + dw: usize, + /// The result's height in pixels. + dh: usize, +} + +/// [`BoxSize`] of a filter of a `width` × `height` source at `scale` to render scale `s` whose +/// result has at most `max_out` pixels, or `None` where the plane stays unscaled. The filter +/// visits every layer pixel and may visit at most four per source pixel, so a footage item +/// claiming a far larger size than its file is left unscaled. +fn box_size(width: u32, height: u32, scale: f64, s: f64, max_out: usize) -> Option { + if !(scale.is_finite() && scale > 0.0) { + return None; + } + // (layer pixels per output pixel; a whole number when it is one within rounding, so a + // third resolution averages exactly three by three pixels) + let k = 1.0 / s; + let k = if (k - k.round()).abs() < 1e-9 * k { k.round() } else { k }; + let (lw, lh) = ((width as f64 / scale).ceil(), (height as f64 / scale).ceil()); + let (dw, dh) = ((lw / k * (1.0 - 1e-12)).ceil(), (lh / k * (1.0 - 1e-12)).ceil()); + let work = (width as usize).saturating_mul(height as usize).saturating_mul(4); + let fits = |v: f64| v.is_finite() && v >= 0.0 && v <= work as f64; + if !(fits(lw) && fits(lh) && fits(dw) && fits(dh)) || (dw * dh) as usize > work.min(max_out) || (lw * lh) as usize > work { + return None; + } + Some(BoxSize { k, lw: lw as usize, lh: lh as usize, dw: dw as usize, dh: dh as usize }) +} + +/// [`crypto_box`] with a result of at most `max_out` pixels. The filter's work, a visit of every +/// layer pixel, is bounded by the source's size alone, which is in memory already: a 16K source +/// at half resolution is filtered, not looked up nearest-neighbour. +fn crypto_box_within(src: CryptoPlane, s: f64, max_out: usize) -> CryptoPlane { + let Some(BoxSize { k, lw, lh, dw, dh }) = box_size(src.width, src.height, src.scale, s, max_out) else { + return src; + }; + let ch = src.output.channels(); + let n = dw.saturating_mul(dh).saturating_mul(ch); + let mut data = Vec::new(); + if data.try_reserve_exact(n).is_err() { + return src; + } + data.resize(n, 0.0f32); + let xs = box_axis(lw, src.width as usize, src.scale, k, dw); + let ys = box_axis(lh, src.height as usize, src.scale, k, dh); + let (sw, area) = (src.width as usize, k * k); + data.par_chunks_mut((dw * ch).max(1)).zip(ys.par_iter()).for_each(|(row, ty)| { + for (dx, tx) in xs.iter().enumerate() { + for c in 0..ch { + let mut sum = 0.0f64; + for &(sy, wy) in ty { + for &(sx, wx) in tx { + let v = src.data.get((sy * sw + sx) * ch + c).copied().unwrap_or(0.0); + sum += wy * wx * v as f64; + } + } + if let Some(o) = row.get_mut(dx * ch + c) { + *o = (sum / area) as f32; + } + } + } + }); + if src.output == CryptoOutput::Colors { + for px in data.as_chunks_mut::<4>().0 { + px[3] = 1.0; + } + } + CryptoPlane { width: dw as u32, height: dh as u32, scale: s, output: src.output, data } +} + /// The hidden switch that keeps Matte Only as projects saved before #3127 render it: the matte in /// RGB and alpha. Fresh instances have it off (the matte in RGB over alpha 1, as After Effects' /// Cryptomatte plug-in shows Matte Only); `migrate::legacy_default` turns it on for older saves. @@ -585,38 +820,46 @@ pub fn matte_only_px(m: f32, in_alpha: bool) -> Px { fn cryptomatte(ctx: &EffectCtx, mut b: Buf) -> Buf { let Some(a) = aux(ctx) else { return b }; let Some(layer) = crypto_layer_named(&a, ctx.params.s("layerName"), ctx.params.e("layer") as usize) else { return b }; - let manifest = a.manifests.iter().find(|(l, _)| *l == layer).map(|(_, m)| m.as_slice()); + let manifest = a.manifest(&layer); let sel = selection_hashes(ctx.params.s("selection"), manifest); - let idx = index_map(&b, &a); let display = ctx.params.e("display"); let matte_only = ctx.params.b("matteOnly"); let in_alpha = ctx.params.b(MATTE_ONLY_IN_ALPHA); + // Below render scale 1: the finished matte (or Colors pixels) box-filtered down (#3334), + // looked up per buffer pixel; the ID channels are never resampled. + if crypto_box_scale(b.scale).is_some() { + let plane = crypto_plane(&a, &layer, &sel, CryptoOutput::for_display(display, matte_only), b.scale); + let idx = crypto_index_map(&b, &plane); + b.img.data.par_iter_mut().zip(idx.par_iter()).for_each(|(px, &k)| *px = plane.shade(*px, k, display, matte_only, in_alpha)); + return b; + } + let idx = index_map(&b, &a); let planes = a.crypto_rank_planes(&layer); b.img.data.par_iter_mut().zip(idx.par_iter()).for_each_init(IdColorMemo::default, |memo, (px, &k)| { let m = k.map_or(0.0, |k| crypto_matte(&planes, &sel, k)); - if matte_only { - *px = matte_only_px(m, in_alpha); - return; - } - *px = match display { + *px = if display == 0 && !matte_only { // Colors: coverage-weighted ID colours (the spec's preview), selection brighter. - 0 => { - let c = k.map_or([0.0; 3], |k| crypto_colors(&planes, k, memo)); - let c = c.map(|v| v * (1.0 - 0.5 * m) + 0.5 * m); - [c[0], c[1], c[2], 1.0] - } - // Matte: the layer keyed by the selection (each pixel only reads itself, so no copy). - 1 => px.map(|v| v * m), - // Preview: the layer with the selection tinted. - _ => { - let s = *px; - [s[0] * (1.0 - 0.5 * m) + 0.5 * m * s[3], s[1] * (1.0 - 0.5 * m) + 0.5 * m * s[3], s[2] * (1.0 - 0.5 * m), s[3]] - } + crypto_colors_px(k.map_or([0.0; 3], |k| crypto_colors(&planes, k, memo)), m) + } else { + crypto_matte_px(*px, m, display, matte_only, in_alpha) }; }); b } +/// The [`CryptoPlane`] pixel for each buffer pixel (None outside the aux image), looked up as +/// [`index_map`] looks up the aux. +fn crypto_index_map(b: &Buf, plane: &CryptoPlane) -> Vec> { + let (w, h) = (b.img.width as usize, b.img.height as usize); + (0..w * h) + .into_par_iter() + .map(|i| { + let [x, y] = aux_point(b.scale, b.offset, [(i % w) as f64 + 0.5, (i / w) as f64 + 0.5]); + plane.index_at(x, y) + }) + .collect() +} + // ---------------------------------------------------------------- EXtractoR /// EXtractoR's channel name for After Effects' `(copy)`: the effect input's own channel of the @@ -825,3 +1068,32 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests; + +#[cfg(test)] +mod aux_need_tests { + /// #3271: ID Matte's Use Coverage can be animated (as in After Effects): the coverage channel + /// is read whether it is on or off, so what a frame reads doesn't depend on it. + #[test] + fn id_matte_reads_coverage_either_way() { + let spec = crate::find("ec.3d.idmatte").expect("an effect"); + let mut params = crate::Params { values: spec.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect() }; + let off = super::aux_needs("ec.3d.idmatte", ¶ms); + params.values.insert("useCoverage".into(), effectcraft_keyframe::Value::Bool(true)); + let on = super::aux_needs("ec.3d.idmatte", ¶ms); + assert_eq!(off, on); + assert_eq!(on.map(|v| v.len()), Some(2), "the ID channel and the coverage channel"); + assert!(!super::selects_channels("ec.3d.idmatte", "useCoverage"), "animatable"); + assert!(super::selects_channels("ec.3d.idmatte", "auxChannel"), "static"); + } + + /// #3271: every effect that reads its layer's channels says which (else a frame would read + /// all of them, or none). + #[test] + fn every_channel_effect_declares_what_it_reads() { + for id in super::READS_AUX { + let spec = crate::find(id).expect("an effect"); + let params = crate::Params { values: spec.params.iter().map(|p| (p.id.to_string(), p.default.clone())).collect() }; + assert!(super::aux_needs(id, ¶ms).is_some(), "{id}"); + } + } +} diff --git a/crates/effects/src/channel3d/tests.rs b/crates/effects/src/channel3d/tests.rs index c1fa21711..7dae546b6 100644 --- a/crates/effects/src/channel3d/tests.rs +++ b/crates/effects/src/channel3d/tests.rs @@ -223,31 +223,200 @@ fn crypto_aux_image_is_bit_exact_on_edge_values() { } } -/// Without the ID colours the matte (A) is bit-identical and the RGB is 0, on the edge values. +/// #3334: at render scale 1 the matte plane is the per-pixel reduction's matte bit for bit, and +/// the Colors plane is the Colors display's pixel made from it, on the edge values. #[test] -fn crypto_aux_image_without_colors_keeps_the_matte() { +fn the_source_resolution_planes_are_the_per_pixel_reduction() { let a = edge_aux(true); let sel = edge_selection(); let full = crypto_aux_image(&a, "CryptoObject", &sel); - let matte = crypto_aux_image_with(&a, "CryptoObject", &sel, CryptoAux::MatteOnly); - for (f, m) in full.data.iter().zip(&matte.data) { - assert_eq!(f[3].to_bits(), m[3].to_bits()); - assert_eq!(m[..3], [0.0; 3]); + let matte = crypto_plane(&a, "CryptoObject", &sel, CryptoOutput::Matte, 1.0); + let colors = crypto_plane(&a, "CryptoObject", &sel, CryptoOutput::Colors, 1.0); + assert_eq!((matte.width, matte.height, matte.scale), (a.width, a.height, a.scale)); + assert_eq!(matte.data.len(), 12, "one value per aux pixel"); + for (i, f) in full.data.iter().enumerate() { + assert_eq!(f[3].to_bits(), matte.data[i].to_bits(), "matte {i}"); + let want = crypto_colors_px([f[0], f[1], f[2]], f[3]); + assert_eq!(want.map(f32::to_bits), [0, 1, 2, 3].map(|c| colors.data[i * 4 + c].to_bits()), "colors {i}"); } } /// Only the Colors display without Matte Only reads the ID colours. #[test] -fn crypto_aux_for_display_reads_colors_only_for_the_colors_display() { - assert_eq!(CryptoAux::for_display(0, false), CryptoAux::ColorsAndMatte); - assert_eq!(CryptoAux::for_display(0, true), CryptoAux::MatteOnly); +fn crypto_output_reads_colors_only_for_the_colors_display() { + assert_eq!(CryptoOutput::for_display(0, false), CryptoOutput::Colors); + assert_eq!(CryptoOutput::for_display(0, true), CryptoOutput::Matte); for display in [1, 2, 3, u32::MAX] { for matte_only in [false, true] { - assert_eq!(CryptoAux::for_display(display, matte_only), CryptoAux::MatteOnly, "display {display}"); + assert_eq!(CryptoOutput::for_display(display, matte_only), CryptoOutput::Matte, "display {display}"); } } } +/// A 9×7 two-rank Cryptomatte layer (`aux_scale` aux pixels per layer pixel) whose objects +/// share their edge pixels: on rank 00 "cube" (60 %) or "sphere", on rank 01 the other one +/// (the remaining coverage) along the edges, so a pixel there belongs to two IDs. +fn shared_edges(aux_scale: f64) -> AuxChannels { + let (lw, lh) = (9usize, 7usize); + let (w, h) = ((lw as f64 * aux_scale) as usize, (lh as f64 * aux_scale) as usize); + let (cube, sphere) = (crypto_float(crypto_hash("cube")), crypto_float(crypto_hash("sphere"))); + let mut a = AuxChannels::new(w as u32, h as u32, aux_scale); + let mut ch: Vec> = vec![vec![0.0; w * h]; 4]; + for y in 0..h { + for x in 0..w { + let i = y * w + x; + let (lx, ly) = (x as f64 / aux_scale, y as f64 / aux_scale); + let d = lx + 0.6 * ly - 6.0; + let edge = d.abs() < 1.5; + let (first, second) = if d < 0.0 { (cube, sphere) } else { (sphere, cube) }; + let c = if edge { 0.6 + 0.1 * ((x + y) % 3) as f32 } else { 1.0 }; + ch[0][i] = first; + ch[1][i] = c; + ch[2][i] = if edge { second } else { 0.0 }; + ch[3][i] = if edge { 1.0 - c } else { 0.0 }; + } + } + a.channels = ["00.R", "00.G", "00.B", "00.A"].iter().zip(ch).map(|(n, v)| (format!("CryptoObject{n}"), v)).collect(); + a.manifests = vec![("CryptoObject".into(), vec![("cube".into(), crypto_hash("cube")), ("sphere".into(), crypto_hash("sphere"))])]; + a +} + +/// Run the Cryptomatte effect on a buffer of the 9×7 layer at render scale 1 / `k` over `a`. +fn crypto_run(a: &AuxChannels, vals: &[(&str, Value)], k: u32) -> Image { + let host = AuxHost(Arc::new(a.clone())); + let (w, h, scale) = (9u32.div_ceil(k), 7u32.div_ceil(k), 1.0 / k as f64); + let spec = crate::find("ec.3d.cryptomatte").unwrap(); + let mut params = crate::Params { values: spec.params.iter().map(|ps| (ps.id.to_string(), crate::default_value(ps, [9.0, 7.0]))).collect() }; + for (k, v) in vals { + params.values.insert(k.to_string(), v.clone()); + } + let ctx = EffectCtx { + params: ¶ms, + time: 0.0, + layer_size: [9.0, 7.0], + seed: 0, + adjustment: false, + env: EffectEnv { host: Some(&host), ..Default::default() }, + }; + (spec.render)(&ctx, Buf { img: Image::filled(w, h, [0.8, 0.6, 0.4, 1.0]), offset: [0.0; 2], scale }).img +} + +/// The full-resolution output box-filtered by `k`, summed in the plane's order (rows, then +/// columns), the pixels past the layer's edge 0. Alpha is 1: the outputs compared (Colors, and +/// Matte Only with the matte in RGB) are opaque. +fn boxed(full: &Image, k: u32) -> Image { + let (w, h) = (full.width.div_ceil(k), full.height.div_ceil(k)); + let mut out = Image::new(w, h); + for y in 0..h { + for x in 0..w { + let mut px = [0.0f32; 4]; + for (c, o) in px.iter_mut().enumerate() { + let mut sum = 0.0f64; + for sy in y * k..y * k + k { + for sx in x * k..x * k + k { + let v = if sx < full.width && sy < full.height { full.get(sx as i64, sy as i64)[c] } else { 0.0 }; + sum += v as f64; + } + } + *o = (sum / (k * k) as f64) as f32; + } + px[3] = 1.0; + out.set(x, y, px); + } + } + out +} + +/// #3334: below render scale 1 the output is the full-resolution output box-filtered down, bit +/// for bit, at half and third resolution, for the matte (Matte Only) and the Colors display, on +/// edges where two IDs share a pixel and with the aux at 1× and 2× the layer's resolution. +#[test] +fn reduced_resolution_is_the_full_resolution_output_box_filtered() { + for aux_scale in [1.0, 2.0] { + let a = shared_edges(aux_scale); + for vals in [ + vec![("selection", Value::Str("cube".into())), ("matteOnly", Value::Bool(true))], + vec![("selection", Value::Str("cube, sphere".into())), ("matteOnly", Value::Bool(true))], + vec![("selection", Value::Str("sphere".into())), ("display", Value::Enum(0)), ("matteOnly", Value::Bool(false))], + ] { + let full = crypto_run(&a, &vals, 1); + for k in [2u32, 3] { + let got = crypto_run(&a, &vals, k); + let want = boxed(&full, k); + assert_eq!((got.width, got.height), (want.width, want.height)); + for (i, (g, w)) in got.data.iter().zip(&want.data).enumerate() { + assert_eq!(g.map(f32::to_bits), w.map(f32::to_bits), "aux {aux_scale} {vals:?} 1/{k}: pixel {i}: {g:?} vs {w:?}"); + } + } + } + // The edges hold partial coverage: a filtered pixel there is neither 0 nor 1. + let half = crypto_run(&a, &[("selection", Value::Str("cube".into())), ("matteOnly", Value::Bool(true))], 2); + assert!(half.data.iter().any(|p| p[0] > 0.05 && p[0] < 0.95), "{:?}", half.data); + } +} + +/// #3334: the ID channels never go through a resampler. The selection is the ID an +/// interpolation of the two IDs would make where they meet (their values' mean: a 2 × 2 box or +/// a bilinear sample half way between them; and their bits' midpoint): no pixel of the layer +/// has it, so its matte is 0 at every render scale, in the effect and in the plane the GPU +/// uploads. (That the planes are the per-pixel reduction is +/// `the_source_resolution_planes_are_the_per_pixel_reduction`.) +#[test] +fn ids_are_never_resampled() { + let (cube, sphere) = (crypto_float(crypto_hash("cube")), crypto_float(crypto_hash("sphere"))); + let mid_bits = ((cube.to_bits() as u64 + sphere.to_bits() as u64) / 2) as u32; + let mean = (cube + sphere) * 0.5; + for made in [mid_bits, mean.to_bits()] { + assert!(made != cube.to_bits() && made != sphere.to_bits()); + for aux_scale in [1.0, 2.0] { + let a = shared_edges(aux_scale); + for k in [1u32, 2, 3, 4] { + let sel = Value::Str(format!("<{made:08x}>")); + let out = crypto_run(&a, &[("selection", sel), ("matteOnly", Value::Bool(true))], k); + assert!(out.data.iter().all(|p| p[0] == 0.0), "aux {aux_scale} 1/{k}: an ID no pixel has was selected"); + // (and the plane the GPU uploads: the matte alone) + let plane = crypto_plane(&a, "CryptoObject", &[made], CryptoOutput::Matte, 1.0 / k as f64); + assert!(plane.data.iter().all(|m| *m == 0.0)); + } + } + } +} + +/// #3334: a hostile render scale or aux scale never allocates a huge plane or panics. +#[test] +fn box_filter_survives_hostile_scales() { + let a = shared_edges(1.0); + for s in [0.0, -1.0, f64::NAN, f64::INFINITY, 1e-12, 1.0, 4.0] { + let p = crypto_plane(&a, "CryptoObject", &[crypto_hash("cube")], CryptoOutput::Matte, s); + assert!(p.data.len() <= 9 * 7, "scale {s}: {}", p.data.len()); + } + let mut tiny = shared_edges(1.0); + tiny.scale = 1e-9; + let p = crypto_plane(&tiny, "CryptoObject", &[crypto_hash("cube")], CryptoOutput::Matte, 0.5); + assert_eq!(p.data.len(), 9 * 7, "too large a layer: left unscaled"); + // A layer claiming 1000 × its file's size at a tiny render scale: few output pixels, but the + // filter would visit 6.3e7 layer pixels; left unscaled, at once. + tiny.scale = 1e-3; + let p = crypto_plane(&tiny, "CryptoObject", &[crypto_hash("cube")], CryptoOutput::Matte, 1e-3); + assert_eq!(p.data.len(), 9 * 7); + assert!(box_size(9, 7, 1e-3, 1e-3, MAX_BOX_PIXELS).is_none(), "the filter's work is refused, not done"); + assert!(box_size(9, 7, 1.0, 0.5, MAX_BOX_PIXELS).is_some(), "an ordinary half resolution is filtered"); +} + +/// #3301 review: a source whose layer has more pixels than a filtered plane may have (a 16K +/// file at half resolution) is still filtered when the result fits: alternating selected and +/// unselected rows give 0.5, not the 0 of a nearest-neighbour lookup of every second row. +#[test] +fn a_large_source_is_filtered_when_its_result_fits() { + let (w, h) = (8usize, 8usize); + let data = (0..w * h).map(|i| if (i / w) % 2 == 0 { 1.0 } else { 0.0 }).collect(); + let src = CryptoPlane { width: w as u32, height: h as u32, scale: 1.0, output: CryptoOutput::Matte, data }; + // (at most 16 output pixels: the 4 × 4 result fits, the 64 layer pixels don't) + let p = crypto_box_within(src, 0.5, 16); + assert_eq!((p.width, p.height), (4, 4), "filtered to half resolution"); + assert!(p.data.iter().all(|m| (m - 0.5).abs() < 1e-6), "{:?}", p.data); +} + /// The CPU effect on a 20×10 layer over the 6×2 edge aux: pixels inside the aux area match /// the lookup by name bit for bit in every display mode, pixels outside it (no aux index) /// get an empty matte and no ID colour. @@ -660,3 +829,72 @@ fn reads_aux_names_the_effects_that_read_channels() { } assert!(READS_AUX.iter().all(|id| specs().iter().any(|s| s.id == *id)), "every listed effect exists"); } + +/// [`scene`] with more channels: IDs, coverage, normals, UVs, a background, a colour layer and +/// two more Cryptomatte layers, each with its own values. +fn rich_scene() -> AuxHost { + let mut a = (*scene().0).clone(); + let n = (a.width * a.height) as usize; + let plane = |k: usize| (0..n).map(|i| ((i * 7 + k * 13) % 23) as f32 / 11.0 - 0.5).collect::>(); + let (ha, hc) = (crypto_hash("asset"), crypto_hash("custom")); + let ids = |h: u32| (0..n).map(|i| if i % 3 == 0 { crypto_float(h) } else { 0.0 }).collect::>(); + let names = ["MaterialID", "Coverage", "N.X", "N.Y", "N.Z", "UV.U", "UV.V", "BG.R", "BG.G", "BG.B", "diffuse.R", "diffuse.G", "diffuse.B"]; + for (k, name) in names.iter().enumerate() { + a.channels.push((name.to_string(), plane(k))); + } + a.channels.push(("A.CryptoAsset00.R".into(), ids(ha))); + a.channels.push(("A.CryptoAsset00.G".into(), plane(40))); + a.channels.push(("zz.Custom00.R".into(), ids(hc))); + a.channels.push(("zz.Custom00.G".into(), plane(41))); + a.manifests.push(("A.CryptoAsset".into(), vec![("asset".into(), ha)])); + AuxHost(Arc::new(a)) +} + +/// The parameters [`run_fx`] gives effect `id` with `vals` (on [`img`]). +fn params_of(id: &str, vals: &[(&str, Value)]) -> crate::Params { + let s = crate::find(id).expect("an effect"); + let mut p = crate::Params { values: s.params.iter().map(|p| (p.id.to_string(), crate::default_value(p, [20.0, 10.0]))).collect() }; + for (k, v) in vals { + p.values.insert(k.to_string(), v.clone()); + } + p +} + +/// #3271: each 3D Channel effect, given only the channels it declares ([`aux_needs`], with every +/// channel name listed), renders bit for bit what it renders with all channels, and reads fewer. +#[test] +fn declared_aux_needs_render_as_all_channels() { + use effectcraft_raster::channels3d::AuxNeed; + let full = rich_scene(); + let mut names = (*full.0).clone(); + for (_, p) in &mut names.channels { + p.clear(); + } + let s = |v: &str| Value::Str(v.into()); + let mut cases: Vec<(&str, Vec<(&str, Value)>)> = (0..8).map(|k| ("ec.3d.channelextract", vec![("channel", Value::Enum(k))])).collect(); + cases.extend([ + ("ec.3d.depthmatte", vec![("depth", num(300.0))]), + ("ec.3d.depthoffield", vec![("focalPlane", num(300.0)), ("maximumRadius", num(4.0))]), + ("ec.3d.fog3d", vec![]), + ("ec.3d.idmatte", vec![("idSelection", num(1.0))]), + ("ec.3d.idmatte", vec![("auxChannel", Value::Enum(1)), ("useCoverage", Value::Bool(true))]), + ("ec.3d.identifier", vec![("id", num(2.0))]), + ("ec.3d.identifier", vec![("channelType", Value::Enum(1)), ("display", Value::Enum(3))]), + ("ec.3d.cryptomatte", vec![("selection", s("left")), ("display", Value::Enum(0))]), + ("ec.3d.cryptomatte", vec![("layer", Value::Enum(3)), ("display", Value::Enum(1)), ("selection", s("<*>"))]), + ("ec.3d.cryptomatte", vec![("layerName", s("A.CryptoAsset")), ("selection", s("asset"))]), + ("ec.3d.extractor", vec![("red", s("diffuse.R")), ("green", s(" N.X ")), ("blue", s("")), ("alpha", s("Coverage"))]), + ]); + let bits = |i: &Image| i.data.iter().flat_map(|p| p.map(f32::to_bits)).collect::>(); + for (id, vals) in cases { + let need = aux_needs(id, ¶ms_of(id, &vals)).map_or(AuxNeed::All, AuxNeed::Lookups); + let keep = need.resolve(&names).expect("declared"); + assert!(!keep.is_empty() && keep.len() < full.0.channels.len(), "{id} {vals:?}: {keep:?}"); + let mut some = (*full.0).clone(); + some.channels.retain(|(n, _)| keep.contains(n)); + some.listed = full.0.names().iter().map(|n| n.to_string()).collect(); + let (want, got) = (run(id, &vals, &full), run(id, &vals, &AuxHost(Arc::new(some)))); + assert_eq!(bits(&got), bits(&want), "{id} {vals:?}: {keep:?}"); + } + assert_eq!(aux_needs("ec.blur.gaussian", &crate::Params::default()), None, "not declared: all"); +} diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index bfe9c5fb8..75a4f7ad3 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -120,9 +120,9 @@ pub use time_fx::{PixelMotion, TimewarpPlan, TwStep, pmb_plan, posterized_time, pub use ocio::color_stabilizer_maps; // GPU effects, part B (3D Channel, Immersive Video, colour management, simulation render passes). pub use channel3d::{ - CRYPTO_LAYERS, CryptoAux, EXTRACTOR_COPY, MATTE_ONLY_IN_ALPHA, aux_point, crypto_aux_image, crypto_aux_image_with, crypto_layer_choices, crypto_layer_menu, - crypto_layer_name, crypto_layer_named, extractor_aux_channel, extractor_own_channel, id_color, is_extractor_copy, matte_only_px, reads_aux, - selection_hashes, + CRYPTO_LAYERS, CryptoOutput, CryptoPlane, EXTRACTOR_COPY, MATTE_ONLY_IN_ALPHA, aux_need, aux_needs, aux_point, crypto_aux_image, crypto_box_scale, + crypto_layer_choices, crypto_layer_menu, crypto_layer_name, crypto_layer_named, crypto_plane, extractor_aux_channel, extractor_own_channel, id_color, + is_extractor_copy, matte_only_px, pixel_margin, reads_aux, selection_hashes, }; pub use file_cache::{check_lut_files, lut_generation}; pub use ocio::{ColorOp, Straight, Tf, color_program}; @@ -917,6 +917,8 @@ pub fn instantiate(spec: &EffectSpec, ids: &mut Ids, instance_name: &str, layer_ if matches!(ps.ui, ParamUi::Checkbox | ParamUi::Popup { .. } | ParamUi::Layer) { pr.hold_only = true; } + // (the channels an effect reads: not animatable, as in After Effects) + pr.static_only = channel3d::selects_channels(spec.id, ps.id); match path.and_then(|path| nested_group(&mut g, ids, path)) { Some(sub) => sub.children.push(pr.into()), None => g.children.push(pr.into()), diff --git a/crates/effects/src/migrate.rs b/crates/effects/src/migrate.rs index 79fb0fbbb..146660353 100644 --- a/crates/effects/src/migrate.rs +++ b/crates/effects/src/migrate.rs @@ -372,6 +372,29 @@ pub fn upgrade_instance(spec: &EffectSpec, g: &mut PropGroup, ids: &mut Ids, lay *g != before } +/// Make the channel-selection parameters of the saved instance `g` of `spec` static +/// ([`crate::channel3d::selects_channels`]: not animatable, as in After Effects). Keyframes or an +/// expression on one (a project from before, or an import) are dropped: it keeps the value of +/// its first keyframe (else its static value). Returns the names of the parameters that lost +/// their animation. +pub fn static_channel_params(spec: &EffectSpec, g: &mut PropGroup) -> Vec { + let mut lost = vec![]; + for ps in spec.params.iter().filter(|ps| crate::channel3d::selects_channels(spec.id, ps.id)) { + let Some(pr) = prop_at(g, ps.id) else { continue }; + pr.static_only = true; + if pr.keys.is_empty() && pr.expr.is_none() { + continue; + } + if let Some(first) = pr.keys.first() { + pr.value = first.value.clone(); + } + pr.keys.clear(); + pr.expr = None; + lost.push(pr.name.clone()); + } + lost +} + /// The spec id of the parameter that an instance of `spec` saved at `id` (`a/b/param`) is now: /// `id` itself when the spec still has it, the new id of a renamed parameter /// ([`PARAM_ID_ALIASES`]), or the twirl-down path of a top-level parameter that moved into a @@ -508,6 +531,30 @@ mod tests { use super::*; use crate::{find, instantiate}; + /// #3271: an import or an older document with a keyed or scripted channel selection + /// (Cryptomatte's Layer) keeps the first key's value, static, and names what it lost. + #[test] + fn channel_selection_becomes_static() { + let spec = find("ec.3d.cryptomatte").unwrap(); + let mut next = 1; + let mut g = instantiate(spec, &mut Ids(&mut next), "Cryptomatte", [100.0, 50.0]); + assert!(static_channel_params(spec, &mut g).is_empty(), "a fresh instance loses nothing"); + let pr = g.get_mut("layer").unwrap(); + assert!(pr.static_only, "no stopwatch"); + pr.static_only = false; + // (keys at 0 s and 1 s) + let first = effectcraft_keyframe::Keyframe::new(Default::default(), Value::Enum(2)); + let mut second = effectcraft_keyframe::Keyframe::new(Default::default(), Value::Enum(0)); + second.time.0 = 254_016_000_000; + pr.keys = vec![first, second]; + g.get_mut("layerName").unwrap().expr = Some(effectcraft_project::Expression { text: "'CryptoObject'".into(), enabled: true }); + assert_eq!(static_channel_params(spec, &mut g), ["Layer", "Layer Name"]); + let pr = g.get_mut("layer").unwrap(); + assert!(pr.static_only && pr.keys.is_empty()); + assert_eq!(pr.value, Value::Enum(2)); + assert!(g.get_mut("layerName").unwrap().expr.is_none()); + } + #[test] fn upgrade_is_a_no_op_on_fresh_instances() { let mut next = 1; diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 4db07e61e..14ea5e8a2 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -47,6 +47,7 @@ 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 } same-file = { workspace = true } tempfile = { workspace = true } effectcraft-sam2 = { workspace = true } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index fefe01950..2585e3b2e 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -20,7 +20,7 @@ mod create; mod edit; mod effect; pub use effect::{CryptoCoverage, CryptoProbeJob, PLUGINS_DIR}; -pub(crate) use effect::{CryptoProbeSlot, crypto_coverage, crypto_probe_job, crypto_probe_ready, keep_crypto_probe, kept_crypto_probe}; +pub(crate) use effect::{CryptoProbeSlot, crypto_coverage, crypto_probe_job, crypto_probe_ready, keep_crypto_probe, kept_crypto_probe, moves}; pub mod essential; pub mod expr_tools; mod file; diff --git a/crates/engine/src/cmd/animation.rs b/crates/engine/src/cmd/animation.rs index 58d0f9f72..33518c9e6 100644 --- a/crates/engine/src/cmd/animation.rs +++ b/crates/engine/src/cmd/animation.rs @@ -262,6 +262,8 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result { ids.iter().filter_map(|lid| comp.layer(*lid).map(|l| (*lid, effectcraft_render::effect_bounds(&s.project, comp, l).0))).collect(); let mut applied = 0; let mut skipped = vec![]; + // Channel selections whose keys or expression the preset had: their first value is kept. + let mut static_kept: Vec = vec![]; s.edit("Apply Animation Preset", None, |proj, _| { let mut next = proj.next_id; for (li, lid) in ids.iter().enumerate() { @@ -279,6 +281,11 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result { }; if let Some(spec) = spec { effectcraft_effects::migrate::upgrade_instance(spec, &mut g, &mut Ids(&mut next), size); + // (channel selection is static: a preset's keys or expression on it + // are dropped, its first value kept) + for name in effectcraft_effects::migrate::static_channel_params(spec, &mut g) { + static_kept.push(format!("{}: {name}", g.name)); + } } retime_effect(&mut g, 1.0, "anim.applyPreset", |t| Ok(Tick(t.0.checked_add(lt.0).ok_or_else(|| effect_time_error("anim.applyPreset"))?)))?; g.reassign_uids(&mut next); @@ -324,6 +331,15 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result { }; let resolved = resolve_effect_path(l, path); match l.props.prop_mut(&resolved) { + // A property that can't be animated takes the preset's first value alone. + Some(pr) if pr.static_only && std::mem::discriminant(&pr.value) == std::mem::discriminant(&src.value) => { + let first = src.keys.first().map(|k| &k.value).filter(|v| std::mem::discriminant(*v) == std::mem::discriminant(&src.value)); + pr.value = first.unwrap_or(&src.value).clone(); + if !src.keys.is_empty() || src.expr.is_some() { + static_kept.push(pr.name.clone()); + } + applied += 1; + } Some(pr) if std::mem::discriminant(&pr.value) == std::mem::discriminant(&src.value) => { pr.value = src.value.clone(); pr.keys = src @@ -394,13 +410,16 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result { proj.next_id = next; Ok(()) })?; + if !static_kept.is_empty() { + s.toast(format!("Channel selection can't be animated: kept the first value of {}", static_kept.join(", "))); + } // Animation ▸ Recent Animation Presets. if let Some(path) = str_p(p, "path") { s.prefs.push_recent_preset(path); s.save_prefs(); s.prefs_revision += 1; } - Ok(json!({"applied": applied, "skipped": skipped})) + Ok(json!({"applied": applied, "skipped": skipped, "staticKept": static_kept})) } /// The preset path of the Version of the Cineon Converter whose Gamma is at preset path `path` diff --git a/crates/engine/src/cmd/app_more.rs b/crates/engine/src/cmd/app_more.rs index ea4230852..faec31877 100644 --- a/crates/engine/src/cmd/app_more.rs +++ b/crates/engine/src/cmd/app_more.rs @@ -424,7 +424,8 @@ pub fn system_report(s: &Session) -> Value { let gb = |b: u64| format!("{:.1} GB", b as f64 / (1u64 << 30) as f64); let export: Vec<&str> = s.exporter.as_ref().map(|e| e.formats().into_iter().map(|f| f.label()).collect()).unwrap_or_default(); let gpu = s.accel.as_ref().map(|a| a.name()); - let budgets = s.prefs.cache_budgets(mem.or(s.sys_memory)); + // (the budget in force: from the reading the session applied, not this fresh one) + let budget = s.memory_budget(); let mut issues = vec![]; if gpu.is_none() { issues.push(match &s.accel_note { @@ -448,7 +449,7 @@ pub fn system_report(s: &Session) -> Value { "gpu": gpu, "gpuNote": if gpu.is_none() { s.accel_note.clone() } else { None }, "windowGraphics": s.window_adapter, - "caches": {"layer": gb(budgets.layer as u64), "footage": gb(budgets.media as u64), "preview": gb(budgets.preview as u64)}, + "caches": {"budget": gb(budget.bytes as u64), "inUse": gb(effectcraft_render::memory::Accountant::global().total() as u64), "reduced": budget.reduced}, "import": IMPORT_FORMATS, "export": export, "logging": crate::logging::is_enabled(), @@ -482,12 +483,7 @@ pub fn report_text(r: &Value) -> String { t.push_str(&format!("Window graphics: {w}\n")); } let c = &r["caches"]; - t.push_str(&format!( - "Cache budgets: layer {}, footage {}, preview {}\n", - c["layer"].as_str().unwrap_or("?"), - c["footage"].as_str().unwrap_or("?"), - c["preview"].as_str().unwrap_or("?") - )); + t.push_str(&format!("Cache memory: {} in use of {}\n", c["inUse"].as_str().unwrap_or("?"), c["budget"].as_str().unwrap_or("?"))); t.push_str(&format!("Import: {}\nExport: {}\n", list("import"), list("export"))); let issues = list("issues"); t.push_str(&if issues.is_empty() { "No compatibility issues found.".to_string() } else { format!("Issues: {issues}") }); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index c2ecb838d..36717cbb1 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -553,7 +553,8 @@ fn paste_links(s: &mut Session, clip: LinkClip) -> Result { let l = super::layer_mut(proj, cid, *lid)?; for (path, e) in &pairs { let path = super::resolve_effect_path(l, path); - if let Some(pr) = l.props.prop_mut(&path) { + // (a property that can't be animated takes no expression) + if let Some(pr) = l.props.prop_mut(&path).filter(|pr| !pr.static_only) { pr.expr = Some(e.clone()); n += 1; } diff --git a/crates/engine/src/cmd/effect.rs b/crates/engine/src/cmd/effect.rs index e6d273dba..4cfd814a6 100644 --- a/crates/engine/src/cmd/effect.rs +++ b/crates/engine/src/cmd/effect.rs @@ -422,7 +422,7 @@ struct CryptoHit { impl CryptoHit { fn manifest(&self) -> Option<&[(String, u32)]> { - self.aux.manifests.iter().find(|(l, _)| *l == self.layer).map(|(_, m)| m.as_slice()) + self.aux.manifest(&self.layer) } fn reply(&self, sel: &str) -> Value { let selected = effectcraft_effects::selection_hashes(sel, self.manifest()).contains(&self.hash); @@ -520,7 +520,13 @@ impl CryptoProbe { reads: None, }; let params = effectcraft_effects::flatten_params(g, &mut |pr| ctx.value(layer, pr)); - let aux = r.layer_aux(&ctx, layer).ok_or(NO_CRYPTO)?; + // The channels the layer's effects read and this effect's (it may be switched off). + let own = match &g.kind { + effectcraft_project::GroupKind::Effect { effect } => effectcraft_effects::aux_need(effect, ¶ms), + _ => effectcraft_raster::channels3d::AuxNeed::Lookups(vec![]), + }; + let need = r.layer_aux_need(&ctx, layer).union(own); + let aux = r.layer_aux_with(&ctx, layer, &need).ok_or(NO_CRYPTO)?; if !live() { return Ok(None); } @@ -540,7 +546,7 @@ impl CryptoProbe { } /// Whether a property in `g` other than `skip` changes over time (keyframes or an expression). -fn moves(g: &PropGroup, skip: Option) -> bool { +pub(crate) fn moves(g: &PropGroup, skip: Option) -> bool { g.children.iter().any(|c| match c { effectcraft_project::Node::Prop(p) => Some(p.uid) != skip && (p.is_animated() || p.has_expression()), effectcraft_project::Node::Group(g) => moves(g, skip), @@ -1264,12 +1270,14 @@ fn list(_: &mut Session, p: &Value) -> Result { impl Session { /// The named channels of layer `lid` in the active comp at the current time: its /// multi-layer OpenEXR footage's layers and channels (`diffuse.R`, `depth.Z`, …), which - /// EXtractoR and the 3D Channel effects read. `None` for other layers. + /// EXtractoR and the 3D Channel effects read, and its Cryptomatte manifests. The names come + /// from the file's headers ([`effectcraft_render::FootageSource::aux_names`]): the planes + /// may be empty, so this is for lists and popups only. `None` for other layers. pub fn layer_channels(&self, lid: LayerId) -> Option> { let layer = self.active_comp()?.layer(lid)?; let effectcraft_project::LayerSource::Footage { item } = layer.source else { return None }; let effectcraft_project::ItemKind::Footage(f) = &self.project.item(item)?.kind else { return None }; - self.footage.aux(item, f, layer.layer_time(self.time())) + self.footage.aux_names(item, f, layer.layer_time(self.time())) } } diff --git a/crates/engine/src/cmd/essential.rs b/crates/engine/src/cmd/essential.rs index 419bd7316..2bf0ebf6c 100644 --- a/crates/engine/src/cmd/essential.rs +++ b/crates/engine/src/cmd/essential.rs @@ -888,7 +888,9 @@ pub fn read_template(bytes: &[u8]) -> std::result::Result<(Value, Project, Vec<( } let text = String::from_utf8(get("project.ecproj").ok_or("template has no project.ecproj")?).map_err(|e| e.to_string())?; let mut project = Project::from_json(&text).map_err(|e| e.to_string())?; - crate::upgrade_effects(&mut project); + // (channel selection can't be animated, as in After Effects: a template made before that + // keeps its first value; read for listings and thumbnails too, so not said each time) + let _static_channels = crate::upgrade_effects(&mut project); Ok((manifest, project, entries)) } diff --git a/crates/engine/src/cmd/import_project.rs b/crates/engine/src/cmd/import_project.rs index af37771a8..6d4365f43 100644 --- a/crates/engine/src/cmd/import_project.rs +++ b/crates/engine/src/cmd/import_project.rs @@ -61,7 +61,8 @@ fn root_comps(project: &Project) -> Vec { fn import_project(s: &mut Session, p: &Value) -> Result { let path = str_p(p, "path").ok_or_else(|| bad(C, "missing `path` (.ecproj)"))?.to_string(); let (mut sub, saved_by) = read_project(s, &path)?; - crate::upgrade_effects(&mut sub); + // (channel selection can't be animated, as in After Effects: said with the import's warnings) + let lost = crate::upgrade_effects(&mut sub); let file = std::path::Path::new(&path); let missing = resolve_footage(s, &mut sub, &path); s.stored_paths.add(&sub, Some(&path)); @@ -96,6 +97,10 @@ fn import_project(s: &mut Session, p: &Value) -> Result { .collect(); let primary = if let [one] = roots.as_slice() { Some(one.0) } else { None }; let mut warnings = vec![]; + if !lost.is_empty() { + log::warn!("channel selection is static: keyframes or expressions dropped on {}", lost.join("; ")); + warnings.push(format!("channel selection can't be animated: kept the first value of {}", lost.join(", "))); + } if let Some(v) = saved_by.as_deref().filter(|v| effectcraft_project::is_newer_version(v, effectcraft_project::APP_VERSION)) { warnings.push(format!("saved by EffectCraft {v}, newer than this version ({})", effectcraft_project::APP_VERSION)); } diff --git a/crates/engine/src/cmd/prop.rs b/crates/engine/src/cmd/prop.rs index 59e932f97..3a1cf38c3 100644 --- a/crates/engine/src/cmd/prop.rs +++ b/crates/engine/src/cmd/prop.rs @@ -505,7 +505,7 @@ fn toggle_key_selected(s: &mut Session, p: &Value) -> Result { let want = added.as_bool().unwrap_or(true); for (olid, ouid) in twins { let _ = with_prop(s, "Add/Remove Keyframe", None, cid, olid, ouid, |pr, lt| { - if key_at(&pr.keys, lt).is_some() != want { + if !pr.static_only && key_at(&pr.keys, lt).is_some() != want { toggle_key_at(pr, lt); } Ok(()) @@ -634,6 +634,9 @@ fn add_key(s: &mut Session, p: &Value) -> Result { let at = snapped_key_time(s, cid, lid, p, "prop.addKey")?; let value = p.get("value").cloned(); let count = with_prop(s, "Add Keyframe", None, cid, lid, uid, |pr, lt| { + if pr.static_only { + return Err(bad("prop.addKey", "this property can't be animated")); + } let t = at.unwrap_or(lt); let cur = pr.value_at(t); let v = match &value { @@ -656,7 +659,12 @@ fn add_key(s: &mut Session, p: &Value) -> Result { fn toggle_key(s: &mut Session, p: &Value) -> Result { let (cid, lid, uid) = prop_ref(s, p, "prop.toggleKey")?; - with_prop(s, "Add/Remove Keyframe", None, cid, lid, uid, |pr, lt| Ok(json!(toggle_key_at(pr, lt)))) + with_prop(s, "Add/Remove Keyframe", None, cid, lid, uid, |pr, lt| { + if pr.static_only { + return Err(bad("prop.toggleKey", "this property can't be animated")); + } + Ok(json!(toggle_key_at(pr, lt))) + }) } /// Add a keyframe at layer time `lt` (true), or remove the one there (false). @@ -731,6 +739,19 @@ fn apply_expr(pr: &mut Property, text: &Option, enabled: Option, d } } +/// Whether [`apply_expr`] would leave `pr` with an enabled expression it didn't have (a new one, +/// one switched on, or new text). +fn adds_expression(pr: &Property, text: &Option, enabled: Option, def: &str) -> bool { + let mut after = pr.clone(); + apply_expr(&mut after, text, enabled, def); + match (&pr.expr, &after.expr) { + (_, None) => false, + (_, Some(a)) if !a.enabled => false, + (Some(b), Some(a)) => !b.enabled || b.text != a.text, + (None, Some(_)) => true, + } +} + /// `{layer?, path|prop, ...}` for one property, or (Animation > Add Expression) no `path`/`prop` /// for the properties selected in the timeline, all in one undo step. fn set_expr(s: &mut Session, p: &Value) -> Result { @@ -766,14 +787,31 @@ fn set_expr(s: &mut Session, p: &Value) -> Result { let results = s.edit("Expression", merge_p(p), |proj, state| { let mut out = vec![]; let mut changed_types = vec![]; + let mut skipped = None; + let mut applied = 0usize; for (((cid, lid, uid), def), time) in targets.iter().zip(&defs).zip(×) { let pr = layer_mut(proj, *cid, *lid)?.props.find_mut(*uid).ok_or_else(|| bad(C, "property vanished"))?; + // A property that can't be animated takes no expression (one an older document has + // may still be disabled or removed): named, that is an error; in a selection it is + // left out, as Add Keyframe leaves it out. + if pr.static_only && adds_expression(pr, &text, enabled, def) { + if explicit { + return Err(bad(C, format!("{} can't have an expression", pr.name))); + } + skipped = Some(pr.name.clone()); + out.push(Value::Null); + continue; + } apply_expr(pr, &text, enabled, def); + applied += 1; out.push(json!(pr.expr.as_ref().map(|e| e.text.clone()))); if pr.match_id == "type" { changed_types.push((*cid, *lid, *uid, *time)); } } + if let Some(name) = skipped.filter(|_| applied == 0) { + return Err(bad(C, format!("{name} can't have an expression"))); + } // All selected targets must be edited before a Type change can remove inner controls. for (cid, lid, uid, time) in changed_types { sync_polystar_property(proj, state, cid, lid, uid, time)?; @@ -1410,8 +1448,11 @@ fn convert_expr_to_keys(s: &mut Session, p: &Value) -> Result { if p.get("path").is_none() && p.get("prop").is_none() && p.get("layer").is_none() { let cid = comp_id(s, p)?; let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?; - let sel: Vec<(LayerId, Uid)> = - selected_leaf_props(s).into_iter().filter(|(l, u)| comp.layer(*l).and_then(|l| l.props.find(*u)).is_some_and(Property::has_expression)).collect(); + // (a property that can't be animated is left out, as Add Keyframe leaves it out) + let sel: Vec<(LayerId, Uid)> = selected_leaf_props(s) + .into_iter() + .filter(|(l, u)| comp.layer(*l).and_then(|l| l.props.find(*u)).is_some_and(|pr| pr.has_expression() && !pr.static_only)) + .collect(); if sel.is_empty() { return Err(bad(CMD, "no `path` given and no selected property has an expression")); } @@ -1459,6 +1500,10 @@ fn convert_one_expr(s: &mut Session, cid: ItemId, lid: LayerId, uid: Uid) -> Res let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone(); let layer = comp.layer(lid).ok_or(EngineError::NoComp)?.clone(); let pr = layer.props.find(uid).ok_or_else(|| bad("prop.convertExpressionToKeyframes", "no property"))?.clone(); + // (an expression an older document left on a property that can't be animated: no keys) + if pr.static_only { + return Err(bad("prop.convertExpressionToKeyframes", format!("{} can't be animated", pr.name))); + } let fd = comp.frame_duration(); check_convertible(fd.0, &layer)?; let mut keys = vec![]; diff --git a/crates/engine/src/cmd/render_queue.rs b/crates/engine/src/cmd/render_queue.rs index 9881f578f..c45865c9e 100644 --- a/crates/engine/src/cmd/render_queue.rs +++ b/crates/engine/src/cmd/render_queue.rs @@ -867,6 +867,7 @@ fn save_current_preview(s: &mut Session, p: &Value) -> Result { caches: None, renderer: None, gpu_frames: s.prefs.memory.gpu_frames(), + cache_budget: Some(s.export_cache_budget()), }; let r = exporter.export(&job, &mut |_, _| true).map_err(EngineError::Other)?; s.toast(format!("Saved preview to {}", r.path)); diff --git a/crates/engine/src/cmd/timeline.rs b/crates/engine/src/cmd/timeline.rs index 691f373de..bec253efe 100644 --- a/crates/engine/src/cmd/timeline.rs +++ b/crates/engine/src/cmd/timeline.rs @@ -107,6 +107,8 @@ struct PrerenderCx { expr: Option>, accel: Option>, nested_switches: bool, + /// What each of a pre-render's two layer caches may hold (`Session::export_cache_budget`). + cache_budget: usize, } /// Render one layer to ProRes 4444 with alpha over its in–out span; `progress` as the exporter's. @@ -149,6 +151,7 @@ fn prerender( caches: None, renderer: None, gpu_frames: None, + cache_budget: Some(cx.cache_budget), }; let r = exporter.export(&job, progress)?; Ok(Prerendered { path: r.path, width: comp.width, height: comp.height, frame_rate: comp.frame_rate, duration: end - start }) @@ -191,6 +194,7 @@ fn export_timeline(s: &mut Session, p: &Value) -> Result { expr: s.expr.clone(), accel: s.accel.clone(), nested_switches: s.prefs.general.switches_affect_nested_comps, + cache_budget: s.export_cache_budget(), }; // The pre-renders can take minutes: with `background` (the export dialog) they run as a job // in Window ▸ Progress instead of with the window waiting (#2269). diff --git a/crates/engine/src/cmd/watch_folder.rs b/crates/engine/src/cmd/watch_folder.rs index 6e480a9e6..682cb49ab 100644 --- a/crates/engine/src/cmd/watch_folder.rs +++ b/crates/engine/src/cmd/watch_folder.rs @@ -65,6 +65,9 @@ fn render_project(host: &Session, path: &Path) -> Value { s.exporter = host.exporter.clone(); s.accel = host.accel.clone(); s.prefs = host.prefs.clone(); + // Its Render Queue caches take the host's memory budget (#3941), which follows its reading. + s.sys_memory = host.sys_memory; + s.memory_low = host.memory_low; let result = (|| -> std::result::Result { s.execute("file.open", json!({"path": name})).map_err(|e| e.to_string())?; let queued = s.project.render_queue.iter().filter(|i| i.render && i.status == RenderStatus::Queued).count(); @@ -91,6 +94,7 @@ fn render_project(host: &Session, path: &Path) -> Value { // The project shared `host`'s footage source and gave it its own set of footage effects read // the channels of (#474): give back the host's. host.footage.set_aux_footage(host.aux_footage.as_deref().unwrap_or(&[])); + host.footage.set_aux_needs(host.aux_needs.as_deref().unwrap_or(&[])); let mut v = match result { Ok(v) => v, Err(e) => json!({"state": "failed", "error": e, "items": []}), diff --git a/crates/engine/src/footage/footage_reload.rs b/crates/engine/src/footage/footage_reload.rs index 5a0576f10..8721f505e 100644 --- a/crates/engine/src/footage/footage_reload.rs +++ b/crates/engine/src/footage/footage_reload.rs @@ -341,6 +341,8 @@ pub(crate) fn forget_media(s: &mut Session, paths: &BTreeSet) { for p in paths { s.footage.forget(p); } + // (thumbnails look at no file: a reload gives them new keys, #3271) + s.footage_reloads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); s.layer_cache.clear(); s.events.push(crate::Event::PurgeCaches); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index f7a39f063..66ca04c13 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -227,6 +227,9 @@ pub struct Session { /// The last physical-memory reading (Settings ▸ Memory & CPU budgets); `None` = unknown /// (headless sessions don't query it, see [`Session::memory_tick`]). pub sys_memory: Option, + /// The system is in a low-memory episode (the cache budgets stay reduced until it ends, see + /// [`sysinfo::SysMemory::still_low`] and [`Session::memory_budget`]). + pub memory_low: bool, /// The keyframe drag in progress (`keys.move` with a merge key). pub key_move: Option, /// Reads the system's memory in the background for [`Session::memory_tick`]. @@ -266,9 +269,15 @@ pub struct Session { /// Each footage file's size and modification time when last seen (Settings ▸ Import ▸ /// Reload Footage Changed on Disk, [`footage_reload`]). pub footage_stamps: std::collections::HashMap, + /// Footage reloaded so far ([`Session::forget_decoded`]): part of the Project panel's + /// thumbnail keys ([`Session::thumbnail_key`]), which otherwise look at no file. + pub footage_reloads: std::sync::atomic::AtomicU64, /// The footage files effects read the channels of, as last given to the footage source /// ([`Session::refresh_aux_footage`]); `None` = not given yet. pub aux_footage: Option>, + /// What the effects read of each of those files, as last given ([`Session::refresh_aux_footage`], + /// #3271); `None` = not given yet. + pub aux_needs: Option>, /// How many script-issued commands are running ([`Session::execute_for_script`]): while one /// is, settings that guard what scripts may do can't change (see /// [`prefs::Scripting::same_permissions`]). @@ -380,6 +389,7 @@ impl Default for Session { library: Default::default(), script_ui: scriptui::ScriptUi::default(), sys_memory: None, + memory_low: false, key_move: None, memory_watch: Default::default(), disk_watch: Default::default(), @@ -397,7 +407,9 @@ impl Default for Session { check_footage_on_open: false, stored_paths: Default::default(), footage_stamps: Default::default(), + footage_reloads: Default::default(), aux_footage: None, + aux_needs: None, script_calls: ScriptCalls::default(), } } diff --git a/crates/engine/src/render_queue.rs b/crates/engine/src/render_queue.rs index 7c10af40c..cacdd4410 100644 --- a/crates/engine/src/render_queue.rs +++ b/crates/engine/src/render_queue.rs @@ -43,20 +43,31 @@ pub struct ExportJob<'a> { pub renderer: Option<&'a Mutex>>, /// Settings ▸ Memory & CPU ▸ GPU Frames Rendered at Once: 1 to 3, `None` for Auto. pub gpu_frames: Option, + /// What each of a one-off export's own two layer caches may hold + /// ([`Session::export_cache_budget`], #3941); `None`: the exporter's default. + pub cache_budget: Option, } /// What the jobs of one Render Queue run keep between them (#3335): a layer cache per -/// compositor (a buffer an effect made on the GPU is not the CPU's), together at the budget -/// each job's single cache had before. +/// compositor (a buffer an effect made on the GPU is not the CPU's), each with the session's +/// budget for an export's caches ([`Session::export_cache_budget`], #3941). Both are in the +/// memory accountant's common budget (#3301): they give way with the other caches when it is +/// full, so together they never hold more than it. pub struct RunCaches { - pub gpu: effectcraft_render::LayerCache, - pub cpu: effectcraft_render::LayerCache, + pub gpu: std::sync::Arc, + pub cpu: std::sync::Arc, } -impl Default for RunCaches { - fn default() -> Self { - let half = effectcraft_render::LayerCache::default().budget() / 2; - RunCaches { gpu: effectcraft_render::LayerCache::new(half), cpu: effectcraft_render::LayerCache::new(half) } +impl RunCaches { + /// The two caches, each with `budget` bytes, registered with the memory accountant. + pub fn new(budget: usize) -> Self { + let (gpu, cpu) = (std::sync::Arc::new(effectcraft_render::LayerCache::new(budget)), std::sync::Arc::new(effectcraft_render::LayerCache::new(budget))); + let accountant = effectcraft_render::memory::Accountant::global(); + for cache in [&gpu, &cpu] { + let holder: std::sync::Arc = cache.clone(); + accountant.register(&holder); + } + RunCaches { gpu, cpu } } } @@ -250,6 +261,8 @@ struct Work { nested_switches: bool, /// Settings ▸ Memory & CPU ▸ GPU Frames Rendered at Once. gpu_frames: Option, + /// What each of the run's two layer caches may hold ([`Session::export_cache_budget`]). + cache_budget: usize, } /// Where a relative render output goes when there is no default folder and the project is unsaved: @@ -346,6 +359,7 @@ pub(crate) async fn run_items( items, nested_switches: s.prefs.general.switches_affect_nested_comps, gpu_frames: s.prefs.memory.gpu_frames(), + cache_budget: s.export_cache_budget(), }; run_work(work, shared, notify).await; } @@ -356,7 +370,7 @@ async fn run_work(w: Work, shared: &JobShared, notify: &mut dyn FnMut(&JobShared let mut s = lock(&shared.state); s.items_total = w.items.len(); } - let caches = RunCaches::default(); + let caches = RunCaches::new(w.cache_budget); let _run_end = RunEnd(w.accel.as_deref()); for (k, modules) in w.items.iter().enumerate() { let Some((item, _)) = modules.first() else { continue }; @@ -395,6 +409,7 @@ async fn run_work(w: Work, shared: &JobShared, notify: &mut dyn FnMut(&JobShared caches: Some(&caches), renderer: Some(&renderer), gpu_frames: w.gpu_frames, + cache_budget: Some(w.cache_budget), }; let rr = w .exporter @@ -656,6 +671,7 @@ impl Session { items, nested_switches: self.prefs.general.switches_affect_nested_comps, gpu_frames: self.prefs.memory.gpu_frames(), + cache_budget: self.export_cache_budget(), }; let shared = Arc::new(JobShared::default()); if wait { diff --git a/crates/engine/src/rq_tests.rs b/crates/engine/src/rq_tests.rs index 60fc2b2c3..124ef9518 100644 --- a/crates/engine/src/rq_tests.rs +++ b/crates/engine/src/rq_tests.rs @@ -307,6 +307,38 @@ fn a_queue_run_keeps_its_jobs_warm() { assert_eq!(ends.0.load(Ordering::SeqCst), 1, "the pool is trimmed once, after the run"); } +#[test] +fn render_queue_runs_and_one_off_exports_follow_the_memory_budget() { + // #3941: a Render Queue run's two layer caches and a one-off export's held 512 MiB each + // (1 GiB together), whatever the memory budget. Both follow the session's budget now. + type Seen = (Option<(usize, usize)>, Option); + struct Budgets(Mutex>); + impl Exporter for Budgets { + fn formats(&self) -> Vec { + OutputFormat::ALL.to_vec() + } + fn export(&self, job: &ExportJob, _: &mut dyn FnMut(u64, u64) -> bool) -> Result { + self.0.lock().unwrap().push((job.caches.map(|c| (c.gpu.budget(), c.cpu.budget())), job.cache_budget)); + Ok(ExportResult { path: job.path.to_string(), ..Default::default() }) + } + } + let mut s = demo(); + let ex = Arc::new(Budgets(Mutex::new(vec![]))); + s.exporter = Some(ex.clone()); + // A 64 GB machine: 46.4 GB with the default reserve. + s.take_memory_reading(Some(crate::sysinfo::SysMemory { total: 64 << 30, available: 48 << 30 })); + let budget = s.memory_budget().bytes; + assert_eq!(budget as u64, (64 - 6) * (1 << 30) * 80 / 100); + assert_eq!(s.export_cache_budget(), budget, "on the desktop the layer cache's budget is the whole budget"); + + s.execute("renderQueue.add", json!({"output": crate::tests::stubs::tmp_out("rq/budget.mp4")})).unwrap(); + s.execute("renderQueue.render", json!({})).unwrap(); + assert_eq!(ex.0.lock().unwrap().last().copied(), Some((Some((budget, budget)), Some(budget))), "a Render Queue run's caches"); + + s.execute("render.saveCurrentPreview", json!({"path": crate::tests::stubs::tmp_out("rq/budget_preview.mp4")})).unwrap(); + assert_eq!(ex.0.lock().unwrap().last().copied(), Some((None, Some(budget))), "a one-off export's own caches"); +} + #[test] fn the_gpu_frames_setting_reaches_every_render_queue_job() { // #3335: Settings ▸ Memory & CPU ▸ GPU Frames Rendered at Once is Auto (`None`) or 1–3. diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 7d2a20949..7f66bbb47 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -223,7 +223,7 @@ impl Session { self.drop_tasks(); self.script_ui.project_epoch = self.script_ui.project_epoch.wrapping_add(1); p.fix_next_id(); - upgrade_effects(&mut p); + let lost = upgrade_effects(&mut p); // Let go of what the closed project's footage and proxies decoded (frames, decoders, // models), and of what the new project's files decoded under an earlier project: the // media layer keys them by path, and the files may have changed since (#1070). @@ -235,11 +235,18 @@ impl Session { self.project = Arc::new(p); // The set of footage effects read the channels of is sent again, even when it is empty. self.aux_footage = None; + self.aux_needs = None; self.history = History::default(); self.state = EditorState { snapping: true, view_layout: 1, ..Default::default() }; self.path = path; self.bump(); self.mark_saved(); + // (channel selection can't be animated, as in After Effects: a document that animated it + // keeps its first value; said once, not as an error) + if !lost.is_empty() { + log::warn!("channel selection is static: keyframes or expressions dropped on {}", lost.join("; ")); + self.toast(format!("Channel selection can't be animated: kept the first value of {}", lost.join(", "))); + } // The viewers' RAM preview shows the closed project's frames, whose comp ids can collide // with the new project's. self.events.push(Event::PurgeCaches); @@ -256,8 +263,12 @@ impl Session { /// [`effectcraft_project::SCHEMA_EFFECT_SPACE`] into effect space /// ([`effectcraft_effects::migrate::to_effect_space`]). Shape path operations get the /// properties added since ([`effectcraft_project::build::upgrade_shape_contents`]). Stamps the -/// current schema. -pub fn upgrade_effects(p: &mut Project) { +/// current schema. Channel-selection parameters are made static +/// ([`effectcraft_effects::migrate::static_channel_params`]); returns what lost its animation +/// (`Layer: Effect: Parameter`). +#[must_use = "what lost its animation is reported to the user"] +pub fn upgrade_effects(p: &mut Project) -> Vec { + let mut lost = vec![]; let to_effect_space = p.schema < effectcraft_project::SCHEMA_EFFECT_SPACE; // Effect bounds per layer: (size, top-left in layer coordinates). let mut bounds = std::collections::HashMap::new(); @@ -291,10 +302,14 @@ pub fn upgrade_effects(p: &mut Project) { if to_effect_space { effectcraft_effects::migrate::to_effect_space(spec, g, size, d, &clone_d); } + for name in effectcraft_effects::migrate::static_channel_params(spec, g) { + lost.push(format!("{}: {}: {name}", l.name, g.name)); + } } } } } p.next_id = next; p.schema = effectcraft_project::SCHEMA_VERSION; + lost } diff --git a/crates/engine/src/session/render.rs b/crates/engine/src/session/render.rs index fe1634945..28215fb8d 100644 --- a/crates/engine/src/session/render.rs +++ b/crates/engine/src/session/render.rs @@ -153,6 +153,37 @@ impl Session { } } + /// What a Project panel thumbnail of `item` at `t` (longest side `max_side`) shows depends + /// on, as a key (#3271): a comp's content as the disk cache keys frames + /// ([`effectcraft_render::disk_cache::comp_content_key`]), footage's item and settings, the + /// time, the size, the render switches the thumbnail uses and the footage reloads so far. + /// An edit that doesn't change the picture (a selection, another comp, a marker) keeps it, so + /// the thumbnail isn't rendered again. `None` for items without pixels. + pub fn thumbnail_key(&self, item: ItemId, t: Tick, max_side: u32) -> Option { + use effectcraft_render::disk_cache::Hash128; + let it = self.project.item(item)?; + let mut h = Hash128::default(); + h.write(b"thumbnail-v1"); + match &it.kind { + effectcraft_project::ItemKind::Comp(_) => { + h.write_u64(1); + h.write(&effectcraft_render::disk_cache::comp_content_key(&self.project, item).to_le_bytes()); + h.write_u64(t.0 as u64); + h.write_u64(u64::from(self.prefs.general.switches_affect_nested_comps)); + h.write_u64(u64::from(self.prefs.three_d.realtime_shadows)); + } + effectcraft_project::ItemKind::Footage(f) if f.has_video => { + h.write_u64(2); + h.write_u64(item.0); + h.write(format!("{f:?}").as_bytes()); + } + _ => return None, + } + h.write_u64(u64::from(max_side)); + h.write_u64(self.footage_reloads.load(std::sync::atomic::Ordering::Relaxed)); + Some(h.finish()) + } + /// [`Session::render_rgba8`], or with `transparent` the frame's own straight alpha (what a /// render with RGB + Alpha channels writes) instead of compositing over the background. pub fn render_rgba8_alpha(&self, comp: ItemId, t: Tick, max_side: u32, transparent: bool) -> Result<(u32, u32, Vec)> { @@ -169,6 +200,7 @@ impl Session { /// Make the media layer and the layer cache let go of what they decoded from `footage`'s /// files (it keys frames by path, so an overwritten file would keep showing its old pixels). pub(crate) fn forget_decoded(&self, footage: &effectcraft_project::Footage) { + self.footage_reloads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); forget_files(self.footage.as_ref(), footage); self.layer_cache.clear(); self.drop_crypto_probe(); @@ -184,9 +216,52 @@ impl Session { self.footage.set_aux_footage(&paths); self.aux_footage = Some(paths); } + let needs = aux_needs(&self.project); + if self.aux_needs.as_ref() != Some(&needs) { + self.footage.set_aux_needs(&needs); + self.aux_needs = Some(needs); + } } } +/// What the effects of [`aux_footage`]'s layers read of each file's channels (#3271), by +/// [`effectcraft_project::Footage::path`], sorted: the union of what each enabled effect reading +/// them declares ([`effectcraft_effects::aux_needs`]) with its parameters' values (channel +/// selection is static, as in After Effects). Several layers of one file add up. +pub(crate) fn aux_needs(project: &effectcraft_project::Project) -> Vec<(String, effectcraft_raster::channels3d::AuxNeed)> { + use effectcraft_project::{GroupKind, ItemKind, LayerSource}; + use effectcraft_raster::channels3d::AuxNeed; + let mut out: std::collections::BTreeMap = std::collections::BTreeMap::new(); + for l in project.comps().flat_map(|(_, c)| c.layers.iter()).filter(|l| l.switches.effects) { + let LayerSource::Footage { item } = &l.source else { continue }; + let Some(ItemKind::Footage(f)) = project.item(*item).map(|i| &i.kind) else { continue }; + if f.path.is_empty() { + continue; + } + for g in l.effects().into_iter().flat_map(|fx| fx.groups()).filter(|g| g.enabled) { + let GroupKind::Effect { effect } = &g.kind else { continue }; + if !effectcraft_effects::reads_aux(effect) { + continue; + } + // Channel selection is static (as in After Effects): the values say what is read. A + // parameter that moves anyway (it can't, see `static_channel_params`) is read at its + // static value. + if commands::moves(g, None) { + static SAID: std::sync::Once = std::sync::Once::new(); + SAID.call_once(|| log::warn!("an effect reading footage channels has animated parameters; its channels are read at their static values")); + } + let params = effectcraft_effects::flatten_params(g, &mut |p| p.value.clone()); + let need = effectcraft_effects::aux_need(effect, ¶ms); + let merged = match out.remove(&f.path) { + Some(e) => e.union(need), + None => need, + }; + out.insert(f.path.clone(), merged); + } + } + out.into_iter().collect() +} + /// The files (each footage item's [`effectcraft_project::Footage::path`], sorted, once each) of /// the footage layers that have an enabled effect reading their channels /// ([`effectcraft_effects::reads_aux`]), with the layer's Effects switch on. Several items can diff --git a/crates/engine/src/settings/prefs.rs b/crates/engine/src/settings/prefs.rs index 94c90c3a3..fd50835ce 100644 --- a/crates/engine/src/settings/prefs.rs +++ b/crates/engine/src/settings/prefs.rs @@ -27,7 +27,10 @@ mod sections; pub use choices::{APPEARANCE_MODES, DARK_THEMES, LANGUAGES, LIGHT_THEMES, THEMES, WINDOW_GRAPHICS, theme_family}; pub use dialog::{Item, Kind, Page, pages, pages_json, todo_keys}; pub use document::{migrate, page_id, section_key}; -pub use queries::{CacheBudgets, WEB_LAYER_CACHE, WEB_MEDIA_CACHE, mask_color}; +pub use queries::{ + CacheCaps, FALLBACK_MEMORY_BUDGET, MEMORY_HEADROOM_PERCENT, MIN_MEMORY_BUDGET, MemoryBudget, PROCESS_PURGE_PERCENT, WEB_LAYER_CACHE, WEB_MEDIA_CACHE, + WEB_MEMORY_BUDGET, WEB_PREVIEW_CACHE, mask_color, +}; pub use recent::{MAX_RECENT_SCRIPTS, RecentScript}; pub use sections::{ Appearance, Audio, AutoSave, CompPreset, CompositionPrefs, Disk, Export, FacePrefs, General, Grids, Import, LabelPref, Memory, Previews, ProjectPrefs, @@ -36,7 +39,7 @@ pub use sections::{ use sections::{Extra, default_labels, lenient_comp_presets}; /// Current settings layout version. -pub const PREFS_VERSION: u32 = 4; +pub const PREFS_VERSION: u32 = 6; /// Settings file name in the config store. pub const PREFS_FILE: &str = "prefs.json"; diff --git a/crates/engine/src/settings/prefs/dialog.rs b/crates/engine/src/settings/prefs/dialog.rs index d7c50cdce..3c82ea952 100644 --- a/crates/engine/src/settings/prefs/dialog.rs +++ b/crates/engine/src/settings/prefs/dialog.rs @@ -47,6 +47,9 @@ pub enum Item { }, /// Read-only information line. Note(&'static str), + /// Memory & CPU: how much RAM EffectCraft's caches may use, of the installed RAM + /// (`Prefs::memory_budget`, `Session::memory_budget`). + MemoryUse, /// The browser's storage manager (web app only, `storage.*`): usage and quota, persistent /// storage, Clear buttons. Not shown where there is no browser storage. BrowserStorage, @@ -300,6 +303,11 @@ pub fn pages() -> Vec { Section("Media Cache"), s("disk.mediaCacheFolder", "Database and Cache Folder", Kind::Path, true), s("disk.conformedMediaFolder", "Conformed Audio Folder", Kind::Path, true), + Section("Network Footage"), + s("disk.localizeFootage", "Localize Network Footage", B, true), + s("disk.localizeMaxGb", "Maximum Local Copies Size", Kind::Int(1, 100_000, "GB"), true), + s("disk.localizeFolder", "Local Copies Folder", Kind::Path, true), + s("disk.networkFootageLocations", "Network Footage Locations", Kind::Text, true), ], }, Page { @@ -307,10 +315,7 @@ pub fn pages() -> Vec { title: "Memory & CPU", items: vec![ s("memory.ramReservedGb", "RAM Reserved for Other Applications", Kind::Int(0, 1024, "GB"), true), - Section("Cache Budgets"), - s("memory.layerCacheMb", "Layer Cache", Kind::Int(64, 1 << 20, "MB"), true), - s("memory.mediaCacheMb", "Footage Frame Cache", Kind::Int(64, 1 << 20, "MB"), true), - s("memory.previewCacheMb", "Preview (RAM) Cache", Kind::Int(64, 1 << 20, "MB"), true), + MemoryUse, s("memory.reduceCacheWhenLow", "Reduce Cache Size When System Is Low on Memory", B, true), s("memory.gpuFramesInFlight", "GPU Frames Rendered at Once", Kind::Choice(&[("Auto", "auto"), ("1", "1"), ("2", "2"), ("3", "3")]), true), ], @@ -439,6 +444,7 @@ pub fn pages_json() -> Value { Item::Labels => json!({"labels": "labels.N.name / labels.N.color (N = 0..15)"}), Item::AudioDevices { key } => json!({"type": "device", "key": key, "label": "Default Output"}), Item::Note(t) => json!({"note": t}), + Item::MemoryUse => json!({"memoryUse": "help.systemInfo → caches.budget / caches.inUse (what EffectCraft's caches may use, and use now)"}), Item::BrowserStorage => json!({"browserStorage": "storage.info / storage.persist / storage.clear (web app)"}), Item::PluginLibrary => json!({"pluginLibrary": "library.list / library.refresh / library.install / library.update / library.uninstall"}), Item::Models(task) => { diff --git a/crates/engine/src/settings/prefs/document.rs b/crates/engine/src/settings/prefs/document.rs index 873e6fe33..74c24099b 100644 --- a/crates/engine/src/settings/prefs/document.rs +++ b/crates/engine/src/settings/prefs/document.rs @@ -11,6 +11,13 @@ use super::{Appearance, General, Map, PREFS_VERSION, Prefs, Startup, Value, json /// old default becomes the new one (a size the user chose is kept). /// - version 3 and earlier could still hold `createSplitLayersAbove: false`, the default before /// #2083 (every save kept it); it becomes After Effects' default, above (#2545). +/// - version 4 and earlier had the Layer Cache, Footage Frame Cache and Preview (RAM) Cache +/// budgets (`memory.layerCacheMb` / `mediaCacheMb` / `previewCacheMb`); they are dropped: the +/// caches share one budget (#3298). +/// - version 5 and earlier saved Cache Frames When Idle off, the default then (every save kept +/// it); it becomes the new default, on, once (#3321). Off saved later is the user's choice. +/// (Released builds wrote version 4; version 5 came only from pre-release builds of #3301, +/// nearly all of them with the default still off. A file without a version predates both.) pub fn migrate(mut v: Value) -> Value { let Some(obj) = v.as_object_mut() else { return json!({}) }; let version = obj.get("version").and_then(Value::as_u64).unwrap_or(0); @@ -50,6 +57,20 @@ pub fn migrate(mut v: Value) -> Value { { g.insert("createSplitLayersAbove".into(), json!(true)); } + // Version 4 and earlier had three cache budgets (#3298): the caches now share one budget + // from RAM Reserved for Other Applications. The old keys are removed whatever the version + // says, not kept as unknown keys (the page keeps those and would write them back forever). + if let Some(m) = obj.get_mut("memory").and_then(Value::as_object_mut) { + for key in ["layerCacheMb", "mediaCacheMb", "previewCacheMb"] { + m.remove(key); + } + } + if version < 6 + && let Some(p) = obj.get_mut("previews").and_then(Value::as_object_mut) + && p.get("cacheFramesWhenIdle") == Some(&json!(false)) + { + p.insert("cacheFramesWhenIdle".into(), json!(true)); + } // Settings saved before appearance modes had one theme: keep showing it, as a fixed Dark or // Light mode, instead of switching established users to Auto. if let Some(a) = obj.get_mut("appearance").and_then(Value::as_object_mut) @@ -155,10 +176,6 @@ impl Prefs { l.color = d.color.clone(); } } - let m = &mut self.memory; - m.layer_cache_mb = m.layer_cache_mb.clamp(64, 1 << 20); - m.media_cache_mb = m.media_cache_mb.clamp(64, 1 << 20); - m.preview_cache_mb = m.preview_cache_mb.clamp(64, 1 << 20); self.grids.grid_spacing = self.grids.grid_spacing.clamp(1.0, 10_000.0); let n = self.general.recent_items as usize; self.recent_projects.truncate(n); diff --git a/crates/engine/src/settings/prefs/queries.rs b/crates/engine/src/settings/prefs/queries.rs index 74be30f8f..c15d48269 100644 --- a/crates/engine/src/settings/prefs/queries.rs +++ b/crates/engine/src/settings/prefs/queries.rs @@ -20,19 +20,6 @@ impl Prefs { Label::from_name(s).or_else(|| Label::ALL.iter().skip(1).copied().find(|l| self.label_name(*l).eq_ignore_ascii_case(s))) } - /// Layer / media / preview cache budgets in bytes. - pub fn layer_cache_bytes(&self) -> usize { - (self.memory.layer_cache_mb as usize) << 20 - } - - pub fn media_cache_bytes(&self) -> usize { - (self.memory.media_cache_mb as usize) << 20 - } - - pub fn preview_cache_bytes(&self) -> usize { - (self.memory.preview_cache_mb as usize) << 20 - } - /// The adaptive resolution limit as a render-scale floor (1/2 → 0.5). pub fn adaptive_limit(&self) -> f64 { match self.previews.adaptive_resolution_limit.as_str() { @@ -42,40 +29,40 @@ impl Prefs { } } - /// The Memory & CPU cache budgets in effect: the configured layer / footage / preview - /// budgets, scaled down so together they leave **RAM Reserved for Other Applications** free, - /// and halved while the system is low on memory when **Reduce Cache Size When System Is Low - /// on Memory** is on. `mem` = the system's memory (`None` = unknown: configured budgets). - /// In the browser the layer and footage caches also stay within [`WEB_LAYER_CACHE`] and - /// [`WEB_MEDIA_CACHE`]. - pub fn cache_budgets(&self, mem: Option) -> CacheBudgets { - self.cache_budgets_in(mem, cfg!(target_arch = "wasm32")) + /// The limits on the process's measured memory (bytes): above the first the caches give way + /// by what it is over, above the second also the frames a playing preview shows next + /// ([`PROCESS_PURGE_PERCENT`] of the installed RAM left after the reserve, and all of it). + /// `None` while the installed RAM is unknown. + pub fn process_limits(&self, mem: Option) -> Option<(u64, u64)> { + let total = mem.map(|m| m.total).filter(|t| *t > 0)?; + let room = total.saturating_sub(u64::from(self.memory.ram_reserved_gb) << 30).max(MIN_MEMORY_BUDGET); + let purge = u64::try_from(u128::from(room) * u128::from(PROCESS_PURGE_PERCENT) / 100).unwrap_or(room); + Some((purge, room)) } - /// [`Prefs::cache_budgets`], in the browser's memory (`web`) or not. - pub(crate) fn cache_budgets_in(&self, mem: Option, web: bool) -> CacheBudgets { - let (mut l, mut m, mut p) = (self.layer_cache_bytes() as u64, self.media_cache_bytes() as u64, self.preview_cache_bytes() as u64); - if web { - (l, m) = (l.min(WEB_LAYER_CACHE), m.min(WEB_MEDIA_CACHE)); + /// The memory EffectCraft's caches share (Settings ▸ Memory & CPU): the layer cache, the + /// footage frames, the decoded OpenEXR planes and the RAM preview frames together, kept within + /// it by the memory accountant (`effectcraft_render::memory::Accountant`), which decides + /// what each holds. It is [`MEMORY_HEADROOM_PERCENT`] of the installed RAM left after **RAM + /// Reserved for Other Applications** (the rest is room for EffectCraft's own working memory), + /// halved while the system is low on memory (`low`) when **Reduce Cache Size When System Is + /// Low on Memory** is on, and never below [`MIN_MEMORY_BUDGET`]. `mem` = the system's memory + /// (`None` = unknown: [`FALLBACK_MEMORY_BUDGET`], in the browser [`WEB_MEMORY_BUDGET`]). + pub fn memory_budget(&self, mem: Option, low: bool) -> MemoryBudget { + let installed = mem.map(|m| m.total).filter(|t| *t > 0); + let reserved = u64::from(self.memory.ram_reserved_gb) << 30; + let mut bytes = match installed { + // u128: `room × percent` cannot overflow. + Some(total) => u64::try_from(u128::from(total.saturating_sub(reserved)) * u128::from(MEMORY_HEADROOM_PERCENT) / 100).unwrap_or(u64::MAX), + None if cfg!(target_arch = "wasm32") => WEB_MEMORY_BUDGET, + None => FALLBACK_MEMORY_BUDGET, + }; + let reduced = installed.is_some() && low && self.memory.reduce_cache_when_low; + if reduced { + bytes /= 2; } - let floor = 64u64 << 20; - let mut capped = false; - let mut reduced = false; - if let Some(mem) = mem.filter(|m| m.total > 0) { - let reserved = (self.memory.ram_reserved_gb as u64) << 30; - let cap = mem.total.saturating_sub(reserved).max(3 * floor); - let sum = l + m + p; - if sum > cap { - let k = cap as f64 / sum as f64; - (l, m, p) = ((l as f64 * k) as u64, (m as f64 * k) as u64, (p as f64 * k) as u64); - capped = true; - } - if self.memory.reduce_cache_when_low && mem.is_low() { - (l, m, p) = (l / 2, m / 2, p / 2); - reduced = true; - } - } - CacheBudgets { layer: l.max(floor) as usize, media: m.max(floor) as usize, preview: p.max(floor) as usize, capped, reduced } + let bytes = bytes.max(MIN_MEMORY_BUDGET); + MemoryBudget { bytes: usize::try_from(bytes).unwrap_or(usize::MAX), installed, reduced } } /// Composition ▸ Motion Path: the layer-time span of a motion path to draw around `now` @@ -175,27 +162,76 @@ impl Prefs { } } -/// The most the layer cache holds in the browser. A wasm32 page addresses at most 4 GiB, which -/// these caches share with the app and with the decoders' own decoded frames (FilmCraft keeps -/// up to 384 MB per open movie): with the desktop's 1 GB defaults, eight stacked 1080p clips ran -/// the page out of memory a few seconds into playback. +/// The most the layer cache holds in the browser, inside the common budget. A wasm32 page +/// addresses at most 4 GiB, which these caches share with the app and with the decoders' own +/// decoded frames (FilmCraft keeps up to 384 MB per open movie): with 1 GB of layers, eight +/// stacked 1080p clips ran the page out of memory a few seconds into playback. On the desktop +/// no cache has a limit of its own. pub const WEB_LAYER_CACHE: u64 = 512 << 20; /// The most the footage frame cache holds in the browser (see [`WEB_LAYER_CACHE`]). pub const WEB_MEDIA_CACHE: u64 = 256 << 20; -/// Effective cache budgets in bytes (see [`Prefs::cache_budgets`]). +/// Above this part (percent) of the installed RAM left after **RAM Reserved for Other +/// Applications**, the process's measured memory makes the caches give way even within their +/// budget ([`Prefs::process_limits`]): above the caches' budget plus most of the room left for +/// the app's own working memory. +pub const PROCESS_PURGE_PERCENT: u64 = 95; + +/// The part (percent) of the installed RAM left after **RAM Reserved for Other Applications** +/// that EffectCraft's caches share ([`Prefs::memory_budget`]). The rest is headroom for +/// EffectCraft's own working memory (decoders, render buffers, undo, GPU staging, the interface), +/// so that does not eat into the memory reserved for other applications. +pub const MEMORY_HEADROOM_PERCENT: u64 = 80; + +/// The caches' budget while the installed RAM is unknown (the browser, a sandbox, or the desktop +/// before its first background reading): 5 GB, what the three fixed cache budgets added up to +/// before they became one. +pub const FALLBACK_MEMORY_BUDGET: u64 = 5 << 30; + +/// The caches' budget in the browser, where the installed RAM is unknown and a page addresses at +/// most 4 GiB, shared with the app and the decoders' own frames: 3.5 GB, a little more than the +/// RAM preview's 3 GB there, leaving at least half a gigabyte of the page to the rest. (The +/// separate budgets there added up to 4.25 GB before they became one, more than a page can +/// spare.) +pub const WEB_MEMORY_BUDGET: u64 = 3584 << 20; + +/// The most the RAM preview frames hold in the browser, inside the common budget (as before). +pub const WEB_PREVIEW_CACHE: u64 = 3 << 30; + +/// The least the caches share, however little RAM is left after the reserve: 192 MB, three times +/// the smallest budget one cache had before they became one. +pub const MIN_MEMORY_BUDGET: u64 = 192 << 20; + +/// The memory EffectCraft's caches share (see [`Prefs::memory_budget`]). #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] -pub struct CacheBudgets { - pub layer: usize, - pub media: usize, - pub preview: usize, - /// Scaled down to leave the reserved RAM free. - pub capped: bool, +pub struct MemoryBudget { + /// The budget in bytes. + pub bytes: usize, + /// The installed RAM it was taken from (`None`: unknown, the fallback). + pub installed: Option, /// Halved because the system is low on memory. pub reduced: bool, } +impl MemoryBudget { + /// What each big cache may hold by itself within the budget: on the desktop all of it (no + /// cache has a share of its own, the memory accountant decides what is kept), in the browser + /// (`web`) also [`WEB_LAYER_CACHE`], [`WEB_MEDIA_CACHE`] and [`WEB_PREVIEW_CACHE`]. + pub fn caps(&self, web: bool) -> CacheCaps { + let cap = |c: u64| if web { usize::try_from(c).unwrap_or(usize::MAX).min(self.bytes) } else { self.bytes }; + CacheCaps { layer: cap(WEB_LAYER_CACHE), footage: cap(WEB_MEDIA_CACHE), preview: cap(WEB_PREVIEW_CACHE) } + } +} + +/// The most each big cache holds by itself ([`MemoryBudget::caps`]), in bytes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CacheCaps { + pub layer: usize, + pub footage: usize, + pub preview: usize, +} + /// Colour of the `k`-th mask of a layer: Appearance ▸ Cycle Mask Colors cycles through the mask /// colours, otherwise every new mask takes the first one. pub fn mask_color(cycle: bool, k: usize) -> [u8; 3] { diff --git a/crates/engine/src/settings/prefs/sections.rs b/crates/engine/src/settings/prefs/sections.rs index 46d654ab0..0e23337b6 100644 --- a/crates/engine/src/settings/prefs/sections.rs +++ b/crates/engine/src/settings/prefs/sections.rs @@ -199,16 +199,20 @@ page!(Disk { disk_cache_folder: String = String::new(), media_cache_folder: String = String::new(), conformed_media_folder: String = String::new(), + /// Copy footage on network shares to a local folder in the background (#3271). + localize_footage: bool = false, + /// Where the local copies go (empty: beside the media cache). + localize_folder: String = String::new(), + /// The most the local copies take (GB). + localize_max_gb: u32 = 20, + /// Path prefixes counted as network footage besides UNC paths (`P:\`), `;`-separated. + network_footage_locations: String = String::new(), }); page!(Memory { + /// RAM Reserved for Other Applications (GB): EffectCraft's caches share most of the rest + /// (see [`crate::prefs::Prefs::memory_budget`]). ram_reserved_gb: u32 = 6, - /// Processed-layer cache budget (MB). - layer_cache_mb: u32 = 1024, - /// Decoded footage frame cache budget (MB). - media_cache_mb: u32 = 1024, - /// RAM preview (viewer frame) cache budget (MB). - preview_cache_mb: u32 = 3072, reduce_cache_when_low: bool = true, /// GPU Frames Rendered at Once (Render Queue): `auto` (from the GPU memory a frame /// measured, 1 to 3) or `1`, `2`, `3`. `EFFECTCRAFT_GPU_INFLIGHT` overrides it. diff --git a/crates/engine/src/settings/session_settings.rs b/crates/engine/src/settings/session_settings.rs index 8ade9f8a3..7b7b16ca1 100644 --- a/crates/engine/src/settings/session_settings.rs +++ b/crates/engine/src/settings/session_settings.rs @@ -30,6 +30,7 @@ impl Session { self.apply_cache_budgets(); self.configure_disk_cache(); self.footage.set_conform_folder(self.conformed_audio_folder()); + self.footage.set_localizer(self.localize_settings()); // Switches Affect Nested Comps changes what precomp layers render: drop cached pixels. let nested = self.prefs.general.switches_affect_nested_comps; if self.applied_nested_switches.replace(nested).is_some_and(|was| was != nested) { @@ -65,30 +66,115 @@ impl Session { self.cache_folder(&self.prefs.disk.media_cache_folder, "Media Cache") } + /// Settings ▸ Disk ▸ Localize Network Footage (#3271): the local copies' folder and size + /// limit, `None` when off (or there is no folder for them). + pub fn localize_settings(&self) -> Option { + let d = &self.prefs.disk; + if !d.localize_footage || cfg!(target_arch = "wasm32") { + return None; + } + // Without a folder of their own, the copies go beside the disk cache's folder (a disk + // the user chose for caches), else beside the platform cache folder. + let folder = if d.localize_folder.trim().is_empty() && !d.disk_cache_folder.trim().is_empty() { + let dc = std::path::PathBuf::from(d.disk_cache_folder.trim()); + dc.parent().map_or_else(|| dc.join("Local Footage Copies"), |p| p.join("Local Footage Copies")) + } else { + self.cache_folder(&d.localize_folder, "Local Footage Copies")? + }; + let space_of = folder.clone(); + Some(effectcraft_render::LocalizeConfig { + folder, + max_bytes: u64::from(d.localize_max_gb.max(1)) << 30, + network: network_locations(&d.network_footage_locations), + disk_space: Some(std::sync::Arc::new(move || { + // (the folder may not exist yet: its nearest existing parent's disk) + let mut at = space_of.as_path(); + while !at.exists() { + at = at.parent()?; + } + crate::sysinfo::disk_space(at) + })), + }) + } + + /// What the footage localizer is doing, for Settings ▸ Disk (`None`: off). + pub fn localize_status(&self) -> Option { + self.footage.localize_status() + } + /// Settings ▸ Disk ▸ Conformed Audio Folder (decoded footage audio, see /// `MediaPool::set_conform_folder`). pub fn conformed_audio_folder(&self) -> Option { self.cache_folder(&self.prefs.disk.conformed_media_folder, "Conformed Audio") } - /// Apply the Memory & CPU cache budgets, limited by RAM Reserved for Other Applications and - /// reduced while the system is low on memory (see [`crate::prefs::Prefs::cache_budgets`]). + /// Apply the Memory & CPU budget ([`Session::memory_budget`]): one budget the big caches share + /// (the layer cache, the footage frames and decoded planes, the preview frames), kept by the + /// memory accountant, which frees the least valuable data first whichever cache holds it. No + /// cache has a limit of its own below that budget, except the browser's caps + /// ([`crate::prefs::MemoryBudget::caps`]; frontends apply the preview frames' cap). pub fn apply_cache_budgets(&mut self) { - let b = self.prefs.cache_budgets(self.sys_memory); - self.layer_cache.set_budget(b.layer); - self.footage.set_cache_budget(b.media); + let b = self.memory_budget(); + let caps = b.caps(cfg!(target_arch = "wasm32")); + self.layer_cache.set_budget(caps.layer); + self.footage.set_cache_budget(caps.footage); + let accountant = effectcraft_render::memory::Accountant::global(); + let layers: std::sync::Arc = self.layer_cache.clone(); + accountant.register(&layers); + accountant.set_budget(b.bytes); + // (what one file's decoded planes may take follows it once the RAM is read, at least the + // fixed limit; until then the host's reader asks when a request is over that, #3749) + if b.installed.is_some() { + effectcraft_render::memory::set_decode_limit(Some(b.bytes)); + } + // The process's measured memory as well (#3301: memory nobody accounts for, such as GPU + // staging, effect buffers and the allocator's fragmentation): over the purge limit the + // caches give way by what it is over, over the hard limit also the frames a playing + // preview shows next. + if let Some((purge_at, hard_at)) = self.prefs.process_limits(self.sys_memory) { + accountant.set_process_memory(crate::sysinfo::process_memory, purge_at, hard_at); + } + } + + /// What each of an export's two layer caches (one per compositor) may hold (#3941): the + /// session's layer cache budget. On the desktop that is the whole common budget, and both are + /// in the memory accountant, which keeps them within it together with the session's caches. + /// In the browser each gets half the layer cache's cap, so the two together keep it. + pub fn export_cache_budget(&self) -> usize { + let web = cfg!(target_arch = "wasm32"); + let layer = self.memory_budget().caps(web).layer; + if web { layer / 2 } else { layer } + } + + /// The memory the caches share for the last memory reading ([`Prefs::memory_budget`]), kept + /// reduced through a low-memory episode until the system has recovered + /// ([`crate::sysinfo::SysMemory::still_low`]), so the budget (and the toast) doesn't flip + /// with every reading. + pub fn memory_budget(&self) -> crate::prefs::MemoryBudget { + let low = self.sys_memory.is_some_and(|m| m.still_low(self.memory_low)); + self.prefs.memory_budget(self.sys_memory, low) } /// Take the latest reading of the system's memory and start the next one in the background /// (desktop frontends call this every few seconds; it never waits for the system), then - /// re-apply the cache budgets when the reading changes them. Returns the effective budgets. + /// re-apply the memory budget when the reading changes it. Returns the budget in effect. /// The disk cache's free disk space is read the same way (it keeps a reserve free). - pub fn memory_tick(&mut self) -> crate::prefs::CacheBudgets { + pub fn memory_tick(&mut self) -> crate::prefs::MemoryBudget { self.poll_disk_space(); - let before = self.prefs.cache_budgets(self.sys_memory); - self.sys_memory = self.memory_watch.latest().or(self.sys_memory); + let reading = self.memory_watch.latest(); self.memory_watch.poll(); - let after = self.prefs.cache_budgets(self.sys_memory); + self.take_memory_reading(reading) + } + + /// [`Session::memory_tick`] with the memory reading taken (`None`: no new one). + pub fn take_memory_reading(&mut self, reading: Option) -> crate::prefs::MemoryBudget { + let before = self.memory_budget(); + self.sys_memory = reading.or(self.sys_memory); + self.memory_low = self.sys_memory.is_some_and(|m| m.still_low(self.memory_low)); + let after = self.memory_budget(); + // (the process's memory is checked with each balance; a reading now and then also + // when the caches don't grow) + effectcraft_render::memory::Accountant::global().balance(); if after != before { self.apply_cache_budgets(); // Frontends re-apply their preview cache budget. @@ -130,6 +216,7 @@ impl Session { self.disk_cache = None; self.disk_watch = Default::default(); self.layer_cache.set_disk(None); + self.footage.set_disk_cache(None); return; }; // Tests: the Roto/Object Matte segment store below is one per process, so a test that @@ -154,6 +241,7 @@ impl Session { self.disk_cache = None; self.disk_watch = Default::default(); self.layer_cache.set_disk(None); + self.footage.set_disk_cache(None); return; } }, @@ -169,6 +257,11 @@ impl Session { // Used at once (no file is looked at first: each entry checks the source files it lists // when it is read, #3184). self.layer_cache.set_disk(Some(dc.clone())); + // Decoded footage channels (OpenEXR planes) persist there too (#3271). + self.footage.set_disk_cache(Some(dc.clone())); + // Its write queue counts in the common memory budget. + let queue: std::sync::Arc = dc.clone(); + effectcraft_render::memory::Accountant::global().register(&queue); // Roto Brush / Object Matte segmentations persist there too (held weakly: switching the // disk cache off drops it). let store: std::sync::Arc = dc.clone(); @@ -373,3 +466,9 @@ impl Session { } } } + +/// Settings ▸ Disk ▸ Network Footage Locations: path prefixes separated by `;` or new lines +/// (`P:\; Q:\renders`), each counted as network footage (#3271). +pub fn network_locations(setting: &str) -> Vec { + setting.split([';', '\n']).map(str::trim).filter(|s| !s.is_empty()).map(std::path::PathBuf::from).collect() +} diff --git a/crates/engine/src/system/sysinfo.rs b/crates/engine/src/system/sysinfo.rs index 80b51b462..8c594b214 100644 --- a/crates/engine/src/system/sysinfo.rs +++ b/crates/engine/src/system/sysinfo.rs @@ -24,7 +24,20 @@ pub struct SysMemory { impl SysMemory { /// The system is low on memory: less than 10% (or less than 1 GB) is available. pub fn is_low(&self) -> bool { - self.total > 0 && (self.available < self.total / 10 || self.available < 1 << 30) + self.total > 0 && self.available < self.low_threshold() + } + + /// Below this much available memory the system is low: 10% of the total, at least 1 GB. + fn low_threshold(&self) -> u64 { + (self.total / 10).max(1 << 30) + } + + /// Still low on memory, given whether it was (`was_low`): a low episode ends only once twice + /// the low threshold is available again. Without that margin, halving the caches frees just + /// enough memory to end it, the budgets double again and fill it, and the system is low + /// again a reading later. + pub fn still_low(&self, was_low: bool) -> bool { + if was_low { self.total > 0 && self.available < self.low_threshold().saturating_mul(2) } else { self.is_low() } } } @@ -139,6 +152,20 @@ pub fn parse_freebsd_sysctl(text: &str) -> Option { Some(SysMemory { total, available: free.saturating_mul(page).min(total) }) } +/// The physical memory this process uses now (its resident set, the working set on Windows), in +/// bytes; `None` where it can't be read (the browser). Cheap: the memory accountant reads it +/// with each balance (at most every 250 ms). +pub fn process_memory() -> Option { + #[cfg(not(target_arch = "wasm32"))] + { + memory_stats::memory_stats().and_then(|m| u64::try_from(m.physical_mem).ok()) + } + #[cfg(target_arch = "wasm32")] + { + None + } +} + /// Total and available physical memory, when the system reports them. pub fn memory() -> Option { #[cfg(target_os = "linux")] diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 62b797dbd..175d828a1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -67,6 +67,7 @@ mod text; mod text_edit; mod text_presets; mod three_d; +mod thumbnails; mod timeline; mod timeline_interchange; pub(crate) mod track; diff --git a/crates/engine/src/tests/aux_footage.rs b/crates/engine/src/tests/aux_footage.rs index 01c3c1c96..069ff7013 100644 --- a/crates/engine/src/tests/aux_footage.rs +++ b/crates/engine/src/tests/aux_footage.rs @@ -18,6 +18,7 @@ use crate::render::{FootageSource, RenderOpts}; struct Recorder { sets: Mutex>>, at_first_frame: Mutex>>>, + needs: Mutex>, } impl Recorder { @@ -37,6 +38,9 @@ impl FootageSource for Recorder { fn set_aux_footage(&self, paths: &[String]) { self.sets.lock().unwrap().push(paths.to_vec()); } + fn set_aux_needs(&self, needs: &[(String, effectcraft_raster::channels3d::AuxNeed)]) { + *self.needs.lock().unwrap() = needs.to_vec(); + } } struct Probe; @@ -198,3 +202,203 @@ fn a_watch_folder_render_gives_the_host_set_back() { s.execute("file.watchFolder", json!({"stop": true})).unwrap(); let _ = std::fs::remove_dir_all(&dir); } + +/// #3271: the parameters that pick the channels an effect reads can't be animated, as in After +/// Effects (no stopwatch there either): a keyframe or an expression is refused, the value still +/// changes; what a frame reads is exactly the channels picked. +#[test] +fn channel_selection_is_static_and_says_what_is_read() { + use effectcraft_raster::channels3d::{AuxLookup, AuxNeed}; + let rec = Arc::new(Recorder::default()); + let mut s = session(&rec); + let item = import(&mut s, "/renders/static.exr"); + let l = add_layer(&mut s, &item); + s.execute_checked("effect.apply", json!({"effect": "EXtractoR", "layers": [l]})).unwrap(); + let red = "effects/#1/red"; + let prop = |s: &Session, path: &str| { + let c = s.active_comp().unwrap(); + c.layer(effectcraft_project::LayerId(l)).unwrap().props.prop(path).unwrap().clone() + }; + assert!(prop(&s, red).static_only, "no stopwatch"); + assert!(s.execute_checked("prop.addKey", json!({"layer": l, "path": red})).is_err(), "no keyframe"); + assert!(s.execute_checked("prop.toggleKey", json!({"layer": l, "path": red})).is_err(), "no keyframe"); + assert!(s.execute_checked("prop.toggleAnimation", json!({"layer": l, "path": red})).is_err(), "no stopwatch"); + assert!(s.execute_checked("prop.setExpression", json!({"layer": l, "path": red, "expression": "'Z'"})).is_err(), "no expression"); + // (the forms that add the default expression: a toggle, and switching one on) + assert!(s.execute_checked("prop.setExpression", json!({"layer": l, "path": red})).is_err(), "no expression by toggle"); + assert!(s.execute_checked("prop.setExpression", json!({"layer": l, "path": red, "enabled": true})).is_err(), "no expression switched on"); + assert!(prop(&s, red).keys.is_empty() && prop(&s, red).expr.is_none()); + // The value changes; the channels read are exactly those picked. + s.execute_checked("prop.set", json!({"layer": l, "path": red, "value": "Z"})).unwrap(); + for c in ["green", "blue", "alpha"] { + s.execute_checked("prop.set", json!({"layer": l, "path": format!("effects/#1/{c}"), "value": ""})).unwrap(); + } + assert_eq!(prop(&s, red).value, effectcraft_keyframe::Value::Str("Z".into())); + let needs = rec.needs.lock().unwrap().clone(); + assert_eq!(needs, [("/renders/static.exr".to_string(), AuxNeed::Lookups(vec![AuxLookup::Name("Z".into())]))]); +} + +/// #3271: a document that animated a channel selection (it can't come from After Effects, nor +/// from EffectCraft now) opens with the first key's value as the static one, its keys and +/// expression dropped, and says so. +#[test] +fn a_keyed_channel_selection_opens_static() { + use effectcraft_keyframe::{Keyframe, Value as K}; + let rec = Arc::new(Recorder::default()); + let mut s = session(&rec); + let item = import(&mut s, "/renders/keyed.exr"); + let l = add_layer(&mut s, &item); + s.execute_checked("effect.apply", json!({"effect": "EXtractoR", "layers": [l]})).unwrap(); + let cid = s.active_comp_id().unwrap(); + { + let p = Arc::make_mut(&mut s.project); + let pr = p.comp_mut(cid).unwrap().layer_mut(effectcraft_project::LayerId(l)).unwrap().props.prop_mut("effects/#1/red").unwrap(); + // (as a document from before) + pr.static_only = false; + pr.keys = vec![Keyframe::new(Tick::ZERO, K::Str("Z".into())), Keyframe::new(Tick::from_seconds_f64(1.0), K::Str("N.X".into()))]; + } + let dir = std::env::temp_dir().join(format!("ec-3271-static-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("keyed.ecproj"); + s.execute_checked("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + let mut o = session(&rec); + o.drain_events(); + o.execute_checked("file.open", json!({"path": path.to_string_lossy()})).unwrap(); + let c = o.active_comp().unwrap(); + let pr = c.layer(effectcraft_project::LayerId(l)).unwrap().props.prop("effects/#1/red").unwrap(); + assert!(pr.static_only && pr.keys.is_empty() && pr.expr.is_none()); + assert_eq!(pr.value, K::Str("Z".into()), "the first key's value"); + let said = o.drain_events().into_iter().any(|e| matches!(e, crate::Event::Toast { message, .. } if message.contains("Channel selection"))); + assert!(said, "the loss is reported"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// #3271 review: an expression a channel selection has from an older document (set here by +/// hand) can still be switched off and removed. +#[test] +fn a_channel_selections_old_expression_can_be_removed() { + let rec = Arc::new(Recorder::default()); + let mut s = session(&rec); + let item = import(&mut s, "/renders/old-expr.exr"); + let l = add_layer(&mut s, &item); + s.execute_checked("effect.apply", json!({"effect": "EXtractoR", "layers": [l]})).unwrap(); + let cid = s.active_comp_id().unwrap(); + let red = "effects/#1/red"; + { + let p = Arc::make_mut(&mut s.project); + let pr = p.comp_mut(cid).unwrap().layer_mut(effectcraft_project::LayerId(l)).unwrap().props.prop_mut(red).unwrap(); + pr.expr = Some(effectcraft_project::Expression { text: "'Z'".into(), enabled: true }); + } + let expr = |s: &Session| s.active_comp().unwrap().layer(effectcraft_project::LayerId(l)).unwrap().props.prop(red).unwrap().expr.clone(); + s.execute_checked("prop.setExpression", json!({"layer": l, "path": red, "enabled": false})).unwrap(); + assert!(expr(&s).is_some_and(|e| !e.enabled), "switched off"); + assert!(s.execute_checked("prop.setExpression", json!({"layer": l, "path": red, "enabled": true})).is_err(), "not on again"); + s.execute_checked("prop.setExpression", json!({"layer": l, "path": red, "expression": ""})).unwrap(); + assert!(expr(&s).is_none(), "removed"); +} + +/// #3301 review: Convert Expression to Keyframes makes no keys on a channel selection that has an +/// expression from an older document: named, it is refused; in a selection, it is left out. +#[test] +fn a_channel_selections_old_expression_is_not_converted_to_keys() { + let rec = Arc::new(Recorder::default()); + let mut s = session(&rec); + let item = import(&mut s, "/renders/old-expr-keys.exr"); + let l = add_layer(&mut s, &item); + s.execute_checked("effect.apply", json!({"effect": "EXtractoR", "layers": [l]})).unwrap(); + let cid = s.active_comp_id().unwrap(); + let red = "effects/#1/red"; + { + let p = Arc::make_mut(&mut s.project); + let pr = p.comp_mut(cid).unwrap().layer_mut(effectcraft_project::LayerId(l)).unwrap().props.prop_mut(red).unwrap(); + pr.expr = Some(effectcraft_project::Expression { text: "'Z'".into(), enabled: true }); + } + let keys = |s: &Session| s.active_comp().unwrap().layer(effectcraft_project::LayerId(l)).unwrap().props.prop(red).unwrap().keys.len(); + assert!(s.execute_checked("prop.convertExpressionToKeyframes", json!({"layer": l, "path": red})).is_err(), "named: refused"); + assert_eq!(keys(&s), 0); + s.execute_checked("prop.select", json!({"layer": l, "path": red})).unwrap(); + let _ = s.execute_checked("prop.convertExpressionToKeyframes", json!({})); + assert_eq!(keys(&s), 0, "selected: left out"); +} + +/// An EXtractoR layer of `path` in a fresh session; the session and the layer. +fn extractor_layer(rec: &Arc, path: &str) -> (Session, u64) { + let mut s = session(rec); + let item = import(&mut s, path); + let l = add_layer(&mut s, &item); + s.execute_checked("effect.apply", json!({"effect": "EXtractoR", "layers": [l]})).unwrap(); + (s, l) +} + +/// #3271 review: an animation preset with keys or an expression on a channel selection applies +/// its first value, static, as a document does (an effect group, and a lone property). +#[test] +fn a_preset_keeps_a_channel_selection_static() { + use effectcraft_keyframe::{Keyframe, Value as K}; + let rec = Arc::new(Recorder::default()); + let (mut s, l) = extractor_layer(&rec, "/renders/preset.exr"); + let lid = effectcraft_project::LayerId(l); + let mut g = s.active_comp().unwrap().layer(lid).unwrap().effects().unwrap().groups().next().unwrap().clone(); + if let Some(pr) = g.get_mut("red") { + pr.static_only = false; + pr.keys = vec![Keyframe::new(Tick::ZERO, K::Str("Z".into())), Keyframe::new(Tick::from_seconds_f64(1.0), K::Str("N.X".into()))]; + pr.expr = Some(effectcraft_project::Expression { text: "'N.Y'".into(), enabled: true }); + } + let preset = json!({"effectcraftAnimationPreset": 2, "name": "keyed", "properties": [], "effects": [g]}); + let r = s.execute_checked("anim.applyPreset", json!({"preset": preset, "layers": [l]})).unwrap(); + assert_eq!(r["staticKept"].as_array().map(Vec::len), Some(1), "{r}"); + let c = s.active_comp().unwrap(); + let applied = c.layer(lid).unwrap().effects().unwrap().groups().nth(1).unwrap(); + let red = applied.get("red").unwrap(); + assert!(red.static_only && red.keys.is_empty() && red.expr.is_none()); + assert_eq!(red.value, K::Str("Z".into())); + // A lone property of the preset. + let path = "effects/#1/green"; + let preset = json!({"effectcraftAnimationPreset": 2, "name": "lone", "properties": [{"path": path, "value": K::Str("G".into()), "keys": [Keyframe::new(Tick::ZERO, K::Str("Y".into()))]}], "effects": []}); + s.execute_checked("anim.applyPreset", json!({"preset": preset, "layers": [l]})).unwrap(); + let green = s.active_comp().unwrap().layer(lid).unwrap().props.prop(path).unwrap().clone(); + assert!(green.keys.is_empty() && green.expr.is_none()); + assert_eq!(green.value, K::Str("Y".into())); +} + +/// #3271 review: Add Expression on a selection leaves a channel selection out (as Add Keyframe +/// does) and adds the others' expressions; named alone, the channel selection is an error. +#[test] +fn add_expression_on_a_selection_skips_a_channel_selection() { + let rec = Arc::new(Recorder::default()); + let (mut s, l) = extractor_layer(&rec, "/renders/select.exr"); + for path in ["effects/#1/red", "effects/#1/blackPoint"] { + s.execute_checked("prop.select", json!({"layer": l, "path": path, "add": true})).unwrap(); + } + s.execute_checked("prop.setExpression", json!({"expression": "0.25"})).unwrap(); + let c = s.active_comp().unwrap(); + let props = &c.layer(effectcraft_project::LayerId(l)).unwrap().props; + assert!(props.prop("effects/#1/red").unwrap().expr.is_none(), "left out"); + assert!(props.prop("effects/#1/blackPoint").unwrap().expr.is_some(), "the other one has it"); + assert!(s.execute_checked("prop.setExpression", json!({"layer": l, "path": "effects/#1/red", "expression": "'Z'"})).is_err()); +} + +/// #3271 review: File ▸ Import a project that animated a channel selection keeps its first value +/// and says so with the import's warnings. +#[test] +fn importing_a_keyed_channel_selection_says_so() { + use effectcraft_keyframe::{Keyframe, Value as K}; + let rec = Arc::new(Recorder::default()); + let (mut s, l) = extractor_layer(&rec, "/renders/imported.exr"); + let cid = s.active_comp_id().unwrap(); + { + let p = Arc::make_mut(&mut s.project); + let pr = p.comp_mut(cid).unwrap().layer_mut(effectcraft_project::LayerId(l)).unwrap().props.prop_mut("effects/#1/red").unwrap(); + pr.static_only = false; + pr.keys = vec![Keyframe::new(Tick::ZERO, K::Str("Z".into())), Keyframe::new(Tick::from_seconds_f64(1.0), K::Str("N.X".into()))]; + } + let dir = std::env::temp_dir().join(format!("ec-3271-import-static-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("keyed.ecproj"); + s.execute_checked("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + let mut o = session(&rec); + let r = o.execute_checked("file.importProject", json!({"path": path.to_string_lossy()})).unwrap(); + let said = r["warnings"].as_array().is_some_and(|w| w.iter().any(|w| w.as_str().is_some_and(|w| w.contains("channel selection")))); + assert!(said, "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/tests/crypto_pick.rs b/crates/engine/src/tests/crypto_pick.rs index 82fe21e71..066b08e06 100644 --- a/crates/engine/src/tests/crypto_pick.rs +++ b/crates/engine/src/tests/crypto_pick.rs @@ -198,8 +198,17 @@ fn picks_on_a_precomp_of_a_3d_comp() { } /// The matte the rendered Cryptomatte effect gives the picked ID at the buffer pixel under -/// `{x, y}`: the pick has to name the ID the effect's own input buffer samples there. +/// `{x, y}`: the pick has to name the ID the effect's own input buffer samples there. Below one +/// buffer pixel per layer pixel (reduced resolution, a smaller proxy) the effect shows the matte +/// box-filtered over the pixel (#3334): the picked ID is then lit, partly where the pixel holds +/// other IDs too. fn rendered_matte_of_pick(s: &mut Session, x: f64, y: f64, scale: f64) -> (String, f32) { + let (name, m, _) = rendered_matte_and_scale(s, x, y, scale); + (name, m) +} + +/// [`rendered_matte_of_pick`], and whether the buffer shows the box-filtered matte. +fn rendered_matte_and_scale(s: &mut Session, x: f64, y: f64, scale: f64) -> (String, f32, bool) { let r = s.execute_checked("effect.pickCryptomatte", json!({"effect": "Cryptomatte", "x": x, "y": y, "scale": scale, "mode": "replace"})).unwrap(); let fx = s.active_comp().unwrap().layers[0].effects().unwrap().groups().position(|g| g.match_id == "ec.3d.cryptomatte").unwrap() + 1; s.execute_checked("prop.set", json!({"path": format!("effects/#{fx}/matteOnly"), "value": true})).unwrap(); @@ -219,7 +228,7 @@ fn rendered_matte_of_pick(s: &mut Session, x: f64, y: f64, scale: f64) -> (Strin let buf = s.renderer(effectcraft_render::RenderOpts { scale, ..Default::default() }).content_buf(&ctx, layer).unwrap(); let (px, py) = buf.to_px([x, y]); let m = buf.img.get(px.floor() as i64, py.floor() as i64)[0]; - (r["name"].as_str().unwrap_or("?").to_string(), m) + (r["name"].as_str().unwrap_or("?").to_string(), m, effectcraft_effects::crypto_box_scale(buf.scale).is_some()) } /// Between 3/4 and full resolution footage keeps its native pixels: at 0.8 the effect samples @@ -239,8 +248,8 @@ fn pick_on_a_proxy_matches_the_proxy_sized_buffer() { let mut s = session(); let item = *s.project.items.iter().find(|(_, i)| matches!(i.kind, effectcraft_project::ItemKind::Footage(_))).unwrap().0; s.execute("file.setProxy", json!({"item": item.0, "path": "/renders/crypto_proxy.exr"})).unwrap(); - let (name, m) = rendered_matte_of_pick(&mut s, 6.5, 1.5, 1.0); - assert!(m >= 0.5, "picked {name:?}, but the render gives it matte {m} there"); + let (name, m, boxed) = rendered_matte_and_scale(&mut s, 6.5, 1.5, 1.0); + assert!(boxed && m > 0.0, "picked {name:?}, but the render gives it matte {m} there"); assert_eq!(name, "left"); } @@ -281,8 +290,9 @@ fn pick_maps_pixel_centres_bit_exactly_as_the_effect() { s.execute("layer.addItem", json!({"item": item})).unwrap(); s.execute_checked("effect.apply", json!({"effect": "Cryptomatte"})).unwrap(); s.execute("file.setProxy", json!({"item": item, "path": "/renders/edge_proxy.exr"})).unwrap(); - let (name, m) = rendered_matte_of_pick(&mut s, 118.0, 5.0, 1.0); - assert_eq!((name.as_str(), m), ("left", 1.0)); + let (name, m, boxed) = rendered_matte_and_scale(&mut s, 118.0, 5.0, 1.0); + assert!(boxed && m > 0.0, "{m}"); + assert_eq!(name, "left"); } struct EdgeProbe(Footage, Footage); @@ -312,8 +322,8 @@ fn mismatches(s: &mut Session, scales: &[f64], xs: impl Iterator + C if s.execute("effect.cryptomatteAt", json!({"effect": "Cryptomatte", "x": x, "y": y, "scale": scale})).unwrap().is_null() { continue; } - let (name, m) = rendered_matte_of_pick(s, x, y, scale); - if m < 0.5 { + let (name, m, boxed) = rendered_matte_and_scale(s, x, y, scale); + if if boxed { m <= 0.0 } else { m < 0.5 } { bad.push(format!("scale {scale} ({x:.2}, {y}): picked {name:?}, matte {m}")); } } diff --git a/crates/engine/src/tests/m137.rs b/crates/engine/src/tests/m137.rs index 13abe9c64..d0857280a 100644 --- a/crates/engine/src/tests/m137.rs +++ b/crates/engine/src/tests/m137.rs @@ -58,6 +58,39 @@ fn watch_folder_renders_queued_projects_and_writes_status() { assert!(host.execute("file.watchFolder", json!({"folder": "/no/such/folder"})).is_err()); } +#[test] +fn a_watch_folder_render_takes_the_hosts_memory_budget() { + // #3941: the Watch Folder renders each project in a session of its own, which had no memory + // reading: its Render Queue caches took the budget for unknown RAM, not the host's. + use crate::{ExportJob, ExportResult, Exporter}; + use effectcraft_project::render_queue::OutputFormat; + struct Budgets(std::sync::Mutex>>); + impl Exporter for Budgets { + fn formats(&self) -> Vec { + OutputFormat::ALL.to_vec() + } + fn export(&self, job: &ExportJob, _: &mut dyn FnMut(u64, u64) -> bool) -> Result { + self.0.lock().unwrap().push(job.caches.map(|c| c.gpu.budget())); + Ok(ExportResult { path: job.path.to_string(), ..Default::default() }) + } + } + let dir = out_dir("watch-folder-budget"); + let ex = Arc::new(Budgets(Default::default())); + let mut a = Session { exporter: Some(ex.clone()), ..Default::default() }; + a.execute("comp.new", json!({"name": "Shot", "width": 32, "height": 32, "frameRate": 10, "duration": 0.5})).unwrap(); + a.execute("renderQueue.add", json!({})).unwrap(); + a.execute("file.saveAs", json!({"path": dir.join("a.ecproj").to_string_lossy()})).unwrap(); + + let mut host = Session { exporter: Some(ex.clone()), ..Default::default() }; + // A 64 GB machine: 46.4 GB with the default reserve. + host.take_memory_reading(Some(crate::sysinfo::SysMemory { total: 64 << 30, available: 48 << 30 })); + let budget = host.export_cache_budget(); + assert_ne!(budget as u64, crate::prefs::FALLBACK_MEMORY_BUDGET); + host.execute("file.watchFolder", json!({"folder": dir.to_string_lossy()})).unwrap(); + host.execute("file.watchFolder", json!({"stop": true})).unwrap(); + assert_eq!(*ex.0.lock().unwrap(), vec![Some(budget)]); +} + #[test] fn vanishing_point_import_is_disabled_with_a_reason() { let mut s = Session::default(); diff --git a/crates/engine/src/tests/m145.rs b/crates/engine/src/tests/m145.rs index 831a05ead..c394a92cf 100644 --- a/crates/engine/src/tests/m145.rs +++ b/crates/engine/src/tests/m145.rs @@ -179,44 +179,160 @@ fn pick_whip_writes_match_names_without_compact_english() { // ---------------------------------------------------------------- pure setting helpers +/// #3298: one budget for the caches together, 80 % of the installed RAM left after RAM Reserved +/// for Other Applications (three fixed budgets of 5 GB in all, whatever the machine had, before). #[test] -fn cache_budgets_leave_reserved_ram_and_shrink_when_low() { +fn the_memory_budget_follows_the_installed_ram() { + use crate::prefs::{FALLBACK_MEMORY_BUDGET, MEMORY_HEADROOM_PERCENT, MIN_MEMORY_BUDGET}; use crate::sysinfo::SysMemory; + assert_eq!(MEMORY_HEADROOM_PERCENT, 80); let mut p = crate::prefs::Prefs::default(); - p.memory.layer_cache_mb = 4096; - p.memory.media_cache_mb = 4096; - p.memory.preview_cache_mb = 8192; - p.memory.ram_reserved_gb = 6; - let b = p.cache_budgets(None); - assert_eq!((b.layer >> 20, b.preview >> 20, b.capped), (4096, 8192, false)); - // 16 GB machine, 6 GB reserved: 16 GB of caches scaled into 10 GB. - let m = SysMemory { total: 16 << 30, available: 12 << 30 }; - let b = p.cache_budgets(Some(m)); - assert!(b.capped && !b.reduced); - assert!(((b.layer + b.media + b.preview) as i64 - (10i64 << 30)).abs() < 4, "{b:?}"); + assert_eq!(p.memory.ram_reserved_gb, 6); + let at = |gb: u64| Some(SysMemory { total: gb << 30, available: gb << 30 }); + for (gb, mb) in [(16u64, 8192u64), (64, 47_513), (128, 99_942)] { + let b = p.memory_budget(at(gb), false); + assert_eq!(b.bytes as u64 >> 20, mb, "{gb} GB: {b:?}"); + assert_eq!((b.installed, b.reduced), (Some(gb << 30), false)); + } + // Unknown RAM: the old three budgets' sum. + let b = p.memory_budget(None, false); + assert_eq!((b.bytes as u64, b.installed), (FALLBACK_MEMORY_BUDGET, None)); + assert_eq!(FALLBACK_MEMORY_BUDGET, 5 << 30); + // Less RAM than the reserve: the floor, for the caches together. + assert_eq!(p.memory_budget(at(4), false).bytes as u64, MIN_MEMORY_BUDGET); + // A larger reserve leaves less. + p.memory.ram_reserved_gb = 32; + assert_eq!(p.memory_budget(at(64), false).bytes as u64, (32u64 << 30) * 80 / 100); // Low on memory: halved; off: not. - let low = SysMemory { total: 16 << 30, available: 512 << 20 }; - let r = p.cache_budgets(Some(low)); - assert!(r.reduced && r.preview < b.preview / 2 + 2); + let b = p.memory_budget(at(64), true); + assert!(b.reduced && b.bytes as u64 == (32u64 << 30) * 80 / 200, "{b:?}"); p.memory.reduce_cache_when_low = false; - assert!(!p.cache_budgets(Some(low)).reduced); + assert!(!p.memory_budget(at(64), true).reduced); } -/// Eight stacked 1080p clips ran the browser build out of its 4 GiB of memory: the footage and -/// layer caches kept their desktop sizes there, beside the decoders' own frames. +/// Halving the caches frees memory: a low-memory episode ends only once twice the threshold is +/// available again, so the budget (and the toast) doesn't flip with every reading. #[test] -fn web_cache_budgets_leave_room_for_the_decoders() { - use crate::prefs::{WEB_LAYER_CACHE, WEB_MEDIA_CACHE}; - let mut p = crate::prefs::Prefs::default(); - p.memory.layer_cache_mb = 4096; - p.memory.media_cache_mb = 4096; - let web = p.cache_budgets_in(None, true); - assert_eq!((web.layer as u64, web.media as u64), (WEB_LAYER_CACHE, WEB_MEDIA_CACHE)); - assert_eq!(web.preview, p.cache_budgets_in(None, false).preview, "the RAM preview keeps its budget"); - // Smaller settings stay as they are; the desktop is unchanged. - p.memory.media_cache_mb = 128; - assert_eq!(p.cache_budgets_in(None, true).media, 128 << 20); - assert_eq!(p.cache_budgets_in(None, false).layer, 4096 << 20); +fn low_memory_budgets_hold_until_the_system_recovers() { + use crate::sysinfo::SysMemory; + // 16 GB: low below 1.6 GB available, recovered from 3.2 GB. + let at = |available: u64| SysMemory { total: 16 << 30, available }; + assert!(at(1 << 30).still_low(false)); + assert!(!at(2 << 30).still_low(false)); + assert!(at(2 << 30).still_low(true), "not recovered yet"); + assert!(!at(4 << 30).still_low(true)); + let mut s = Session::default(); + assert!(!s.memory_budget().reduced, "no reading: nothing reduced"); + s.sys_memory = Some(at(2 << 30)); + assert!(!s.memory_budget().reduced); + s.memory_low = true; + assert!(s.memory_budget().reduced, "the episode holds"); + s.sys_memory = Some(at(4 << 30)); + assert!(!s.memory_budget().reduced, "recovered"); +} + +/// #3301 review: the System Compatibility Report shows the cache budget in force, the one the +/// session applied from its last reading, not one worked out from a fresh reading. +#[test] +fn the_report_shows_the_budget_in_force() { + use crate::sysinfo::SysMemory; + let mut s = Session::default(); + // (a reading no machine running the test has: 3 GiB, of which 0.1 GiB is free, low) + let applied = s.take_memory_reading(Some(SysMemory { total: 3 << 30, available: 100 << 20 })); + let report = crate::cmd::app_more::system_report(&s); + let gb = format!("{:.1} GB", applied.bytes as f64 / (1u64 << 30) as f64); + assert_eq!(report["caches"]["budget"], gb.as_str(), "{report}"); + assert_eq!(report["caches"]["reduced"], applied.reduced); +} + +/// The memory readings over a low-memory episode: the budget is halved once, stays halved while +/// the system has not recovered (a reading between the low line and twice it), and the toast +/// shows once; recovered, the budget is whole again, and the next episode toasts again. +#[test] +fn a_low_memory_episode_toasts_once_and_reapplies_the_budget() { + use crate::sysinfo::SysMemory; + let at = |available: u64| Some(SysMemory { total: 64 << 30, available }); + let mut s = Session::default(); + s.drain_events(); + let toasts = |s: &mut Session| s.drain_events().into_iter().filter(|e| matches!(e, crate::Event::Toast { .. })).count(); + let whole = s.take_memory_reading(at(40 << 30)); + assert!(!whole.reduced); + assert_eq!(s.layer_cache.budget(), whole.bytes, "applied"); + let revision = s.prefs_revision; + // Low (below 6.4 GB): halved, re-applied, one toast. + let low = s.take_memory_reading(at(4 << 30)); + assert!(low.reduced && low.bytes == whole.bytes / 2, "{low:?}"); + assert_eq!(s.layer_cache.budget(), low.bytes); + assert!(s.prefs_revision > revision, "frontends re-apply theirs"); + assert_eq!(toasts(&mut s), 1); + // Between the low line and twice it, then low again: still the same episode. + for available in [8u64 << 30, 3 << 30, 10 << 30] { + assert!(s.take_memory_reading(at(available)).reduced, "{available}"); + } + assert_eq!(toasts(&mut s), 0, "one toast per episode"); + // Recovered (13 GB, over twice 6.4 GB): whole again; a new episode toasts again. + assert_eq!(s.take_memory_reading(at(13 << 30)), whole); + assert_eq!(s.layer_cache.budget(), whole.bytes); + assert!(s.take_memory_reading(at(2 << 30)).reduced); + assert_eq!(toasts(&mut s), 1); +} + +/// #3321: Cache Frames When Idle is on by default. Settings saved before held the old default +/// (off) and turn it on once; off saved after that is the user's choice and stays. +#[test] +fn cache_frames_when_idle_is_on_by_default() { + use crate::prefs::Prefs; + assert!(Prefs::default().previews.cache_frames_when_idle); + assert!(Prefs::from_json(r#"{"version": 6, "previews": {"fastPreviews": true}}"#).previews.cache_frames_when_idle, "not saved: on"); + // An old file with the old default: on, once. + let old = Prefs::from_json(r#"{"version": 5, "previews": {"cacheFramesWhenIdle": false}}"#); + assert!(old.previews.cache_frames_when_idle, "the old default becomes the new one"); + assert!(Prefs::from_json(r#"{"version": 4, "previews": {"cacheFramesWhenIdle": true}}"#).previews.cache_frames_when_idle, "on stays on"); + // Turned off after the migration: stays off, also after the next save. + let off = Prefs::from_json(r#"{"version": 6, "previews": {"cacheFramesWhenIdle": false}}"#); + assert!(!off.previews.cache_frames_when_idle, "saved off: off"); + let mut p = old; + p.previews.cache_frames_when_idle = false; + assert!(!Prefs::from_json(&p.to_json()).previews.cache_frames_when_idle, "and after the next save"); +} + +/// #3298: settings saved with the three cache budgets (version 4, or a later file that still +/// has them) keep RAM Reserved for Other Applications and lose the budgets: they are not kept +/// as unknown keys and written back. +#[test] +fn the_old_cache_budgets_are_dropped_from_saved_settings() { + use crate::prefs::Prefs; + for version in [4, 5] { + let old = format!( + r#"{{"version": {version}, "memory": {{"ramReservedGb": 12, "layerCacheMb": 2048, "mediaCacheMb": 4096, "previewCacheMb": 8192, "reduceCacheWhenLow": false}}}}"# + ); + let p = Prefs::from_json(&old); + assert_eq!((p.memory.ram_reserved_gb, p.memory.reduce_cache_when_low), (12, false), "v{version}"); + let saved: Value = serde_json::from_str(&p.to_json()).unwrap(); + let memory = saved["memory"].as_object().unwrap(); + for key in ["layerCacheMb", "mediaCacheMb", "previewCacheMb"] { + assert!(!memory.contains_key(key), "v{version}: {key} dropped"); + } + assert_eq!(memory["ramReservedGb"], json!(12)); + } +} + +/// What each cache may hold by itself: on the desktop all of the budget (the accountant +/// decides), in the browser its cap, as before one budget: the RAM preview keeps its 3 GB and the +/// layer and footage caches their 512 / 256 MB (#3298 review: the preview may not take the whole +/// web budget), all within the web budget. +#[test] +fn caches_have_no_limit_of_their_own_below_the_budget() { + use crate::prefs::{MemoryBudget, WEB_LAYER_CACHE, WEB_MEDIA_CACHE, WEB_MEMORY_BUDGET, WEB_PREVIEW_CACHE}; + let b = |bytes: usize| MemoryBudget { bytes, installed: None, reduced: false }; + let desktop = b(40 << 30).caps(false); + assert_eq!((desktop.layer, desktop.footage, desktop.preview), (40 << 30, 40 << 30, 40 << 30)); + let web = b(WEB_MEMORY_BUDGET as usize).caps(true); + assert_eq!((web.layer as u64, web.footage as u64, web.preview as u64), (WEB_LAYER_CACHE, WEB_MEDIA_CACHE, WEB_PREVIEW_CACHE)); + assert_eq!(WEB_PREVIEW_CACHE, 3 << 30, "the RAM preview keeps its budget"); + const { assert!(WEB_MEMORY_BUDGET <= 3584 << 20 && WEB_MEMORY_BUDGET >= WEB_PREVIEW_CACHE) }; + let small = b(100 << 20).caps(true); + assert_eq!((small.layer, small.footage, small.preview), (100 << 20, 100 << 20, 100 << 20)); } #[test] diff --git a/crates/engine/src/tests/settings.rs b/crates/engine/src/tests/settings.rs index 42bcefc97..20a1e93fd 100644 --- a/crates/engine/src/tests/settings.rs +++ b/crates/engine/src/tests/settings.rs @@ -76,8 +76,8 @@ fn prefs_migrate_old_layout_and_keep_unknown_keys() { assert_eq!(p.labels[1].name, "Sun"); assert_eq!(p.labels[2].name, "Aqua"); assert_eq!(p.labels.len(), 16); - // A bad value falls back to that page's defaults; other pages survive. - assert_eq!(p.memory.layer_cache_mb, 1024); + // The old cache budgets (#3298) are dropped, not kept as unknown keys. + assert_eq!(p.memory, crate::prefs::Memory::default()); // Unknown keys (a newer version's) are kept and written back. let again: serde_json::Value = serde_json::from_str(&p.to_json()).unwrap(); assert_eq!(again["futureSetting"], json!({"x": 1})); @@ -351,10 +351,16 @@ fn renamed_labels_show_in_the_label_menu_and_apply_by_name() { } #[test] +/// #3298: the caches share one budget from RAM Reserved for Other Applications; a workload of +/// footage only may use nearly all of it (it was held to the 1 GB Footage Frame Cache). fn cache_budgets_are_applied() { let mut s = Session::default(); - s.execute("prefs.set", json!({"key": "memory.layerCacheMb", "value": 128})).unwrap(); - assert_eq!(s.layer_cache.budget(), 128 << 20); + assert!(s.layer_cache.budget() > 0); + s.sys_memory = Some(crate::sysinfo::SysMemory { total: 64 << 30, available: 60 << 30 }); + s.execute("prefs.set", json!({"key": "memory.ramReservedGb", "value": 6})).unwrap(); + let budget = (58usize << 30) * 80 / 100; + assert_eq!(s.memory_budget().bytes, budget); + assert_eq!(s.layer_cache.budget(), budget, "no layer cache budget of its own"); struct Src(std::sync::Mutex); impl effectcraft_render::FootageSource for Src { fn frame(&self, _: effectcraft_project::ItemId, _: &effectcraft_project::Footage, _: effectcraft_time::Tick) -> Option> { @@ -366,8 +372,9 @@ fn cache_budgets_are_applied() { } let src = Arc::new(Src(Default::default())); s.footage = src.clone(); - s.execute("prefs.set", json!({"key": "memory.mediaCacheMb", "value": 256})).unwrap(); - assert_eq!(*src.0.lock().unwrap(), 256 << 20); + s.execute("prefs.set", json!({"key": "memory.ramReservedGb", "value": 32})).unwrap(); + assert_eq!(*src.0.lock().unwrap(), (32usize << 30) * 80 / 100, "the footage frames may use the whole budget"); + assert!(s.execute("prefs.set", json!({"key": "memory.mediaCacheMb", "value": 256})).is_err(), "no such setting any more"); } #[test] diff --git a/crates/engine/src/tests/thumbnails.rs b/crates/engine/src/tests/thumbnails.rs new file mode 100644 index 000000000..abd6ca906 --- /dev/null +++ b/crates/engine/src/tests/thumbnails.rs @@ -0,0 +1,67 @@ +//! #3271: Project panel thumbnails are keyed by what they show, not by the project's revision: +//! an edit elsewhere keeps a comp's thumbnail, an edit of the comp, another time or size, and a +//! footage reload give it a new key. + +use effectcraft_time::Tick; +use serde_json::json; + +use crate::Session; + +#[test] +fn thumbnail_keys_follow_the_content() { + let mut s = Session::default(); + s.execute("comp.new", json!({"name": "A", "width": 64, "height": 32, "frameRate": 24, "duration": 2})).unwrap(); + let a = s.active_comp_id().unwrap(); + s.execute("layer.newSolid", json!({"name": "S", "color": "#ff8000"})).unwrap(); + let key = |s: &Session| s.thumbnail_key(a, Tick::ZERO, 192).unwrap(); + let k0 = key(&s); + // Another comp: the project changed, this comp's picture didn't. + s.execute("comp.new", json!({"name": "B", "width": 16, "height": 16, "frameRate": 24, "duration": 1})).unwrap(); + assert_eq!(key(&s), k0, "an edit elsewhere keeps the key"); + assert_ne!(s.thumbnail_key(a, Tick::from_seconds_f64(0.5), 192).unwrap(), k0, "another time"); + assert_ne!(s.thumbnail_key(a, Tick::ZERO, 96).unwrap(), k0, "another size"); + // An edit of the comp itself. + std::sync::Arc::make_mut(&mut s.project).comp_mut(a).unwrap().background = [0.2, 0.4, 0.6]; + assert_ne!(key(&s), k0, "an edit of the comp gives a new key"); + // A reload: files may have changed without the project knowing. + let before = key(&s); + s.forget_decoded(&effectcraft_project::Footage::default()); + assert_ne!(key(&s), before, "a reload gives a new key"); +} + +/// #3271 review: File ▸ Reload Footage gives the footage's thumbnail a new key (the file may +/// have changed without the project knowing). +#[test] +fn reload_footage_gives_thumbnails_a_new_key() { + struct Probe; + impl crate::Importer for Probe { + fn probe(&self, path: &str) -> Result { + Ok(effectcraft_project::Footage { + path: path.into(), + kind: effectcraft_project::FootageKind::Still, + width: 1, + height: 1, + has_video: true, + ..Default::default() + }) + } + } + let dir = std::env::temp_dir().join(format!("ec-3271-thumb-reload-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("a.png"); + std::fs::write(&file, b"aa").unwrap(); + let mut s = Session { importer: Some(std::sync::Arc::new(Probe)), ..Default::default() }; + let f = effectcraft_project::Footage { + path: file.to_string_lossy().to_string(), + kind: effectcraft_project::FootageKind::Still, + width: 1, + height: 1, + has_video: true, + ..Default::default() + }; + let id = s.edit("add", None, |p, _| Ok(p.add_item("a", effectcraft_color::Label::None, None, effectcraft_project::ItemKind::Footage(f)))).unwrap(); + let before = s.thumbnail_key(id, Tick::ZERO, 192).unwrap(); + s.execute_checked("file.reloadFootage", json!({"item": id.0})).unwrap(); + assert_ne!(s.thumbnail_key(id, Tick::ZERO, 192).unwrap(), before); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml index 1bf883df3..6b93a8a7c 100644 --- a/crates/export/Cargo.toml +++ b/crates/export/Cargo.toml @@ -18,14 +18,15 @@ craft-video = { workspace = true } craft-audio = { workspace = true } craft-media = { workspace = true } craft-gif = { workspace = true } +craft-exr = { workspace = true, features = ["decode"] } image = { workspace = true, features = ["png", "jpeg", "tiff", "exr", "tga"] } -exr = { workspace = true } rayon = { workspace = true } web-time = { workspace = true } thiserror = { workspace = true } log = { workspace = true } [dev-dependencies] +exr = { workspace = true } gif = { workspace = true } tempfile = { workspace = true } effectcraft-media = { workspace = true } diff --git a/crates/export/src/exr_out.rs b/crates/export/src/exr_out.rs index 43467629a..cefa81a07 100644 --- a/crates/export/src/exr_out.rs +++ b/crates/export/src/exr_out.rs @@ -12,40 +12,25 @@ use std::io::{Seek, Write}; +use craft_exr::decode::{Compression, Result, SampleDepth}; use effectcraft_project::render_queue::{ExrBitDepth, ExrCompression}; -use exr::meta::attribute::Chromaticities; -use exr::prelude::{Blocks, Compression, Encoding, Image, Layer, LayerAttributes, LineOrder, SpecificChannels, Vec2, WritableImage, f16}; -/// The largest finite half float. -const HALF_MAX: f32 = 65_504.0; - -/// A sample as half float: rounded to the nearest half (ties to even), held to ±65 504 so an -/// over-range render doesn't turn into infinity. NaN stays NaN. -fn to_half(v: f32) -> f16 { - f16::from_f32(v.clamp(-HALF_MAX, HALF_MAX)) -} - -/// The `exr` crate's compression for an Output Module setting. +/// The `craft-exr` compression for an Output Module setting. pub fn compression(c: ExrCompression) -> Compression { match c { - ExrCompression::None => Compression::Uncompressed, - ExrCompression::Rle => Compression::RLE, - ExrCompression::Zips => Compression::ZIP1, - ExrCompression::Zip => Compression::ZIP16, - ExrCompression::Piz => Compression::PIZ, - ExrCompression::Pxr24 => Compression::PXR24, + ExrCompression::None => Compression::None, + ExrCompression::Rle => Compression::Rle, + ExrCompression::Zips => Compression::Zip1, + ExrCompression::Zip => Compression::Zip16, + ExrCompression::Piz => Compression::Piz, + ExrCompression::Pxr24 => Compression::Pxr24, ExrCompression::B44 => Compression::B44, - ExrCompression::B44a => Compression::B44A, - ExrCompression::Dwaa => Compression::DWAA(None), - ExrCompression::Dwab => Compression::DWAB(None), + ExrCompression::B44a => Compression::B44a, + ExrCompression::Dwaa => Compression::Dwaa, + ExrCompression::Dwab => Compression::Dwab, } } -/// Scan lines, top to bottom, with compression `c`. -fn encoding(c: ExrCompression) -> Encoding { - Encoding { compression: compression(c), blocks: Blocks::ScanLines, line_order: LineOrder::Increasing } -} - /// Write `w`×`h` RGBA pixels (`data`: four samples per pixel as they are to be written, /// premultiplied, rows top to bottom) as one OpenEXR frame, its blocks compressed in parallel as before. A pixel `data` /// doesn't cover is written as transparent black. @@ -58,56 +43,38 @@ pub fn write_rgba( (w, h): (usize, usize), (c, depth): (ExrCompression, ExrBitDepth), chroma: Option<[[f32; 2]; 4]>, -) -> exr::error::UnitResult { - let chroma = chroma.map(|[red, green, blue, white]| { - let v = |[x, y]: [f32; 2]| Vec2(x, y); - Chromaticities { red: v(red), green: v(green), blue: v(blue), white: v(white) } - }); - let row = w.saturating_mul(4); - let px = move |p: Vec2| -> [f32; 4] { - let o = p.y().saturating_mul(row).saturating_add(p.x().saturating_mul(4)); - match data.get(o..o.saturating_add(4)) { - Some(&[r, g, b, a]) => [r, g, b, a], - _ => [0.0; 4], - } +) -> Result<()> { + let sample_depth = match depth { + ExrBitDepth::Float => SampleDepth::Float, + ExrBitDepth::Half => SampleDepth::Half, }; - match depth { - ExrBitDepth::Float => { - let mut image = Image::from_layer(Layer::new( - (w, h), - LayerAttributes::default(), - encoding(c), - SpecificChannels::rgba(move |p: Vec2| { - let [r, g, b, a] = px(p); - (r, g, b, a) - }), - )); - image.attributes.chromaticities = chroma; - image.write().to_buffered(file) - } - ExrBitDepth::Half => { - let mut image = Image::from_layer(Layer::new( - (w, h), - LayerAttributes::default(), - encoding(c), - SpecificChannels::rgba(move |p: Vec2| { - let [r, g, b, a] = px(p).map(to_half); - (r, g, b, a) - }), - )); - image.attributes.chromaticities = chroma; - image.write().to_buffered(file) - } - } + craft_exr::decode::write_rgba(file, data, w as u32, h as u32, sample_depth, compression(c), chroma) } #[cfg(test)] mod tests { use super::*; - use exr::prelude::{ReadChannels, ReadLayers}; - use exr::prelude::{SampleType, read}; + use exr::prelude::{ + Encoding, Image, Layer, LayerAttributes, LineOrder, ReadChannels, ReadLayers, SampleType, SpecificChannels, Vec2, WritableImage, f16, read, + }; use std::io::Cursor; + fn exr_compression(c: ExrCompression) -> exr::compression::Compression { + use exr::compression::Compression as C; + match c { + ExrCompression::None => C::Uncompressed, + ExrCompression::Rle => C::RLE, + ExrCompression::Zips => C::ZIP1, + ExrCompression::Zip => C::ZIP16, + ExrCompression::Piz => C::PIZ, + ExrCompression::Pxr24 => C::PXR24, + ExrCompression::B44 => C::B44, + ExrCompression::B44a => C::B44A, + ExrCompression::Dwaa => C::DWAA(None), + ExrCompression::Dwab => C::DWAB(None), + } + } + /// A frame with a smooth gradient, grain, over-range highlights, a hard-edged high-contrast /// block and a soft alpha ramp (premultiplied), like a render with text over a plate. fn frame(w: usize, h: usize) -> Vec { @@ -172,7 +139,7 @@ mod tests { }; let ty = if depth == ExrBitDepth::Half { SampleType::F16 } else { SampleType::F32 }; for c in ExrCompression::ALL { - assert_eq!(c.is_lossy(depth), !compression(c).is_lossless_for(ty), "{c:?} {depth:?}"); + assert_eq!(c.is_lossy(depth), !exr_compression(c).is_lossless_for(ty), "{c:?} {depth:?}"); let bytes = write(&src, (w, h), c, depth); if c.is_lossy(depth) { assert!(bytes.len() < write(&src, (w, h), ExrCompression::None, depth).len(), "{c:?} {depth:?}: smaller than None"); @@ -205,7 +172,7 @@ mod tests { let meta = exr::meta::MetaData::read_from_buffered(Cursor::new(&bytes), false).unwrap(); assert_eq!(meta.headers.len(), 1); assert_eq!(meta.headers[0].blocks, exr::meta::BlockDescription::ScanLines, "{c:?}"); - assert_eq!(meta.headers[0].compression, compression(c), "{c:?}"); + assert_eq!(meta.headers[0].compression, exr_compression(c), "{c:?}"); assert_eq!(meta.headers[0].line_order, LineOrder::Increasing); } } diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs index 081eb3d7b..16d65fabe 100644 --- a/crates/export/src/lib.rs +++ b/crates/export/src/lib.rs @@ -127,6 +127,11 @@ pub struct JobOptions<'a> { /// a GPU frame measured a frame's working memory. `None`: CPU frames are capped only by /// `EFFECTCRAFT_CPU_INFLIGHT`. pub free_memory: Option<&'a (dyn Fn() -> Option + Sync)>, + /// What each of the job's own two layer caches (one per compositor) may hold when it has no + /// Render Queue run's caches (#3941): the session's budget for an export's caches. Both are + /// in the memory accountant's common budget, so together with the other caches they stay + /// within it. `None`: [`CACHE_BUDGET`]. + pub cache_budget: Option, } /// The layer caches of a Render Queue run (see [`JobOptions::caches`]): one per compositor, diff --git a/crates/export/src/pipeline.rs b/crates/export/src/pipeline.rs index a0e4980ec..1cba495f5 100644 --- a/crates/export/src/pipeline.rs +++ b/crates/export/src/pipeline.rs @@ -89,8 +89,9 @@ const PROBE_CPU_FRAMES: usize = 8; /// Jobs shorter than this render on the project's compositor without measuring: the frames /// the slower one renders for the measurement would cost more than they could save. const PROBE_MIN_JOB: u64 = 12; -/// Bytes each of a job's two layer caches (one per compositor) may hold: together what the -/// job's single cache held before (`LayerCache::default()`). +/// Bytes each of a job's own two layer caches (one per compositor) may hold when the caller +/// gives no budget ([`crate::JobOptions::cache_budget`]): together what the job's single cache +/// held before (`LayerCache::default()`). pub const CACHE_BUDGET: usize = 1 << 29; /// The faster compositor from measured milliseconds per frame (`None`: not measured, or the @@ -276,7 +277,7 @@ pub(crate) struct Cx<'a> { /// A job's layer caches: its own, or those of the Render Queue run it belongs to. enum Caches<'a> { - Own { gpu: Box, cpu: Box }, + Own { gpu: std::sync::Arc, cpu: std::sync::Arc }, Run(crate::JobCaches<'a>), } @@ -338,7 +339,17 @@ impl<'a> Cx<'a> { let frame_times = (job.options.log == RenderLog::PlusPerFrameInfo).then(|| Mutex::new(Vec::new())); let caches = match job.options.caches { Some(c) => Caches::Run(c), - None => Caches::Own { gpu: Box::new(LayerCache::new(CACHE_BUDGET)), cpu: Box::new(LayerCache::new(CACHE_BUDGET)) }, + None => { + // (in the memory accountant's common budget: they give way with the other caches) + let budget = job.options.cache_budget.unwrap_or(CACHE_BUDGET); + let (gpu, cpu) = (std::sync::Arc::new(LayerCache::new(budget)), std::sync::Arc::new(LayerCache::new(budget))); + let accountant = effectcraft_render::memory::Accountant::global(); + for cache in [&gpu, &cpu] { + let holder: std::sync::Arc = cache.clone(); + accountant.register(&holder); + } + Caches::Own { gpu, cpu } + } }; // With deferred readbacks, buffers computed from a missed pass's placeholders are not kept. for r in [crate::JobRenderer::Gpu, crate::JobRenderer::Cpu] { @@ -1281,6 +1292,35 @@ mod tests { assert_eq!(Cx::new(&job).gpu_cap(), None, "no accelerator"); } + #[test] + fn a_one_off_exports_caches_take_the_budget_it_is_given() { + // #3941: a one-off export's own caches had 512 MiB each whatever the memory budget; the + // session's budget for an export's caches comes with the job now. + use effectcraft_project::render_queue::{OutputFormat, OutputModule, RenderSettings}; + use effectcraft_render::NoFootage; + let (settings, output) = (RenderSettings::default(), OutputModule::for_format(OutputFormat::PngSequence)); + let p = Project::default(); + for (given, want) in [(None, CACHE_BUDGET), (Some(1500 << 20), 1500 << 20)] { + let job = Job { + project: &p, + footage: &NoFootage, + expr: None, + accel: None, + comp: effectcraft_project::ItemId(0), + settings: &settings, + output: &output, + path: "/c/f_[#####].png", + sink: None, + nested_switches: true, + options: crate::JobOptions { cache_budget: given, ..Default::default() }, + }; + let cx = Cx::new(&job); + for r in [crate::JobRenderer::Gpu, crate::JobRenderer::Cpu] { + assert_eq!(cx.caches.of(r).budget(), want, "{given:?} {r:?}"); + } + } + } + /// A resumed sequence can start with one or two missing frames. Once emitted, their /// compositor must also be used by every later batch and the item's other output modules. #[test] diff --git a/crates/gpu/src/fx_depth.rs b/crates/gpu/src/fx_depth.rs index 3f348c47d..daef68a3f 100644 --- a/crates/gpu/src/fx_depth.rs +++ b/crates/gpu/src/fx_depth.rs @@ -6,12 +6,15 @@ //! extra texture at the aux resolution: the planes an effect reads are packed into its four //! channels (alpha = 1 marks "inside the aux image"). `fxd_lookup` resamples it nearest-neighbour //! onto the buffer grid with the CPU's exact index arithmetic (layer position × aux scale, -//! floored), and the effect kernels work on that buffer-sized plane. Cryptomatte packs a -//! per-aux-pixel reduction of its rank layers (selection coverage and the coverage-weighted ID -//! colours, measured on the CPU) instead of the raw ranks. Fog 3D's Gradient Layer is rendered -//! by the host on the CPU (it is another layer) and uploaded. +//! floored), and the effect kernels work on that buffer-sized plane. Cryptomatte uploads its +//! finished output instead of the raw ranks (#3334): the matte as one R32F plane (the Colors +//! display: its RGBA pixels), made on the CPU from the unscaled channels at source resolution, +//! box-filtered below render scale 1 and kept in [`matte_cache`]. Fog 3D's Gradient Layer is +//! rendered by the host on the CPU (it is another layer) and uploaded. -use effectcraft_effects::{Buf, EffectCtx}; +use std::sync::Arc; + +use effectcraft_effects::{Buf, CryptoOutput, CryptoPlane, EffectCtx}; use effectcraft_keyframe::Value; use effectcraft_raster::channels3d::BACKGROUND_DEPTH; use effectcraft_raster::{AuxChannels, Image}; @@ -19,6 +22,8 @@ use effectcraft_raster::{AuxChannels, Image}; use crate::context::{Enc, GpuImage, Params}; use crate::effects::{GBuf, gaussian_blur}; +pub(crate) mod matte_cache; + /// Compute entry points in `fx_depth.wgsl`. pub(crate) const KERNELS: &[&str] = &["fxd_lookup", "fxd_point", "fxd_dof_f", "fxd_dof_level", "fxd_avg"]; @@ -73,12 +78,12 @@ fn aux_texture(e: &mut Enc, a: &AuxChannels, planes: [Option<&[f32]>; 4]) -> Opt e.g.upload_image(&img) } -/// Resample an aux texture onto the buffer grid (nearest; `fill` outside the aux image), -/// sampling each buffer pixel at sub-pixel position `at`. -fn lookup(e: &mut Enc, b: &GBuf, a: &AuxChannels, tex: &GpuImage, at: [f64; 2], fill: [f32; 4]) -> GpuImage { +/// Resample an aux texture (`tex_scale` texels per layer pixel) onto the buffer grid (nearest; +/// `fill` outside the aux image), sampling each buffer pixel at sub-pixel position `at`. +fn lookup(e: &mut Enc, b: &GBuf, tex_scale: f64, tex: &GpuImage, at: [f64; 2], fill: [f32; 4]) -> GpuImage { let inv = 1.0 / b.scale.max(1e-9); let mut p = Params::default(); - p.f[0] = [b.offset[0] as f32, b.offset[1] as f32, inv as f32, a.scale as f32]; + p.f[0] = [b.offset[0] as f32, b.offset[1] as f32, inv as f32, tex_scale as f32]; p.f[1] = [at[0] as f32, at[1] as f32, 0.0, 0.0]; p.f[2] = fill; let out = e.scratch(b.img.width, b.img.height); @@ -116,14 +121,14 @@ fn channel_extract(e: &mut Enc, ctx: &EffectCtx, b: GBuf, a: &AuxChannels) -> Op p.u[0] = [0, mode, pr.b("clampOutput") as u32, pr.b("invertDepthMap") as u32]; p.f[0] = [pr.f("blackPoint") as f32, pr.f("whitePoint") as f32, 0.0, 0.0]; if !pr.b("antialias") { - let plane = lookup(e, &b, a, &tex, [0.5, 0.5], [0.0; 4]); + let plane = lookup(e, &b, a.scale, &tex, [0.5, 0.5], [0.0; 4]); return point(e, &p, b, &plane); } // Anti-alias: four sub-pixel samples, summed in order and scaled once (as the CPU does). let (w, h) = (b.img.width, b.img.height); let mut acc: Option = None; for s in [[0.25, 0.25], [0.75, 0.25], [0.25, 0.75], [0.75, 0.75]] { - let plane = lookup(e, &b, a, &tex, s, [0.0; 4]); + let plane = lookup(e, &b, a.scale, &tex, s, [0.0; 4]); let one = e.scratch(w, h); e.pixels("fxd_point", &p, &b.img, Some(&plane), &one, None); acc = Some(match acc { @@ -146,7 +151,7 @@ fn channel_extract(e: &mut Enc, ctx: &EffectCtx, b: GBuf, a: &AuxChannels) -> Op fn depth_plane(e: &mut Enc, b: &GBuf, a: &AuxChannels) -> Option { let z = a.depth()?; let tex = aux_texture(e, a, [Some(z), None, None, None])?; - Some(lookup(e, b, a, &tex, [0.5, 0.5], [BACKGROUND_DEPTH, 0.0, 0.0, 0.0])) + Some(lookup(e, b, a.scale, &tex, [0.5, 0.5], [BACKGROUND_DEPTH, 0.0, 0.0, 0.0])) } fn depth_matte(e: &mut Enc, ctx: &EffectCtx, b: GBuf, a: &AuxChannels) -> Option { @@ -236,7 +241,7 @@ fn id_matte(e: &mut Enc, ctx: &EffectCtx, b: GBuf, a: &AuxChannels) -> Option Option< let Some(ids) = id_plane(a, pr.e("channelType")) else { return Some(b) }; let max_id = ids.iter().cloned().fold(1.0f32, f32::max); let tex = aux_texture(e, a, [Some(ids), None, None, None])?; - let plane = lookup(e, &b, a, &tex, [0.5, 0.5], [0.0; 4]); + let plane = lookup(e, &b, a.scale, &tex, [0.5, 0.5], [0.0; 4]); let mut p = op(6); p.u[0][1] = pr.e("display"); p.f[0] = [pr.f("id").round() as f32, max_id, 0.0, 0.0]; @@ -266,25 +271,67 @@ fn identifier(e: &mut Enc, ctx: &EffectCtx, b: GBuf, a: &AuxChannels) -> Option< // ---------------------------------------------------------------- Cryptomatte -fn cryptomatte(e: &mut Enc, ctx: &EffectCtx, b: GBuf, a: &AuxChannels) -> Option { +fn cryptomatte(e: &mut Enc, ctx: &EffectCtx, b: GBuf, a: &Arc) -> Option { let pr = ctx.params; let Some(layer) = effectcraft_effects::crypto_layer_named(a, pr.s("layerName"), pr.e("layer") as usize) else { return Some(b) }; - let manifest = a.manifests.iter().find(|(l, _)| *l == layer).map(|(_, m)| m.as_slice()); + let manifest = a.manifest(&layer); let sel = effectcraft_effects::selection_hashes(pr.s("selection"), manifest); - // Per aux pixel: coverage-weighted ID colours (RGB) and the selection's coverage (A), on all - // cores with the rank planes resolved once. - // The ID colours are only read by the Colors display; Matte, Preview and Matte Only need the - // matte alone. + // The finished output, made on the CPU from the unscaled ID and coverage channels at source + // resolution and box-filtered below render scale 1 (#3334): the matte alone for Matte, + // Preview and Matte Only, the finished pixels for Colors. Kept per footage frame, layer, + // selection and output, so a frame shown again neither makes nor reads the ranks again. // `tests::fx_depth::cryptomatte_every_display_matches_the_cpu` guards this against the shader. - let what = effectcraft_effects::CryptoAux::for_display(pr.e("display"), pr.b("matteOnly")); - let img = effectcraft_effects::crypto_aux_image_with(a, &layer, &sel, what); - let tex = e.g.upload_image(&img)?; - let plane = lookup(e, &b, a, &tex, [0.5, 0.5], [0.0; 4]); + let output = CryptoOutput::for_display(pr.e("display"), pr.b("matteOnly")); + let finished = matte_cache::plane(a, &layer, &sel, output, b.scale); + let tex = upload_plane(e, &finished)?; + let plane = lookup(e, &b, finished.scale, &tex, [0.5, 0.5], [0.0; 4]); let mut p = op(7); p.u[0] = [7, pr.e("display"), pr.b("matteOnly") as u32, pr.b(effectcraft_effects::MATTE_ONLY_IN_ALPHA) as u32]; point(e, &p, b, &plane) } +/// Upload a finished Cryptomatte plane: the matte as one R32F channel (four bytes a pixel, not +/// the sixteen of a working image), the Colors display's pixels as RGBA. `None` when it does not +/// fit the device (the effect then runs on the CPU). +fn upload_plane(e: &Enc, p: &CryptoPlane) -> Option { + let g = e.g; + if !g.fits(p.width, p.height) { + return None; + } + let (format, bpp) = match p.output { + CryptoOutput::Matte => (wgpu::TextureFormat::R32Float, 4), + CryptoOutput::Colors => (wgpu::TextureFormat::Rgba32Float, 16), + }; + let n = (p.width as usize).checked_mul(p.height as usize)?.checked_mul(p.output.channels())?; + if p.data.len() != n { + return None; + } + let size = wgpu::Extent3d { width: p.width, height: p.height, depth_or_array_layers: 1 }; + let texture = g.device.create_texture(&wgpu::TextureDescriptor { + label: Some("Cryptomatte plane"), + size, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + g.queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + bytemuck::cast_slice(&p.data), + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(p.width.checked_mul(bpp)?), rows_per_image: Some(p.height) }, + size, + ); + #[cfg(test)] + PLANE_UPLOADS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((p.output, p.width, p.height, p.bytes())); + Some(GpuImage::new(texture, p.width, p.height)) +} + +/// The Cryptomatte planes uploaded so far (output, width, height, bytes; tests). +#[cfg(test)] +pub(crate) static PLANE_UPLOADS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + // ---------------------------------------------------------------- EXtractoR fn extractor(e: &mut Enc, ctx: &EffectCtx, b: GBuf, a: Option<&AuxChannels>) -> Option { @@ -303,7 +350,7 @@ fn extractor(e: &mut Enc, ctx: &EffectCtx, b: GBuf, a: Option<&AuxChannels>) -> let plane = match a { Some(a) if src_ch.iter().any(Option::is_some) => { let tex = aux_texture(e, a, [src_ch[0], src_ch[1], src_ch[2], src_ch[3]])?; - Some(lookup(e, &b, a, &tex, [0.5, 0.5], [0.0; 4])) + Some(lookup(e, &b, a.scale, &tex, [0.5, 0.5], [0.0; 4])) } _ => None, }; diff --git a/crates/gpu/src/fx_depth/matte_cache.rs b/crates/gpu/src/fx_depth/matte_cache.rs new file mode 100644 index 000000000..19b67d7d0 --- /dev/null +++ b/crates/gpu/src/fx_depth/matte_cache.rs @@ -0,0 +1,195 @@ +//! Finished Cryptomatte planes (#3334), kept so a frame shown again neither reads the rank +//! channels again nor makes the matte again: per footage frame (the decoded channels the plane +//! was made of), Cryptomatte layer, selection, output and render scale. +//! +//! The frame is named by its channels' identity: the footage source hands out the same +//! [`AuxChannels`] while it keeps that frame's channels, and new ones once the frame changes or +//! the file is forgotten (Reload Footage), so a stale plane can't be found. The cache holds them +//! only weakly (it never keeps decoded channels alive); a plane whose channels are gone is the +//! first to go. +//! +//! The planes are in the common memory budget ([`effectcraft_render::memory`]), each worth what +//! making it took, and bounded by themselves as well (a render without a budget keeps no more +//! than [`MAX_ENTRIES`] planes and [`MAX_BYTES`]). + +use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, Weak}; + +use effectcraft_effects::{CryptoOutput, CryptoPlane}; +use effectcraft_raster::AuxChannels; +use effectcraft_render::memory::{self, Accountant, Candidate, MemoryHolder}; + +/// At most this many planes… +const MAX_ENTRIES: usize = 32; +/// …and bytes, whatever the common budget. +const MAX_BYTES: usize = 512 << 20; + +#[derive(Clone, Debug, PartialEq)] +struct Key { + layer: String, + sel: Vec, + output: CryptoOutput, + /// The render scale the plane is box-filtered to (its bits), `None` at source resolution. + scale: Option, +} + +struct Entry { + /// The channels it was made of (held weakly: the allocation stays while this lives, so its + /// address names these channels alone). + aux: Weak, + key: Key, + plane: Arc, + /// Last use ([`memory::tick`]) and what making it took (µs). + used: u64, + cost_us: u64, +} + +impl Entry { + fn of(&self, a: &Arc) -> bool { + std::ptr::eq(self.aux.as_ptr(), Arc::as_ptr(a)) + } + fn gone(&self) -> bool { + self.aux.strong_count() == 0 + } +} + +struct Cache { + entries: Vec, + /// Planes made so far (tests). + made: u64, +} + +static CACHE: Mutex = Mutex::new(Cache { entries: Vec::new(), made: 0 }); + +fn lock() -> MutexGuard<'static, Cache> { + CACHE.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// In the common memory budget, registered once. +fn register() { + static HOLDER: OnceLock> = OnceLock::new(); + HOLDER.get_or_init(|| { + let h: Arc = Arc::new(Holder); + Accountant::global().register(&h); + h + }); +} + +/// Cryptomatte layer `layer`'s finished plane for selection `sel` (hashes) at `render_scale` +/// ([`effectcraft_effects::crypto_plane`]), kept or made now. +pub(crate) fn plane(a: &Arc, layer: &str, sel: &[u32], output: CryptoOutput, render_scale: f64) -> Arc { + plane_within(a, layer, sel, output, render_scale, MAX_BYTES, Accountant::global().budget()) +} + +/// [`plane`] with at most `max_bytes` kept, and the common `budget` (`usize::MAX`: none). +fn plane_within(a: &Arc, layer: &str, sel: &[u32], output: CryptoOutput, render_scale: f64, max_bytes: usize, budget: usize) -> Arc { + register(); + let key = Key { layer: layer.to_string(), sel: sel.to_vec(), output, scale: effectcraft_effects::crypto_box_scale(render_scale).map(f64::to_bits) }; + { + let mut c = lock(); + let now = memory::tick(); + if let Some(e) = c.entries.iter_mut().find(|e| e.of(a) && e.key == key) { + e.used = now; + return e.plane.clone(); + } + } + let started = web_time::Instant::now(); + let made = Arc::new(effectcraft_effects::crypto_plane(a, layer, sel, output, render_scale)); + let cost_us = u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX).max(1); + let bytes = made.bytes(); + { + let mut c = lock(); + c.made += 1; + // (planes of channels that are gone can't be asked for again; another thread may have + // made this one meanwhile) + c.entries.retain(|e| !e.gone() && !(e.of(a) && e.key == key)); + // A plane over MAX_BYTES on its own (a 16K Colors plane) is kept only where the common + // budget trims it: a render without a budget hands it out and keeps nothing. + if bytes > max_bytes && (budget == usize::MAX || bytes > budget) { + return made; + } + // Whether it can stay once every plane nobody holds is dropped: the planes renders hold + // stay whatever the limits, so with them it must fit the entry limit, and the byte limit + // unless it is over that on its own (kept for the common budget to trim, as above). + // Else it is handed out but not kept (and nothing is dropped for it), so the cache never + // stays over its limits once the renders let go. + let held: Vec = c.entries.iter().filter(|e| Arc::strong_count(&e.plane) > 1).map(|e| e.plane.bytes()).collect(); + let held_bytes = held.iter().fold(0usize, |t, b| t.saturating_add(*b)); + if held.len() >= MAX_ENTRIES || (bytes <= max_bytes && held_bytes.saturating_add(bytes) > max_bytes) { + return made; + } + c.entries.push(Entry { aux: Arc::downgrade(a), key, plane: made.clone(), used: memory::tick(), cost_us }); + loop { + let total: usize = c.entries.iter().map(|e| e.plane.bytes()).fold(0, usize::saturating_add); + if c.entries.len() <= 1 || (c.entries.len() <= MAX_ENTRIES && total <= max_bytes) { + break; + } + let Some(i) = oldest(&c) else { break }; + c.entries.swap_remove(i); + } + } + Accountant::global().note_growth(bytes); + made +} + +/// The entry to drop next, of those no render holds now (dropping one in use would free nothing +/// yet): one whose channels are gone, else the least recently used. +fn oldest(c: &Cache) -> Option { + let free = |e: &Entry| Arc::strong_count(&e.plane) == 1; + c.entries + .iter() + .position(|e| e.gone() && free(e)) + .or_else(|| c.entries.iter().enumerate().filter(|(_, e)| free(e)).min_by_key(|(_, e)| e.used).map(|(i, _)| i)) +} + +/// The planes in the common memory budget. +struct Holder; + +impl MemoryHolder for Holder { + fn name(&self) -> &'static str { + "Cryptomatte mattes" + } + fn bytes(&self) -> usize { + lock().entries.iter().map(|e| e.plane.bytes()).fold(0, usize::saturating_add) + } + fn oldest(&self) -> Option { + let c = lock(); + let e = c.entries.get(oldest(&c)?)?; + // (a plane of channels that are gone is worth nothing) + Some(if e.gone() { Candidate::new(0, e.plane.bytes(), 0) } else { Candidate::new(e.used, e.plane.bytes(), e.cost_us) }) + } + fn drop_oldest(&self) -> usize { + let mut c = lock(); + let Some(i) = oldest(&c) else { return 0 }; + c.entries.swap_remove(i).plane.bytes() + } +} + +/// [`plane_within`] (tests). +#[cfg(test)] +pub(crate) fn plane_held_to(a: &Arc, layer: &str, sel: &[u32], output: CryptoOutput, max_bytes: usize, budget: usize) -> Arc { + plane_within(a, layer, sel, output, 1.0, max_bytes, budget) +} + +/// Planes made so far (tests). +#[cfg(test)] +pub(crate) fn made() -> u64 { + lock().made +} + +/// Whether `p` is kept (tests). +#[cfg(test)] +pub(crate) fn keeps(p: &Arc) -> bool { + lock().entries.iter().any(|e| Arc::ptr_eq(&e.plane, p)) +} + +/// Planes kept now (tests). +#[cfg(test)] +pub(crate) fn kept() -> usize { + lock().entries.len() +} + +/// The planes in the common memory budget (tests). +#[cfg(test)] +pub(crate) fn holder() -> Arc { + Arc::new(Holder) +} diff --git a/crates/gpu/src/shaders/fx_depth.wgsl b/crates/gpu/src/shaders/fx_depth.wgsl index 68fc78f9f..6d892fe9b 100644 --- a/crates/gpu/src/shaders/fx_depth.wgsl +++ b/crates/gpu/src/shaders/fx_depth.wgsl @@ -198,15 +198,17 @@ fn fxd_point(@builtin(global_invocation_id) gid: vec3) { } } } - // Cryptomatte (aux = (ID colours, selection coverage)). u[0] = (op, display, matte only, - // matte only in alpha). Matte Only is the matte in RGB over alpha 1, or in every channel - // for projects saved before #3127 (`effectcraft_effects::matte_only_px`). + // Cryptomatte (aux = the finished plane, #3334: the selection's coverage in x; for the + // Colors display, its finished pixel). u[0] = (op, display, matte only, matte only in + // alpha). Matte Only is the matte in RGB over alpha 1, or in every channel for projects + // saved before #3127 (`effectcraft_effects::matte_only_px`). Outside the aux image the + // plane is 0: no matte, and Colors shows black over alpha 1. case 7u: { - let m = q.w; + let m = q.x; if (P.u[0].z != 0u) { o = select(vec4(m, m, m, 1.0), vec4(m), P.u[0].w != 0u); } else if (P.u[0].y == 0u) { - o = vec4(q.xyz * (1.0 - 0.5 * m) + 0.5 * m, 1.0); + o = vec4(q.xyz, 1.0); } else if (P.u[0].y == 1u) { o = px * m; } else { diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 563664ec8..9f6f85651 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -29,6 +29,7 @@ use crate::Gpu; mod adjust; mod adv3d; mod bench_share; +mod crypto_bench; mod deferred; mod deferred_jobs; mod footage_share; diff --git a/crates/gpu/src/tests/crypto_bench.rs b/crates/gpu/src/tests/crypto_bench.rs new file mode 100644 index 000000000..050c92f10 --- /dev/null +++ b/crates/gpu/src/tests/crypto_bench.rs @@ -0,0 +1,85 @@ +//! #3334: what Cryptomatte costs on the GPU at 1920 × 1080 with three ranks (six ID and coverage +//! planes), at full and half resolution: the first frame and the same frame again. Ignored; run +//! with `cargo test -p effectcraft-gpu --release crypto_bench -- --ignored --nocapture`. + +use std::sync::Arc; + +use effectcraft_effects::EffectEnv; +use effectcraft_keyframe::Value; +use effectcraft_raster::channels3d::{crypto_float, crypto_hash}; +use effectcraft_raster::{AuxChannels, Image}; + +use crate::tests::fx_depth::AuxHost; +use crate::tests::gpu; + +const NAMES: [&str; 6] = ["floor", "wall", "chair", "table", "lamp", "cup"]; + +/// 1920 × 1080, three ranks: diagonal bands of objects whose edges share pixels. +fn aux_1080p() -> AuxChannels { + let (w, h) = (1920usize, 1080usize); + let ids: Vec = NAMES.iter().map(|n| crypto_float(crypto_hash(n))).collect(); + let mut a = AuxChannels::new(w as u32, h as u32, 1.0); + let mut planes = vec![vec![0.0f32; w * h]; 6]; + for y in 0..h { + for x in 0..w { + let i = y * w + x; + let band = (x + y / 2) / 97; + let edge = (x + y / 2) % 97 < 3; + let c = if edge { 0.6 } else { 1.0 }; + planes[0][i] = ids[band % 6]; + planes[1][i] = c; + planes[2][i] = ids[(band + 1) % 6]; + planes[3][i] = 1.0 - c; + planes[4][i] = ids[(band + 2) % 6]; + planes[5][i] = 0.0; + } + } + let names = ["00.R", "00.G", "00.B", "00.A", "01.R", "01.G"]; + a.channels = names.iter().zip(planes).map(|(n, p)| (format!("CryptoObject{n}"), p)).collect(); + a.manifests = vec![("CryptoObject".into(), NAMES.iter().map(|n| (n.to_string(), crypto_hash(n))).collect())]; + a +} + +#[test] +#[ignore] +fn crypto_bench() { + let Some(g) = gpu() else { return }; + let host = AuxHost(Arc::new(aux_1080p())); + let spec = effectcraft_effects::find("ec.3d.cryptomatte").unwrap(); + let size = [1920.0, 1080.0]; + for (label, display, matte_only) in [("Matte", 1u32, false), ("Matte Only", 1, true), ("Colors", 0, false)] { + let mut params = + effectcraft_effects::Params { values: spec.params.iter().map(|ps| (ps.id.to_string(), effectcraft_effects::default_value(ps, size))).collect() }; + params.values.insert("selection".into(), Value::Str("chair, lamp".into())); + params.values.insert("display".into(), Value::Enum(display)); + params.values.insert("matteOnly".into(), Value::Bool(matte_only)); + for scale in [1.0, 0.5] { + let (w, h) = ((size[0] * scale) as u32, (size[1] * scale) as u32); + let buf = effectcraft_effects::Buf { img: Image::filled(w, h, [0.5, 0.4, 0.3, 1.0]), offset: [0.0; 2], scale }; + let ctx = || effectcraft_effects::EffectCtx { + params: ¶ms, + time: 0.0, + layer_size: size, + seed: 0, + adjustment: false, + env: EffectEnv { host: Some(&host), ..Default::default() }, + }; + // The effect alone on a buffer already on the GPU, until its result is done (a 1 × 1 + // readback waits for it): no upload of the layer, no readback of the frame. + let mut e = crate::context::Enc::new(&g.ctx); + let input = g.ctx.upload_image(&buf.img).unwrap(); + let mut run = || { + let t = std::time::Instant::now(); + let gbuf = crate::effects::GBuf { img: input.clone(), offset: buf.offset, scale }; + let out = crate::fx_depth::apply(&mut e, "ec.3d.cryptomatte", &ctx(), gbuf).expect("the GPU runs the effect"); + let one = e.crop(&out.img, 0, 0, 1, 1); + e.download(&one).expect("a readback"); + t.elapsed().as_secs_f64() * 1000.0 + }; + let first = run(); + let mut warm: Vec = (0..20).map(|_| run()).collect(); + warm.sort_by(f64::total_cmp); + eprintln!("crypto_bench {label} scale {scale}: first frame {first:.2} ms, same frame again {:.2} ms (median of 20)", warm[10]); + } + } +} diff --git a/crates/gpu/src/tests/fx_depth.rs b/crates/gpu/src/tests/fx_depth.rs index f60f31e3e..8dafa1bb8 100644 --- a/crates/gpu/src/tests/fx_depth.rs +++ b/crates/gpu/src/tests/fx_depth.rs @@ -259,7 +259,7 @@ fn ids_and_cryptomatte() { } /// The GPU skips the ID colours for displays that do not read them -/// ([`effectcraft_effects::CryptoAux::for_display`]): every display × Matte Only must still match +/// ([`effectcraft_effects::CryptoOutput::for_display`]): every display × Matte Only must still match /// the CPU effect, so a shader that starts reading RGB in another mode fails here. Matte Only is /// checked both ways: the matte in RGB over alpha 1 (#3127) and, for older projects, in alpha too. #[test] @@ -279,6 +279,189 @@ fn cryptomatte_every_display_matches_the_cpu() { } } +/// Cryptomatte alone on a `scale` buffer of the 70 × 44 layer over `host`, on the GPU and the +/// CPU: (GPU, CPU, the Cryptomatte planes the GPU uploaded, the uploads counted by the context). +fn crypto_direct(host: &AuxHost, vals: &[(&str, Value)], scale: f64) -> Option<(Image, Image, Vec<(effectcraft_effects::CryptoOutput, u32, u32, usize)>, u64)> { + let g = gpu()?; + let spec = effectcraft_effects::find("ec.3d.cryptomatte").unwrap(); + let size = [70.0, 44.0]; + let mut params = + effectcraft_effects::Params { values: spec.params.iter().map(|ps| (ps.id.to_string(), effectcraft_effects::default_value(ps, size))).collect() }; + for (k, v) in vals { + params.values.insert(k.to_string(), v.clone()); + } + let (w, h) = ((size[0] * scale) as u32, (size[1] * scale) as u32); + let buf = effectcraft_effects::Buf { img: pattern(5, w, h), offset: [0.0; 2], scale }; + let ctx = || effectcraft_effects::EffectCtx { + params: ¶ms, + time: 0.0, + layer_size: size, + seed: 0, + adjustment: false, + env: EffectEnv { host: Some(host), ..Default::default() }, + }; + let cpu = (spec.render)(&ctx(), buf.clone()); + let planes = || crate::fx_depth::PLANE_UPLOADS.lock().unwrap().len(); + let (before, uploads) = (planes(), g.ctx.transfer_stats().uploads); + let out = effectcraft_render::Accelerator::effects(g, &[effectcraft_render::FxStep { spec, ctx: ctx() }], &buf, None).expect("the GPU runs the effect"); + let uploads = g.ctx.transfer_stats().uploads - uploads; + let uploaded = crate::fx_depth::PLANE_UPLOADS.lock().unwrap()[before..].to_vec(); + Some((out.img, cpu.img, uploaded, uploads)) +} + +/// #3334: at full resolution the GPU's Cryptomatte is bit-identical to the CPU effect (whose +/// full-resolution path is unchanged) in the displays whose output is the plane or one product +/// with it (Matte Only, Colors, Matte); the Preview tint within rounding. It uploads one plane: +/// the matte as R32F at source resolution (the Colors display its RGBA pixels), and nothing +/// else of the channels (the context's own uploads are the layer's buffer alone). +#[test] +fn cryptomatte_full_resolution_uploads_only_the_matte_and_is_bit_identical() { + use effectcraft_effects::CryptoOutput; + let host = AuxHost(Arc::new(aux_scene(70, 44, 1.0))); + for (vals, output, exact) in [ + (vec![("matteOnly", on())], CryptoOutput::Matte, true), + (vec![("display", e(0))], CryptoOutput::Colors, true), + (vec![("display", e(1))], CryptoOutput::Matte, true), + (vec![("display", e(2))], CryptoOutput::Matte, false), + ] { + let mut vals = vals; + vals.push(("selection", Value::Str("beta, delta".into()))); + let Some((gpu_img, cpu_img, planes, uploads)) = crypto_direct(&host, &vals, 1.0) else { return }; + let bytes = 70 * 44 * output.channels() * 4; + assert_eq!(planes, [(output, 70, 44, bytes)], "{vals:?}: one plane, at source resolution"); + assert_eq!(uploads, 1, "{vals:?}: the layer's buffer, no channel"); + if exact { + for (i, (g, c)) in gpu_img.data.iter().zip(&cpu_img.data).enumerate() { + assert_eq!(g.map(f32::to_bits), c.map(f32::to_bits), "{vals:?}: pixel {i}"); + } + } else { + let d = diff(&cpu_img, &gpu_img, 1e-6); + assert_eq!(d.over, 0, "{vals:?}: max {}, worst {:?}", d.max, d.worst); + } + } +} + +/// #3334: at half resolution the GPU uploads the box-filtered matte (a quarter of the pixels, +/// four bytes each) and shows what the CPU effect shows. +#[test] +fn cryptomatte_half_resolution_uploads_the_filtered_matte() { + use effectcraft_effects::CryptoOutput; + let host = AuxHost(Arc::new(aux_scene(70, 44, 1.0))); + let vals = [("selection", Value::Str("beta, delta".into())), ("matteOnly", on())]; + let Some((gpu_img, cpu_img, planes, uploads)) = crypto_direct(&host, &vals, 0.5) else { return }; + assert_eq!(planes, [(CryptoOutput::Matte, 35, 22, 35 * 22 * 4)]); + assert_eq!(uploads, 1); + for (i, (g, c)) in gpu_img.data.iter().zip(&cpu_img.data).enumerate() { + assert_eq!(g.map(f32::to_bits), c.map(f32::to_bits), "pixel {i}"); + } + assert!(gpu_img.data.iter().any(|p| p[0] > 0.0 && p[0] < 1.0), "partial coverage where objects meet"); +} + +/// #3334: the finished planes are kept per footage frame (its channels), layer, selection, +/// output and render scale: the same frame again makes none; another selection, output or +/// scale makes its own. Once the frame's channels are gone, its planes are the first the memory +/// accountant drops, at no cost. +#[test] +fn cryptomatte_planes_are_kept_per_frame_and_selection() { + use crate::fx_depth::matte_cache; + use effectcraft_effects::CryptoOutput; + crate::tests::hold_gpu_lock(); + let a = Arc::new(aux_scene(70, 44, 1.0)); + let sel = vec![crypto_hash("beta")]; + let made = matte_cache::made(); + let one = matte_cache::plane(&a, "CryptoObject", &sel, CryptoOutput::Matte, 1.0); + assert_eq!(matte_cache::made(), made + 1); + let again = matte_cache::plane(&a, "CryptoObject", &sel, CryptoOutput::Matte, 1.0); + assert!(Arc::ptr_eq(&one, &again) && matte_cache::made() == made + 1, "kept"); + matte_cache::plane(&a, "CryptoObject", &[crypto_hash("gamma")], CryptoOutput::Matte, 1.0); + matte_cache::plane(&a, "CryptoObject", &sel, CryptoOutput::Colors, 1.0); + matte_cache::plane(&a, "CryptoObject", &sel, CryptoOutput::Matte, 0.5); + assert_eq!(matte_cache::made(), made + 4, "one per selection, output and scale"); + // Another frame (other channels, equal values) makes its own. + let other = Arc::new(aux_scene(70, 44, 1.0)); + matte_cache::plane(&other, "CryptoObject", &sel, CryptoOutput::Matte, 1.0); + assert_eq!(matte_cache::made(), made + 5); + // The frame's channels go: its planes are worth nothing. + drop(other); + let holder = matte_cache::holder(); + let next = holder.oldest().unwrap(); + assert_eq!(next.cost_us, 0, "{next:?}"); + let kept = matte_cache::kept(); + assert_eq!(holder.drop_oldest(), 70 * 44 * 4); + assert_eq!(matte_cache::kept(), kept - 1); + assert!(Arc::ptr_eq(&one, &matte_cache::plane(&a, "CryptoObject", &sel, CryptoOutput::Matte, 1.0)), "the live frame's plane stays"); +} + +/// #3301 review: a plane over the cache's own byte limit is not kept by a render without a +/// common budget (nothing would trim it); with a budget that holds it, it is kept and the budget +/// trims it. +#[test] +fn a_plane_over_the_byte_limit_is_kept_only_under_a_budget() { + use crate::fx_depth::matte_cache; + use effectcraft_effects::CryptoOutput; + crate::tests::hold_gpu_lock(); + let sel = vec![crypto_hash("beta")]; + let a = Arc::new(aux_scene(70, 44, 1.0)); + // (one Matte plane: 70 × 44 × 4 bytes, over a 100-byte limit) + let first = matte_cache::plane_held_to(&a, "CryptoObject", &sel, CryptoOutput::Matte, 100, usize::MAX); + let again = matte_cache::plane_held_to(&a, "CryptoObject", &sel, CryptoOutput::Matte, 100, usize::MAX); + assert!(!Arc::ptr_eq(&first, &again), "no budget: an oversized plane is not kept"); + let b = Arc::new(aux_scene(70, 44, 1.0)); + let first = matte_cache::plane_held_to(&b, "CryptoObject", &sel, CryptoOutput::Matte, 100, 1 << 30); + let again = matte_cache::plane_held_to(&b, "CryptoObject", &sel, CryptoOutput::Matte, 100, 1 << 30); + assert!(Arc::ptr_eq(&first, &again), "a budget that holds it: kept"); +} + +/// #3750 review: a plane a render still holds is not offered to the memory accountant, even +/// once its frame's channels are gone (dropping it would free nothing while the render holds it). +#[test] +fn a_held_plane_of_gone_channels_is_not_offered() { + use crate::fx_depth::matte_cache; + use effectcraft_effects::CryptoOutput; + crate::tests::hold_gpu_lock(); + let gone = Arc::new(aux_scene(70, 44, 1.0)); + let held = matte_cache::plane(&gone, "CryptoObject", &[crypto_hash("beta")], CryptoOutput::Matte, 1.0); + drop(gone); + let holder = matte_cache::holder(); + // (everything nobody holds goes; at most as many rounds as planes kept) + for _ in 0..=matte_cache::kept() { + if holder.drop_oldest() == 0 { + break; + } + } + assert!(matte_cache::keeps(&held), "the held plane was offered and dropped"); +} + +/// #3750 review: when renders hold every plane kept, a new plane is handed out but not kept, so +/// the cache never stays over its entry limit (32) once they let go. +#[test] +fn the_entry_limit_holds_while_renders_hold_every_plane() { + use crate::fx_depth::matte_cache; + use effectcraft_effects::CryptoOutput; + crate::tests::hold_gpu_lock(); + let a = Arc::new(aux_scene(70, 44, 1.0)); + let held: Vec<_> = (0..40u32).map(|i| matte_cache::plane_held_to(&a, "CryptoObject", &[i], CryptoOutput::Matte, usize::MAX, usize::MAX)).collect(); + assert!(matte_cache::kept() <= 32, "{} planes kept", matte_cache::kept()); + drop(held); +} + +/// #3750 review: a plane over the cache's byte limit kept under a common budget is kept also +/// while a render holds another plane (only the entry limit, or a plane within the byte limit +/// that can't fit beside the held ones, hands a new plane out without keeping it). +#[test] +fn an_oversized_plane_is_kept_beside_a_held_one_under_a_budget() { + use crate::fx_depth::matte_cache; + use effectcraft_effects::CryptoOutput; + crate::tests::hold_gpu_lock(); + let a = Arc::new(aux_scene(70, 44, 1.0)); + // (each Matte plane: 70 × 44 × 4 bytes, over a 100-byte limit; the budget holds them) + let neighbour = matte_cache::plane_held_to(&a, "CryptoObject", &[crypto_hash("beta")], CryptoOutput::Matte, 100, 1 << 30); + let first = matte_cache::plane_held_to(&a, "CryptoObject", &[crypto_hash("gamma")], CryptoOutput::Matte, 100, 1 << 30); + let again = matte_cache::plane_held_to(&a, "CryptoObject", &[crypto_hash("gamma")], CryptoOutput::Matte, 100, 1 << 30); + assert!(Arc::ptr_eq(&first, &again), "kept beside the held plane"); + drop(neighbour); +} + #[test] fn extractor() { case("ec.3d.extractor", &[("red", Value::Str("Z".into())), ("green", Value::Str("UV.U".into())), ("whitePoint", n(1000.0))]); diff --git a/crates/host/src/lib.rs b/crates/host/src/lib.rs index 7212fd730..3eb0d9ad2 100644 --- a/crates/host/src/lib.rs +++ b/crates/host/src/lib.rs @@ -69,6 +69,7 @@ impl Exporter for FileExporter { renderer: job.renderer, gpu_frames: job.gpu_frames, free_memory: Some(&free_memory), + cache_budget: job.cache_budget, }, nested_switches: job.nested_switches, }; @@ -113,9 +114,34 @@ pub fn session() -> Session { ..Default::default() }; effectcraft_script::install(&mut s); + // The caches' common budget from the start (#3298): the CLI and the MCP server never load + // the settings, and the caches have no limits of their own below it. Without a memory + // reading yet, the budget for unknown RAM ([`headless_session`] takes one). + s.apply_cache_budgets(); + // A session without a memory reading: a request for a file's planes over the fixed limit + // asks for it once (#3749). + effectcraft_engine::render::memory::set_decode_limit_source(Some(installed_memory_budget)); s } +/// [`session`] for a frontend without a window (the CLI, its MCP server, scripts and replays): +/// reads the system's memory once (#3941), so the caches share the budget of the installed RAM +/// as in the desktop app instead of the budget for unknown RAM. The desktop app reads it in the +/// background every few seconds instead (`Session::memory_tick`); this waits for the reading +/// (about a second on Windows). A session that can't read it keeps the budget for unknown RAM. +pub fn headless_session() -> Session { + let mut s = session(); + s.take_memory_reading(effectcraft_engine::sysinfo::memory()); + s +} + +/// The memory budget of the installed RAM with the default settings: what one file's decoded +/// planes may take when a request is over the fixed limit and the session read no memory. +fn installed_memory_budget() -> Option { + let memory = effectcraft_engine::sysinfo::memory()?; + Some(effectcraft_engine::prefs::Prefs::default().memory_budget(Some(memory), false).bytes) +} + /// External effect helpers run as child processes: native builds only. #[cfg(not(target_arch = "wasm32"))] fn helper_hooks() -> Option { diff --git a/crates/host/tests/it/cryptomatte_pick.rs b/crates/host/tests/it/cryptomatte_pick.rs index 57b6e624b..8a674a962 100644 --- a/crates/host/tests/it/cryptomatte_pick.rs +++ b/crates/host/tests/it/cryptomatte_pick.rs @@ -73,8 +73,10 @@ fn picking_on_a_cryptomatte_exr_edits_the_selection_and_the_matte() { let _ = std::fs::remove_dir_all(std::path::Path::new(&path).parent().unwrap()); } -/// At half resolution a preview pixel shows the aux texel at its centre (layer x 3 for preview -/// pixel 1): `scale` makes the pick read that one, so what is clicked is what lights up. +/// At half resolution the pick reads the aux texel at the preview pixel's centre (layer x 3 for +/// preview pixel 1): `scale` makes the pick read that one, so what is clicked lights up. The +/// preview pixel shows the matte box-filtered over the two layer pixels it covers (#3334): Left's +/// x 2 and Right's x 3, half lit. #[test] fn a_pick_at_preview_resolution_reads_the_pixel_the_preview_shows() { let (mut s, path) = footage("half", 3); @@ -83,7 +85,8 @@ fn a_pick_at_preview_resolution_reads_the_pixel_the_preview_shows() { assert_eq!(r["name"], RIGHT, "{r}"); let opts = effectcraft_engine::render::RenderOpts { scale: 0.5, ..Default::default() }; // Matte Only: the matte in RGB over alpha 1 (#3127). - assert_eq!(s.render(s.active_comp_id().unwrap(), Tick::ZERO, opts).get(1, 0), [1.0; 4]); + // (0.5 at 8 bpc) + assert_eq!(s.render(s.active_comp_id().unwrap(), Tick::ZERO, opts).get(1, 0), [128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]); // At full resolution the same point is Left's pixel. let r = s.execute_checked("effect.cryptomatteAt", json!({"effect": 1, "x": 2.5, "y": 1.5})).unwrap(); assert_eq!(r["name"], "Left"); diff --git a/crates/host/tests/it/exr_layers.rs b/crates/host/tests/it/exr_layers.rs index 39ea95e22..ebed80b35 100644 --- a/crates/host/tests/it/exr_layers.rs +++ b/crates/host/tests/it/exr_layers.rs @@ -39,8 +39,9 @@ fn extractor_shows_the_chosen_layer_and_channels_of_a_layered_exr() { assert_eq!(r["errors"], json!([]), "the file imports: {r}"); s.execute("comp.new", json!({"name": "EXR", "width": 8, "height": 4, "frameRate": 24, "duration": 1})).unwrap(); let layer = s.execute("layer.addItem", json!({"item": r["items"][0]})).unwrap()["layer"].clone(); - // The picture is the colour layer (diffuse: orange). - assert!(near(px(&s), [1.0, 0.735, 0.0]), "{:?}", px(&s)); + // No unnamed R, G, B: no main picture, black as in After Effects (the layers are reached by + // name, below). + assert!(near(px(&s), [0.0, 0.0, 0.0]), "{:?}", px(&s)); let ch = s.execute("layer.channels", json!({"layer": layer})).unwrap(); let names: Vec<&str> = ch["layers"].as_array().unwrap().iter().filter_map(|l| l["name"].as_str()).collect(); diff --git a/crates/host/tests/it/main.rs b/crates/host/tests/it/main.rs index ecc1abb0f..4f1b5bca5 100644 --- a/crates/host/tests/it/main.rs +++ b/crates/host/tests/it/main.rs @@ -7,6 +7,7 @@ mod exr_layers; mod footage_reload; mod gif_animates; mod library; +mod memory_budget; mod pick_whip; mod plugins; mod relink; diff --git a/crates/host/tests/it/memory_budget.rs b/crates/host/tests/it/memory_budget.rs new file mode 100644 index 000000000..153932137 --- /dev/null +++ b/crates/host/tests/it/memory_budget.rs @@ -0,0 +1,31 @@ +//! #3298: every host session (the desktop app, the CLI, the MCP server) starts with the caches' +//! common budget: the caches have no limits of their own below it, so an unset budget would let +//! them grow until memory runs out. +//! +//! #3941: a headless session (the CLI, its MCP server) reads the system's memory once, so its +//! caches share the budget of the installed RAM, as in the desktop app. + +use effectcraft_engine::render::memory::Accountant; + +/// One test: the headless session sets the common budget to the installed RAM's, which the +/// first check (the budget for unknown RAM) would see if both ran at once. +#[test] +fn a_host_session_bounds_the_caches() { + let s = effectcraft_host::session(); + let budget = Accountant::global().budget(); + assert!(budget < usize::MAX, "a finite budget"); + assert_eq!(budget, s.memory_budget().bytes); + assert!(s.layer_cache.budget() <= budget); + + // (a sandbox that can't read the system's memory keeps the budget for unknown RAM) + let Some(memory) = effectcraft_engine::sysinfo::memory() else { + eprintln!("the system's memory can't be read here: the headless reading is not checked"); + return; + }; + let headless = effectcraft_host::headless_session(); + let b = headless.memory_budget(); + assert_eq!(b.installed, Some(memory.total), "the budget of the installed RAM, not of unknown RAM"); + assert_eq!(b, effectcraft_engine::prefs::Prefs::default().memory_budget(Some(memory), b.reduced)); + assert_eq!(headless.layer_cache.budget(), b.bytes, "the caches follow it"); + assert_eq!(headless.export_cache_budget(), b.bytes, "exports and Render Queue runs follow it"); +} diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 7b4c3acc2..72fd5088e 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -33,6 +33,7 @@ craft-media = { workspace = true, features = ["mpegts"] } filmcraft-frame = { workspace = true } filmcraft-color = { workspace = true } filmcraft-time = { workspace = true } +half = { workspace = true } image = { workspace = true, features = ["gif", "webp", "tiff", "bmp", "exr", "tga", "hdr"] } rayon = { workspace = true } serde_json = { workspace = true } @@ -40,6 +41,7 @@ thiserror = { workspace = true } log = { workspace = true } [dev-dependencies] +# Writes the OpenEXR files of the tests (reading is craft-exr's). exr = { workspace = true } # Writes the animated GIFs of the tests. gif = { workspace = true } diff --git a/crates/media/src/exr_channels.rs b/crates/media/src/exr_channels.rs index 3463cf663..5ef1b5e8d 100644 --- a/crates/media/src/exr_channels.rs +++ b/crates/media/src/exr_channels.rs @@ -1,5 +1,5 @@ //! Auxiliary channels from multi-layer OpenEXR files (depth, object / material IDs, normals, -//! Cryptomatte, …) for the 3D Channel effects, read through the shared `craft-exr` decoder. +//! Cryptomatte, …) for the 3D Channel effects, read with `craft-exr`. //! //! Every channel of every layer becomes a plane named `layer.channel` (or just `channel` for //! the unnamed layer), placed in the display window (pixels outside a layer's data window are @@ -7,638 +7,171 @@ //! `cryptomatte//name` and `cryptomatte//manifest` header attributes (the published //! Cryptomatte metadata convention: the manifest is a JSON object of name → hex hash). //! -//! Decoded files are kept in a small cache ([`CACHE_BUDGET`]) that the picture of an EXR -//! footage item shares with EXtractoR / Cryptomatte once an effect has read its channels -//! (#474); a file is decoded once however many callers ask for it at the same time. +//! The files are indexed from their headers ([`crate::exr_index`]), read chunk by chunk +//! ([`crate::exr_read`]) and their planes kept in the plane store ([`crate::exr_planes`]), +//! which the picture of an EXR footage item shares with EXtractoR / Cryptomatte (#474, #3271). +//! This module holds the naming and picture rules they share, and whole-file reads of bytes. -use std::collections::HashMap; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex, OnceLock, PoisonError}; - -use effectcraft_raster::channels3d::{BACKGROUND_DEPTH, split_channel}; +use craft_exr::decode::PartInfo; use effectcraft_raster::{AuxChannels, Image}; -use effectcraft_render::reads::{ReadFile, ReadFiles}; +use effectcraft_render::reads::FileStamp; use crate::convert::{AlphaOp, float_to_image}; +use crate::exr_index::ExrIndex; +use crate::exr_read::{ReadRequest, read_planes}; /// The largest display window decoded (16384²; vector footage and Continuously Rasterize /// stop at the same size). -const MAX_DISPLAY_PIXELS: usize = 1 << 28; +pub(crate) const MAX_DISPLAY_PIXELS: usize = 1 << 28; // Channel naming and the Cryptomatte manifest are `craft-exr`'s. -use craft_exr::channels::{is_depth, part_channel_name as channel_name}; +pub(crate) use craft_exr::channels::{is_depth, part_channel_name as channel_name}; pub use craft_exr::cryptomatte::parse_manifest; +/// The part name channels are prefixed with (`None`: unnamed). +pub(crate) fn part_name(part: &PartInfo) -> Option { + part.name.clone().filter(|s| !s.is_empty()) +} + /// Why an OpenEXR file's pixels can't be decoded when its headers name a compression this build /// can't decompress (HTJ2K, OpenEXR 3.4's High-Throughput JPEG 2000): the decoders only said /// "no non-deep rgb channels" or showed a transparent frame (#482). `None` for other files. pub fn unsupported_compression(bytes: &[u8]) -> Option<&'static str> { - let mut limits = craft_exr::decode::Limits::default(); - limits.max_pixels = u64::MAX; - limits.max_bytes = u64::MAX; - craft_exr::decode::parts(bytes, &limits) - .ok()? - .iter() - .any(|part| matches!(part.compression.as_str(), "HTJ2K32" | "HTJ2K256")) - .then_some("OpenEXR HTJ2K compression isn't supported yet: re-save the file with ZIP, PIZ or DWAA compression") + let parts = craft_exr::decode::parts(bytes, &craft_exr::decode::Limits::none()).ok()?; + parts.iter().any(|p| p.compression.starts_with("HTJ2K")).then_some(crate::exr_index::HTJ2K) } -/// How the `image` crate's OpenEXR decoder would show a file: the first part with exact `R`, `G` -/// and `B` channels (alpha `A` when it has one, else opaque), placed in the display window with -/// 0 outside the data window. -#[derive(Clone, Copy, Debug, PartialEq)] -enum Rgb { - /// No part has R, G and B: the decoder refuses the file (a multi-layer file, shown with - /// [`layered_image`]'s rule). - None, - /// The channels (indices in [`AuxChannels::channels`]) hold exactly what it would show. - Planes([usize; 3], Option), - /// The planes can't stand in for it (a depth-named channel, whose plane is filled with the - /// background depth, or another display window): decode with the `image` crate. - Unsupported, +/// How many bytes of decoded planes the plane store keeps by itself until the caches' budget is +/// set (then it follows the footage frames' cap, see [`crate::exr_planes::set_budget`]: the whole +/// common budget on the desktop, #3298), like the frame cache's default +/// ([`crate::DEFAULT_BUDGET`]): two 2560×1440 files of 32 channels (470 MB each, as every plane +/// is f32). A soft bound: the newest file is kept whatever its size (so a frame's picture and its +/// effects share its decode), and files still in use are never dropped (planes an effect holds, +/// pictures waiting for their effects, decodes in progress), so memory can go above it while +/// they are. +pub const CACHE_BUDGET: usize = if cfg!(target_arch = "wasm32") { WEB_CACHE_CAP } else { crate::DEFAULT_BUDGET }; + +/// The most decoded planes the plane store keeps in the browser: the browser's largest footage +/// budget (Footage Frame Cache, frames and planes together, `WEB_MEDIA_CACHE` in the engine). +pub const WEB_CACHE_CAP: usize = 256 << 20; + +/// The index of an EXR file's bytes and the planes of `ids` (all when `None`). `None` when it is +/// not a readable EXR or the planes need too much memory. +fn read_bytes(bytes: &[u8], ids: Option>) -> Option<(ExrIndex, Vec, Vec>)> { + let mut src = std::io::Cursor::new(bytes); + let index = crate::exr_index::build(&mut src, FileStamp::Virtual).ok()?; + let ids = ids.unwrap_or_else(|| (0..index.channels.len()).collect()); + let (planes, _) = read_planes(&mut src, &index, &ReadRequest::full(ids.clone())); + Some((index, ids, planes.ok()?)) } -/// A decoded file: its channels and how its picture is made of them. -pub(crate) struct Decoded { - pub(crate) aux: Arc, - rgb: Rgb, -} - -impl Decoded { - /// Bytes held (the planes; names and manifests are small). - fn bytes(&self) -> usize { - self.aux.channels.iter().map(|(n, p)| n.len() + std::mem::size_of_val(p.as_slice())).sum() - } -} - -/// The most bytes of planes one decode allocates (every kept channel is a display-window plane -/// of f32, allocated before any pixels are read): a header can ask for far more than the file -/// holds. -#[cfg(target_pointer_width = "64")] -const MAX_DECODE_BYTES: usize = 8 << 30; -#[cfg(not(target_pointer_width = "64"))] -const MAX_DECODE_BYTES: usize = 512 << 20; - -/// Why a file's channels weren't decoded. -#[derive(Debug, PartialEq)] -enum Refused { - /// Not a readable OpenEXR file. - Unreadable, - /// Its kept channels need more memory than [`MAX_DECODE_BYTES`] (the reason, to show). - TooLarge(String), -} - -/// Bytes the selected channels occupy in each part's own display window. The channel cache -/// reserves this before decoding so concurrent imports cannot exceed its soft budget. -fn planes_bytes(infos: &[craft_exr::decode::PartInfo], keep: &dyn Fn(&str) -> bool) -> Option { - infos.first()?; - let total = infos.iter().try_fold(0u64, |total, part| { - let count = part.channels.iter().filter(|channel| keep(&channel_name(part.name.as_deref(), &channel.name))).count() as u64; - if count == 0 { - return Some(total); - } - let pixels = u64::from(part.display_window.width).checked_mul(u64::from(part.display_window.height))?; - total.checked_add(pixels.checked_mul(count)?.checked_mul(4)?) - })?; - usize::try_from(total).ok() -} - -/// Decode selected EXR channels through craft-exr, which places each selected block directly -/// into its bounded display-window plane. -fn decode(bytes: &[u8], keep: &dyn Fn(&str) -> bool) -> Result { - use craft_exr::decode::{self, Error as ExrError, Limits}; - - let mut limits = Limits::default(); - limits.max_pixels = MAX_DISPLAY_PIXELS as u64; - limits.max_bytes = MAX_DECODE_BYTES as u64; - // Header-only checks must not charge channels this caller does not decode. The shared display - // decoder independently checks the exact selected display planes before allocating them. It - // also bounds a selected part's data window across all of its channels (decoded blocks carry - // every channel before the unused ones are dropped), so a part whose full channel set exceeds - // `max_bytes` is refused even when the kept planes alone would fit. - let mut header_limits = limits; - header_limits.max_width = u32::MAX; - header_limits.max_height = u32::MAX; - header_limits.max_pixels = u64::MAX; - header_limits.max_bytes = u64::MAX; - let infos = decode::parts(bytes, &header_limits).map_err(|e| match e { - ExrError::LimitExceeded(message) => Refused::TooLarge(message), - _ => Refused::Unreadable, - })?; - let display = infos.first().ok_or(Refused::Unreadable)?.display_window; - let needed = planes_bytes(&infos, keep).filter(|bytes| *bytes > 0).ok_or(Refused::Unreadable)?; - if needed > MAX_DECODE_BYTES { - let gb = |b: u64| b as f64 / f64::from(1u32 << 30); - return Err(Refused::TooLarge(format!( - "its {}×{} OpenEXR channels need {:.1} GB of memory, more than the {:.1} GB one file may use", - display.width, - display.height, - gb(needed as u64), - gb(MAX_DECODE_BYTES as u64), - ))); - } - - let mut aux = AuxChannels::new(display.width, display.height, 1.0); - let mut crypto: HashMap, Option)> = HashMap::new(); - let mut rgb = Rgb::None; - for info in infos { - for (key, value) in &info.text_attributes { - let Some(rest) = key.strip_prefix("cryptomatte/") else { continue }; - let Some((id, field)) = rest.split_once('/') else { continue }; - let entry = crypto.entry(id.to_string()).or_default(); - match field { - "name" => entry.0 = Some(value.clone()), - "manifest" => entry.1 = Some(value.clone()), - _ => {} - } - } - let prefix = info.name.as_deref(); - let exact = info.display_window == display; - let rgb_indices = ["R", "G", "B"].map(|wanted| info.channels.iter().position(|channel| channel.name == wanted)); - let has_rgb = rgb_indices.iter().all(Option::is_some); - let alpha_index = info.channels.iter().position(|channel| channel.name == "A"); - // Metadata above still belongs to the file, but an ignored part must not allocate or - // impose its pixel/deep-data limits on the selected picture channels. - if !info.channels.iter().any(|channel| keep(&channel_name(prefix, &channel.name))) { - if rgb == Rgb::None && has_rgb { - rgb = Rgb::Unsupported; - } - continue; - } - let mut part = decode::decode_display_part( - bytes, - info.index, - keep, - &|name| { - if is_depth(name) { BACKGROUND_DEPTH } else { 0.0 } - }, - &limits, - ) - .map_err(|error| match error { - ExrError::LimitExceeded(message) => Refused::TooLarge(message), - _ => Refused::Unreadable, - })?; - if rgb == Rgb::None && has_rgb { - let base = aux.channels.len(); - let locate = |raw: usize| { - let name = channel_name(prefix, &info.channels.get(raw)?.name); - part.channels.iter().position(|channel| channel.name == name) - }; - rgb = match (rgb_indices[0].and_then(locate), rgb_indices[1].and_then(locate), rgb_indices[2].and_then(locate)) { - (Some(r), Some(g), Some(b)) if exact => { - let a = alpha_index.and_then(locate); - let depth = - [Some(r), Some(g), Some(b), a].into_iter().flatten().any(|i| part.channels.get(i).is_some_and(|channel| is_depth(&channel.name))); - if depth { Rgb::Unsupported } else { Rgb::Planes([base + r, base + g, base + b], a.map(|i| base + i)) } - } - _ => Rgb::Unsupported, - }; - } - aux.channels.extend(part.channels.drain(..).map(|channel| (channel.name, channel.samples))); - } - for (_, (name, manifest)) in crypto { - if let (Some(name), Some(manifest)) = (name, manifest) { - aux.manifests.push((name, parse_manifest(&manifest))); - } - } - aux.manifests.sort(); - Ok(Decoded { aux: Arc::new(aux), rgb }) +/// The channels `ids` of `index` with their `planes` (as [`read_bytes`] reads them). +fn aux_of(index: &ExrIndex, ids: &[usize], planes: Vec>) -> AuxChannels { + let (w, h) = index.size(); + let mut aux = AuxChannels::new(w as u32, h as u32, 1.0); + aux.channels = ids.iter().zip(planes).filter_map(|(id, p)| Some((index.channels.get(*id)?.name.clone(), p))).collect(); + aux.manifests = index.names.manifests.clone(); + aux.aliases = index.names.aliases.clone(); + aux } /// Read all channels of an EXR file's bytes. `None` when it is not a readable EXR. pub fn read_exr_channels(bytes: &[u8]) -> Option { - let aux = decode(bytes, &|_| true).ok()?.aux; - Some(Arc::try_unwrap(aux).unwrap_or_else(|a| (*a).clone())) + let (index, ids, planes) = read_bytes(bytes, None)?; + Some(aux_of(&index, &ids, planes)) } -/// Names of the beauty pass, most preferred first, matched against the last part of a layer's -/// name (Blender's `ViewLayer.Combined` is `Combined`): Blender's Combined pass and its -/// compositor's File Output default `Image`, the beauty / rgba / rgb / color of Nuke, Arnold and -/// V-Ray. -const BEAUTY: [&str; 7] = ["combined", "beauty", "image", "rgba", "rgb", "color", "colour"]; - -/// A data pass, never the picture: Cryptomatte (`CryptoMaterial00`), depth, mist, normals, -/// motion vectors, positions, UVs and object / material indices. -fn is_data_layer(layer: &str) -> bool { - let last = layer.rsplit('.').next().unwrap_or(layer).to_ascii_lowercase(); - last.starts_with("crypto") - || ["z", "uv", "id", "mist", "indexob", "indexma"].contains(&last.as_str()) - || ["depth", "normal", "vector", "position", "velocity", "motion", "objectid", "materialid"].iter().any(|k| last.contains(k)) -} - -/// The layer whose colour a multi-layer file shows (see [`layered_image`]). -fn picture_layer<'a>(aux: &AuxChannels, layers: &[&'a str]) -> Option<&'a str> { - // Colour layers: three different channels (not one channel, such as depth, shown in all). - let rgb: Vec<&str> = layers - .iter() - .copied() - .filter(|l| { - let [r, g, b, _] = aux.layer_rgba(l); - !r.is_empty() && !g.is_empty() && !b.is_empty() && r != g - }) - .collect(); - let last = |l: &str| l.rsplit('.').next().unwrap_or(l).to_ascii_lowercase(); - let pictures = || rgb.iter().filter(|l| !is_data_layer(l)); - // The unnamed layer (plain R, G, B), then the beauty pass by name. - rgb.iter() - .find(|l| l.is_empty()) - .or_else(|| BEAUTY.iter().find_map(|k| rgb.iter().find(|l| last(l) == *k))) - .or_else(|| pictures().find(|l| ["combined", "beauty"].iter().any(|k| last(l).contains(k)))) - .or_else(|| pictures().next()) - .or_else(|| layers.iter().find(|l| !is_data_layer(l))) - .or_else(|| rgb.first()) - .or_else(|| layers.first()) - .copied() -} - -/// The planes a multi-layer file's picture is made of (see [`layered_image`]): red, green, blue -/// (one channel thrice for grey) and alpha, by name. Only the names of `aux` are read. -fn picture_names(aux: &AuxChannels) -> Option<([String; 3], Option)> { - let layers = aux.layers(); - let colour = picture_layer(aux, &layers)?; - let names = aux.layer_rgba(colour); - // A layer without R, G and B channels shows its first channel as grey. - let first = aux.names().into_iter().find(|n| split_channel(n).0 == colour).unwrap_or_default(); - let pick = |k: usize| names.get(k).map(String::as_str).filter(|n| !n.is_empty()).unwrap_or(first).to_string(); - let a = names.get(3).filter(|n| !n.is_empty() && aux.get(n).is_some()).cloned(); - Some(([pick(0), pick(1), pick(2)], a)) -} - -/// The channels of the picture of a multi-layer file and nothing else (names first from the -/// headers, then only those channels decoded; in a multi-part file the other parts' pixels are -/// not even decompressed), with the names of its planes. -fn picture_only(bytes: &[u8]) -> Result<(Decoded, [String; 3], Option), Refused> { - let mut limits = craft_exr::decode::Limits::default(); - limits.max_width = u32::MAX; - limits.max_height = u32::MAX; - limits.max_pixels = u64::MAX; - limits.max_bytes = u64::MAX; - let meta = craft_exr::decode::parts(bytes, &limits).map_err(|_| Refused::Unreadable)?; - let mut names = AuxChannels::new(0, 0, 1.0); - for part in meta { - let prefix = part.name.as_deref(); - names.channels.extend(part.channels.iter().map(|ch| (channel_name(prefix, &ch.name), vec![]))); +/// The main picture of an OpenEXR file's bytes ([`crate::exr_index::MainPicture`]), linear, +/// straight RGB(A) as the file stores it (a `Y` picture as grey); a file without one (named +/// layers only, as Blender's `ViewLayer.Combined.R`) is black at its display window's size, as +/// After Effects shows it (its layers are reached by name, EXtractoR). Only the picture's +/// channels are decoded (in a multi-part file the other parts aren't read). `None` when it is +/// not a readable EXR. +pub fn picture_image(bytes: &[u8]) -> Option { + let mut src = std::io::Cursor::new(bytes); + let index = crate::exr_index::build(&mut src, FileStamp::Virtual).ok()?; + let (w, h) = index.size(); + let (w, h) = (u32::try_from(w).ok()?, u32::try_from(h).ok()?); + let n = (w as usize).checked_mul(h as usize)?; + // (the caller converts it to a float RGBA picture: a still's bound) + if n as u64 > crate::probe::MAX_STILL_PIXELS { + return None; } - let (rgb, a) = picture_names(&names).ok_or(Refused::Unreadable)?; - // Planes are looked up by name ignoring case, so every channel that could answer is kept. - let keep = |n: &str| rgb.iter().chain(&a).any(|k| k.eq_ignore_ascii_case(n)); - let decoded = decode(bytes, &keep)?; - Ok((decoded, rgb, a)) -} - -/// The picture of a multi-layer OpenEXR file without an unnamed RGB layer (Blender's -/// `ViewLayer.Combined.R`, the compositor's `Image.R`, Nuke's `beauty.R`, …), which the image -/// decoder rejects. After Effects shows a file's main RGBA channels and leaves the other layers -/// to EXtractoR; here that is the beauty pass by name (`BEAUTY`), else the first colour layer -/// that is not a data pass (never Cryptomatte, depth or normals, #412), else the first channel -/// as grey. Linear, straight RGBA as the file stores it. `None` when it is not a readable EXR. -pub fn layered_image(bytes: &[u8]) -> Option { - let (d, rgb, a) = picture_only(bytes).ok()?; - let aux = &d.aux; - let [r, g, b] = [aux.get(&rgb[0])?, aux.get(&rgb[1])?, aux.get(&rgb[2])?]; - let a = match &a { - Some(n) => Some(aux.get(n)?), + let Some(picture) = &index.picture else { + let len = n.checked_mul(3)?; + let mut data: Vec = Vec::new(); + data.try_reserve_exact(len).ok()?; + data.resize(len, 0.0); + return image::Rgb32FImage::from_raw(w, h, data).map(image::DynamicImage::ImageRgb32F); + }; + let ([r, g, b], a) = picture.rgba()?; + let ids = index.picture_ids(); + let (planes, _) = read_planes(&mut src, &index, &ReadRequest::full(ids.clone())); + let planes = planes.ok()?; + let plane = |id: usize| ids.iter().position(|i| *i == id).and_then(|at| planes.get(at)); + let (r, g, b) = (plane(r)?, plane(g)?, plane(b)?); + let a = match a { + Some(a) => Some(plane(a)?), None => None, }; - let n = (aux.width as usize).checked_mul(aux.height as usize)?; - let mut data = Vec::with_capacity(n.checked_mul(4)?); + let mut data = Vec::new(); + data.try_reserve_exact(n.checked_mul(if a.is_some() { 4 } else { 3 })?).ok()?; + // (0 outside the picture part's data window where its planes hold another fill) + let width = w as usize; + let shown = |i: usize| picture.inside.is_none_or(|[x0, y0, x1, y1]| (x0..x1).contains(&(i % width.max(1))) && (y0..y1).contains(&(i / width.max(1)))); for i in 0..n { - data.extend([r.get(i)?, g.get(i)?, b.get(i)?].map(|v| *v)); + let on = shown(i); + let pick = |v: &f32| if on { *v } else { 0.0 }; + data.extend([r.get(i)?, g.get(i)?, b.get(i)?].map(pick)); if let Some(a) = a { - data.push(*a.get(i)?); + data.push(pick(a.get(i)?)); } } match a { - Some(_) => image::Rgba32FImage::from_raw(aux.width, aux.height, data).map(image::DynamicImage::ImageRgba32F), - None => image::Rgb32FImage::from_raw(aux.width, aux.height, data).map(image::DynamicImage::ImageRgb32F), + Some(_) => image::Rgba32FImage::from_raw(w, h, data).map(image::DynamicImage::ImageRgba32F), + None => image::Rgb32FImage::from_raw(w, h, data).map(image::DynamicImage::ImageRgb32F), } } +/// The size and alpha of an OpenEXR file's main picture ([`picture_image`]) from its headers +/// alone (import; a file without one is its display window, opaque). `None` when it is not a +/// readable EXR. +pub(crate) fn picture_size(bytes: &[u8]) -> Option<(u32, u32, bool)> { + let mut src = std::io::Cursor::new(bytes); + let index = crate::exr_index::build(&mut src, FileStamp::Virtual).ok()?; + let (w, h) = index.size(); + Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?, index.picture.as_ref().is_some_and(|p| p.has_alpha()))) +} + +/// The black picture of a file without a main picture, `w` × `h`, opaque (no alpha channel). +pub(crate) fn black_picture(w: u32, h: u32, op: AlphaOp) -> Image { + float_to_image(w, h, op, |_| [0.0, 0.0, 0.0, 1.0]) +} + /// The picture made of planes `rgb` and `a` (opaque without one) of `aux`, as /// [`crate::convert::dynamic_to_image`] makes it of the same values. `None` when a plane is /// missing or short. -fn planes_picture(aux: &AuxChannels, rgb: [&[f32]; 3], a: Option<&[f32]>, op: AlphaOp) -> Option { - let n = (aux.width as usize).checked_mul(aux.height as usize)?; +pub(crate) fn planes_picture(aux: &AuxChannels, rgb: [&[f32]; 3], a: Option<&[f32]>, inside: Option<[usize; 4]>, op: AlphaOp) -> Option { + let w = aux.width as usize; + let n = w.checked_mul(aux.height as usize)?; if rgb.iter().chain(&a).any(|p| p.len() < n) { return None; } let [r, g, b] = rgb; - let at = |p: &[f32], i: usize| p.get(i).copied().unwrap_or(0.0); + // (0 outside `inside`, the picture part's data window, where the planes hold another fill) + let shown = |i: usize| inside.is_none_or(|[x0, y0, x1, y1]| (x0..x1).contains(&(i % w.max(1))) && (y0..y1).contains(&(i / w.max(1)))); + let at = |p: &[f32], i: usize| if shown(i) { p.get(i).copied().unwrap_or(0.0) } else { 0.0 }; Some(float_to_image(aux.width, aux.height, op, |i| [at(r, i), at(g, i), at(b, i), a.map_or(1.0, |a| at(a, i))])) } -/// The picture of a decoded file by [`layered_image`]'s rule. -fn layered_picture_of(aux: &AuxChannels, op: AlphaOp) -> Option { - let (rgb, a) = picture_names(aux)?; - let a = match &a { - Some(n) => Some(aux.get(n)?), - None => None, - }; - planes_picture(aux, [aux.get(&rgb[0])?, aux.get(&rgb[1])?, aux.get(&rgb[2])?], a, op) -} - -/// The picture of the multi-layer EXR at `path` ([`layered_image`]'s rule) as an [`Image`]: -/// from the channel cache when `shared` (an effect reads the footage's channels, so they are -/// decoded anyway), else of the picture's channels alone (also when the cache has no channels -/// for the file: a read that failed, or a broken part the picture doesn't use). `Err(Some(why))` -/// when the file is too large to decode, `Err(None)` when it isn't a readable multi-layer EXR. -pub(crate) fn layered_picture(path: &str, bytes: Arc<[u8]>, file: &ReadFile, op: AlphaOp, shared: bool) -> Result> { - if shared && let Some(d) = cache().get(path, Use::Picture, || read_as(file, bytes.clone())) { - return layered_picture_of(&d.aux, op).ok_or(None); - } - let (d, rgb, a) = picture_only(&bytes).map_err(|r| match r { - Refused::TooLarge(why) => Some(why), - Refused::Unreadable => None, - })?; - let aux = &d.aux; - let plane = |n: &str| aux.get(n).ok_or(None); - let a = match &a { - Some(n) => Some(plane(n)?), - None => None, - }; - planes_picture(aux, [plane(&rgb[0])?, plane(&rgb[1])?, plane(&rgb[2])?], a, op).ok_or(None) -} - -/// The picture of the EXR at `path` from the channel cache (#474: EXtractoR / Cryptomatte read -/// this footage's channels, so the picture shares their decode): what the `image` crate's -/// decoder shows for a file it reads, [`layered_image`]'s rule for one it refuses. `None` when -/// the planes can't stand in for the `image` crate's picture (decode with it), or the file is -/// not a readable EXR. -pub(crate) fn cached_picture(path: &str, bytes: Arc<[u8]>, file: &ReadFile, op: AlphaOp) -> Option { - let d = cache().get(path, Use::Picture, || read_as(file, bytes))?; - let aux = &d.aux; - match d.rgb { - Rgb::None => layered_picture_of(aux, op), - Rgb::Planes([r, g, b], a) => { - let plane = |i: usize| aux.channels.get(i).map(|(_, p)| p.as_slice()); - let a = match a { - Some(a) => Some(plane(a)?), - None => None, - }; - planes_picture(aux, [plane(r)?, plane(g)?, plane(b)?], a, op) - } - Rgb::Unsupported => None, - } -} - -/// How many bytes of decoded channels the cache keeps, like the frame cache's default -/// ([`crate::DEFAULT_BUDGET`]): two 2560×1440 files of 32 channels (470 MB each, as every plane -/// is f32). A soft bound: the newest file is kept whatever its size (so a frame's picture and its -/// effects share its decode), and files still in use are never dropped (planes an effect holds, -/// [`HELD_FILES`] pictures waiting for their effects, decodes in progress), so memory can go -/// above it while they are. (Measured on such a sequence decoded one frame at a time: 1 GiB held -/// peak memory about 1 GB lower than 2 GiB, at the same speed.) -#[cfg(not(target_arch = "wasm32"))] -pub const CACHE_BUDGET: usize = 1 << 30; -#[cfg(target_arch = "wasm32")] -pub const CACHE_BUDGET: usize = 512 << 20; - -/// At most this many files are cached (unreadable ones hold no bytes). -const CACHE_FILES: usize = 64; - -/// At most this many files whose picture was made of their planes are kept for their effects -/// (the renderer asks for a frame's picture, then its channels): about as many frames as are -/// rendered at once. The oldest stops being kept when another comes. -const HELD_FILES: usize = 4; - -/// A file's decode: done once, by the first caller; the others wait for it. With the files read -/// for it (see [`crate::reads`]), noted again on every hit. -type Slot = Arc>, ReadFiles)>>; - -/// Bytes the caller already read from `file`, given to the cache as read from it (so the entry -/// keeps the file's identity). -fn read_as(file: &ReadFile, bytes: Arc<[u8]>) -> Option> { - crate::reads::note(file.clone()); - Some(bytes) -} - -struct Entry { - path: String, - slot: Slot, - /// Bytes of the finished decode, or the planes it will allocate while it decodes. - bytes: usize, - /// When it was last asked for or finished decoding (a counter). - used: u64, -} - -impl Entry { - /// Dropping it would free nothing or lose a decode in progress: an effect (or a picture - /// waiting for its effects) still holds its planes, someone is using the slot, or it is decoding. - fn in_use(&self) -> bool { - // `get_or_init` hands an active caller a borrow of the OnceLock value before that caller - // can clone the decoded Arc. Keep the entry while any caller still holds this slot, or a - // concurrent account/eviction can remove it in that gap and make the next request decode - // the same file again. - if Arc::strong_count(&self.slot) > 1 { - return true; - } - match self.slot.get() { - None => true, - Some((None, _)) => false, - Some((Some(d), _)) => Arc::strong_count(d) > 1 || Arc::strong_count(&d.aux) > 1, - } - } -} - -struct State { - entries: Vec, - clock: u64, - /// Files whose picture was made of their planes and whose channels haven't been asked for - /// since, oldest first (at most [`HELD_FILES`]). - held: std::collections::VecDeque<(String, Arc)>, -} - -/// Who asks for a file's channels. -#[derive(Clone, Copy, PartialEq)] -pub(crate) enum Use { - /// The picture of a footage item whose effects read its channels next: kept for them. - Picture, - /// The channels themselves (EXtractoR, Cryptomatte, the 3D Channel effects). - Channels, -} - -/// Decoded EXR files by path, bounded by bytes, least recently used out first. -pub(crate) struct ChannelCache { - state: Mutex, - budget: usize, - /// Files decoded (for tests). - decodes: AtomicU64, -} - -/// Removes a decode's entry if the decode panics, so the file doesn't stay "decoding" (never -/// dropped, its estimated bytes counted) until someone asks for it again. -struct Abandon<'a> { - cache: &'a ChannelCache, - slot: &'a Slot, -} - -impl Drop for Abandon<'_> { - fn drop(&mut self) { - if std::thread::panicking() { - self.cache.lock().entries.retain(|e| !Arc::ptr_eq(&e.slot, self.slot)); - } - } -} - -impl ChannelCache { - pub(crate) const fn new(budget: usize) -> Self { - Self { state: Mutex::new(State { entries: Vec::new(), clock: 0, held: std::collections::VecDeque::new() }), budget, decodes: AtomicU64::new(0) } - } - - fn lock(&self) -> std::sync::MutexGuard<'_, State> { - self.state.lock().unwrap_or_else(PoisonError::into_inner) - } - - /// Set the bytes of the entry of `slot` (if it's still cached), mark it used now and drop - /// least recently used files until the rest fit the budget. - fn account(&self, slot: &Slot, bytes: usize) { - let mut state = self.lock(); - state.clock += 1; - let clock = state.clock; - // (gone when the file was forgotten meanwhile) Used as of now: a file asked for before - // another but decoded after it is not the older one. - if let Some(e) = state.entries.iter_mut().find(|e| Arc::ptr_eq(&e.slot, slot)) { - e.bytes = bytes; - e.used = clock; - } - Self::evict(&mut state.entries, self.budget, slot); - } - - /// The decoded file at `path`, read with `read` by the first caller; callers asking for the - /// same file meanwhile wait for that decode instead of decoding it again. - pub(crate) fn get(&self, path: &str, by: Use, read: impl FnOnce() -> Option>) -> Option> { - let slot = { - let mut state = self.lock(); - state.clock += 1; - let clock = state.clock; - match state.entries.iter_mut().find(|e| e.path == path) { - Some(e) => { - e.used = clock; - e.slot.clone() - } - None => { - let slot = Slot::default(); - state.entries.push(Entry { path: path.to_string(), slot: slot.clone(), bytes: 0, used: clock }); - slot - } - } - }; - let mut decoded_here = false; - // Waiting here can block a rayon worker (which `Inner::frame_at` avoids for frames): that - // is safe because the decode never waits on rayon's global pool (the exr crate - // decompresses on a pool of its own and this thread only receives the blocks), so the - // decoding thread can't be waiting for this one. - let (v, files) = slot.get_or_init(|| { - decoded_here = true; - self.decodes.fetch_add(1, Ordering::Relaxed); - #[cfg(test)] - count_decode(true); - let _abandon = Abandon { cache: self, slot: &slot }; - let (bytes, files) = crate::reads::captured(read); - (bytes.and_then(|bytes| self.decode_file(path, &slot, &bytes)), files) - }); - // The file(s) the decode was made of, read now or for an earlier caller. - crate::reads::note_all(files); - let v = v.clone(); - if decoded_here { - self.account(&slot, v.as_ref().map_or(0, |d| d.bytes())); - } - let mut state = self.lock(); - match (by, &v) { - (Use::Picture, Some(d)) => { - if !state.held.iter().any(|(p, _)| p == path) { - state.held.push_back((path.to_string(), d.clone())); - if state.held.len() > HELD_FILES { - state.held.pop_front(); - } - } - } - (Use::Channels, _) => state.held.retain(|(p, _)| p != path), - (Use::Picture, None) => {} - } - drop(state); - v - } - - /// Decode the file at `path` whose bytes are `bytes` for `slot` (see [`ChannelCache::get`]). - fn decode_file(&self, path: &str, slot: &Slot, bytes: &[u8]) -> Option> { - // The planes it will allocate count against the budget while it decodes. - let mut limits = craft_exr::decode::Limits::default(); - limits.max_width = u32::MAX; - limits.max_height = u32::MAX; - limits.max_pixels = u64::MAX; - limits.max_bytes = u64::MAX; - if let Ok(infos) = craft_exr::decode::parts(bytes, &limits) - && let Some(need) = planes_bytes(&infos, &|_| true) - { - self.account(slot, need.min(MAX_DECODE_BYTES)); - } - match decode(bytes, &|_| true) { - Ok(d) => Some(Arc::new(d)), - Err(Refused::TooLarge(why)) => { - log::warn!("media: {path}: {why}"); - None - } - Err(Refused::Unreadable) => None, - } - } - - /// Drop least recently used files not in use until the rest fit the budget, keeping `newest`. - fn evict(entries: &mut Vec, budget: usize, newest: &Slot) { - while entries.iter().map(|e| e.bytes).sum::() > budget || entries.len() > CACHE_FILES { - let oldest = entries.iter().enumerate().filter(|(_, e)| !Arc::ptr_eq(&e.slot, newest) && !e.in_use()).min_by_key(|(_, e)| e.used).map(|(i, _)| i); - let Some(i) = oldest else { break }; - entries.remove(i); - } - } - - pub(crate) fn forget(&self, path: &str) { - let mut state = self.lock(); - state.entries.retain(|e| e.path != path); - state.held.retain(|(p, _)| p != path); - } - - #[cfg(test)] - fn decodes(&self) -> u64 { - self.decodes.load(Ordering::Relaxed) - } - - #[cfg(test)] - fn cached(&self) -> Vec { - self.lock().entries.iter().map(|e| e.path.clone()).collect() - } -} - -fn cache() -> &'static ChannelCache { - static CACHE: ChannelCache = ChannelCache::new(CACHE_BUDGET); - &CACHE -} - -/// Drop the cached channels of `path` (the file changed on disk). -pub(crate) fn forget(path: &str) { - cache().forget(path); -} - -/// Stop keeping the decodes of the last pictures for their effects ([`HELD_FILES`]): which -/// footage effects read changed, so they may wait for effects that are gone. Their entries stay -/// cached as any other, least recently used out first. -pub(crate) fn release_held() { - cache().lock().held.clear(); -} - -/// Read (and cache, see [`CACHE_BUDGET`]) the channels of the EXR at `path` via `read`. -pub(crate) fn cached(path: &str, read: impl FnOnce() -> Option>) -> Option> { - cache().get(path, Use::Channels, read).map(|d| d.aux.clone()) -} - #[cfg(test)] thread_local! { /// Decodes of a still's pixels on this thread ([`count_decode`]): the `image` crate's, then - /// the channel cache's. + /// the plane store's. static DECODES: std::cell::Cell<[u64; 2]> = const { std::cell::Cell::new([0; 2]) }; } -/// Count a decode of a file's pixels on this thread (tests): by the channel cache (`channels`) +/// Count a decode of a file's pixels on this thread (tests): by the plane store (`channels`) /// or by the `image` crate. #[cfg(test)] pub(crate) fn count_decode(channels: bool) { @@ -650,15 +183,37 @@ pub(crate) fn count_decode(channels: bool) { } /// The decodes [`count_decode`] counted on this thread since the last call: by the `image` crate -/// and by the channel cache. +/// and by the plane store. #[cfg(test)] pub(crate) fn take_decodes() -> [u64; 2] { DECODES.with(|d| d.replace([0; 2])) } +/// Run `f` and return the decodes [`count_decode`] counted on this thread meanwhile, leaving +/// this thread's count as it was (a decode thread may run another request's decode inside +/// this one's). +#[cfg(test)] +pub(crate) fn counting(f: impl FnOnce() -> R) -> (R, [u64; 2]) { + let before = DECODES.with(std::cell::Cell::get); + let r = f(); + let after = DECODES.with(|d| d.replace(before)); + (r, [after[0].saturating_sub(before[0]), after[1].saturating_sub(before[1])]) +} + +/// Count `n` decodes ([`counting`]) on this thread: made for it on another. +#[cfg(test)] +pub(crate) fn add_decodes(n: [u64; 2]) { + DECODES.with(|d| { + let c = d.get(); + d.set([c[0] + n[0], c[1] + n[1]]); + }); +} + #[cfg(test)] mod tests { use super::*; + use effectcraft_raster::channels3d::BACKGROUND_DEPTH; + use std::sync::Arc; /// An EXR file of `layers` (with their display window `display`). fn file(layers: Vec>>, display: exr::prelude::IntegerBounds) -> Vec { @@ -669,14 +224,6 @@ mod tests { bytes.into_inner() } - /// A single-part file of float channels named `names`, `w`×`h`, every sample `v`. - fn flat(names: &[&str], (w, h): (usize, usize), v: f32) -> Vec { - use exr::prelude::*; - let list: Vec> = names.iter().map(|n| AnyChannel::new(*n, FlatSamples::F32(vec![v; w * h]))).collect(); - let layer = Layer::new((w, h), LayerAttributes::default(), Encoding::FAST_LOSSLESS, AnyChannels::sort(list.into())); - file(vec![layer], IntegerBounds::from_dimensions((w, h))) - } - #[test] fn reads_layered_channels_and_cryptomatte_metadata() { use exr::prelude::*; @@ -744,349 +291,38 @@ mod tests { assert_eq!(read_exr_channels(&away).unwrap().get("G").unwrap(), [0.0; 6]); } - /// #474: concurrent requests for a file that isn't cached decode it once; the others wait - /// for that decode and share its planes. - #[test] - fn concurrent_requests_decode_a_file_once() { - let bytes: Arc<[u8]> = flat(&["R", "G", "B", "Z"], (64, 64), 0.5).into(); - let cache = ChannelCache::new(CACHE_BUDGET); - let reads = AtomicU64::new(0); - let barrier = std::sync::Barrier::new(8); - let got: Vec> = std::thread::scope(|s| { - let jobs: Vec<_> = (0..8) - .map(|_| { - s.spawn(|| { - barrier.wait(); - cache - .get("/474-concurrent.exr", Use::Channels, || { - reads.fetch_add(1, Ordering::Relaxed); - // Long enough for the others to arrive while this one decodes. - std::thread::sleep(std::time::Duration::from_millis(50)); - Some(bytes.clone()) - }) - .unwrap() - }) - }) - .collect(); - jobs.into_iter().map(|j| j.join().unwrap()).collect() - }); - assert_eq!(cache.decodes(), 1, "one decode"); - assert_eq!(reads.load(Ordering::Relaxed), 1, "the file is read once"); - assert!(got.iter().all(|d| Arc::ptr_eq(d, &got[0])), "every caller has the same planes"); - assert_eq!(got[0].aux.get("Z").and_then(|z| z.first()).copied(), Some(0.5)); - } - - /// #474: the cache is bounded by the bytes of its planes, least recently used out first; the - /// newest file stays even when it alone is over the budget, and unreadable files are cached - /// (as such) without counting bytes. - #[test] - fn cache_evicts_least_recently_used_by_bytes() { - // 4 float planes of 32×32: 16 KiB of samples (plus a few bytes of names) per file. - let bytes: Arc<[u8]> = flat(&["R", "G", "B", "A"], (32, 32), 0.25).into(); - let one = 4 * 32 * 32 * 4 + 4; - let cache = ChannelCache::new(2 * one); - let get = |p: &str| cache.get(p, Use::Channels, || Some(bytes.clone())).unwrap(); - assert_eq!(get("/a.exr").bytes(), one); - get("/b.exr"); - get("/a.exr"); // a is now more recent than b - get("/c.exr"); - assert_eq!(cache.cached(), ["/a.exr", "/c.exr"], "b was least recently used"); - assert_eq!(cache.decodes(), 3); - get("/a.exr"); - assert_eq!(cache.decodes(), 3, "a hit"); - // A file over the budget on its own is still kept while it is the newest. - let small = ChannelCache::new(one / 2); - assert!(small.get("/big.exr", Use::Channels, || Some(bytes.clone())).is_some()); - assert_eq!(small.cached(), ["/big.exr"]); - small.get("/big2.exr", Use::Channels, || Some(bytes.clone())); - assert_eq!(small.cached(), ["/big2.exr"]); - // An unreadable file is remembered (not read again) without bytes, and forgotten on request. - assert!(cache.get("/broken.exr", Use::Channels, || Some(Arc::from(&b"not an exr"[..]))).is_none()); - assert!(cache.get("/broken.exr", Use::Channels, || panic!("not read again")).is_none()); - cache.forget("/broken.exr"); - assert!(!cache.cached().contains(&"/broken.exr".to_string())); - // At most CACHE_FILES files, however small. - for i in 0..CACHE_FILES + 10 { - cache.get(&format!("/none{i}.exr"), Use::Channels, || None); - } - assert!(cache.cached().len() <= CACHE_FILES); - } - - /// #474: a file counts as used when its decode finishes: one asked for first but decoded - /// after another is the newer of the two, so concurrent frames don't evict each other's - /// files before their effects read them. - #[test] - fn a_file_is_used_as_of_its_decode() { - let bytes: Arc<[u8]> = flat(&["R", "G", "B", "A"], (32, 32), 0.25).into(); - let one = 4 * 32 * 32 * 4 + 4; - let cache = ChannelCache::new(2 * one); - cache.get("/first.exr", Use::Channels, || { - // Another frame's file is asked for and decoded while this one decodes. - cache.get("/second.exr", Use::Channels, || Some(bytes.clone())); - Some(bytes.clone()) - }); - cache.get("/third.exr", Use::Channels, || Some(bytes.clone())); - assert_eq!(cache.cached(), ["/first.exr", "/third.exr"], "the file decoded first went first"); - } - - /// #474: frames rendered at once (each asks for its picture, then its effects for the - /// channels while other frames decode) decode each file once, though the budget holds only - /// one: a picture's file is kept for its effects, and files in use are never dropped. - #[test] - fn concurrent_frames_decode_each_file_once() { - let bytes: Arc<[u8]> = flat(&["R", "G", "B", "Z"], (64, 64), 0.5).into(); - let cache = ChannelCache::new(4 * 64 * 64 * 4 + 4); - let (next, reads, frames) = (std::sync::atomic::AtomicUsize::new(0), AtomicU64::new(0), 24); - let read = || { - reads.fetch_add(1, Ordering::Relaxed); - Some(bytes.clone()) - }; - std::thread::scope(|s| { - for _ in 0..4 { - s.spawn(|| { - loop { - let i = next.fetch_add(1, Ordering::Relaxed); - if i >= frames { - break; - } - let path = format!("/474-frames/{i:04}.exr"); - drop(cache.get(&path, Use::Picture, read).unwrap()); - std::thread::sleep(std::time::Duration::from_millis(3)); - let aux = cache.get(&path, Use::Channels, read).unwrap(); - std::thread::sleep(std::time::Duration::from_millis(2)); - assert_eq!(aux.aux.get("Z").and_then(|z| z.first()).copied(), Some(0.5)); - } - }); - } - }); - assert_eq!(cache.decodes(), frames as u64, "one decode per frame"); - assert_eq!(reads.load(Ordering::Relaxed), frames as u64); - } - - #[test] - fn cache_does_not_evict_a_slot_while_a_caller_is_using_it() { - let bytes: Arc<[u8]> = flat(&["R", "G", "B", "A"], (32, 32), 0.25).into(); - let one = 4 * 32 * 32 * 4 + 4; - let cache = ChannelCache::new(one); - drop(cache.get("/active.exr", Use::Channels, || Some(bytes.clone()))); - let active_slot = cache.lock().entries.iter().find(|entry| entry.path == "/active.exr").unwrap().slot.clone(); - drop(cache.get("/next.exr", Use::Channels, || Some(bytes.clone()))); - assert!(cache.cached().contains(&"/active.exr".to_string()), "an active caller pins the slot"); - - drop(active_slot); - drop(cache.get("/newest.exr", Use::Channels, || Some(bytes.clone()))); - assert!(!cache.cached().contains(&"/active.exr".to_string()), "an idle slot is eligible for eviction"); - } - - /// #474: a decode that panics doesn't leave its file "decoding" in the cache (never dropped, - /// its planes counted): the entry goes, and the next request decodes the file. - #[test] - fn a_decode_that_panics_is_not_left_in_the_cache() { - let bytes: Arc<[u8]> = flat(&["R"], (8, 8), 1.0).into(); - let cache = ChannelCache::new(CACHE_BUDGET); - let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| cache.get("/474-panics.exr", Use::Channels, || panic!("the read failed")))); - assert!(r.is_err()); - assert!(cache.cached().is_empty()); - assert!(cache.get("/474-panics.exr", Use::Channels, || Some(bytes.clone())).is_some()); - assert_eq!(cache.cached(), ["/474-panics.exr"]); - } - - /// #474: the picture of a multi-layer file whose effects read its channels comes from the - /// cache, and from the picture's own channels when the cache has none for the file (a read - /// that failed, or a broken part the picture doesn't use). - #[test] - fn a_shared_picture_without_cached_channels_is_still_decoded() { - use effectcraft_project::Footage; - use effectcraft_render::FloatCurve; - let bytes: Arc<[u8]> = flat(&["Image.R", "Image.G", "Image.B", "depth.Z"], (4, 2), 0.5).into(); - let path = "/474-shared-fallback.exr"; - assert!(cache().get(path, Use::Channels, || None).is_none(), "a read that failed"); - let op = AlphaOp::of(&Footage::default(), FloatCurve::Linear); - let img = layered_picture(path, bytes, &ReadFile::new(path, effectcraft_render::reads::FileStamp::Virtual), op, true).unwrap(); - assert_eq!(img.get(1, 1), [0.5, 0.5, 0.5, 1.0]); - } - /// #474: a header asking for more plane memory than one decode may allocate (16384² display /// window, 40 channels: 43 GB) is refused with a reason before anything is allocated. #[test] fn a_header_asking_for_too_much_memory_is_refused() { use exr::prelude::*; + // (another test raises the process-wide decode limit far above the request: not now) + let _only = crate::exr_read::LIMIT_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let list: Vec> = (0..40).map(|i| AnyChannel::new(format!("pass{i:02}.Y").as_str(), FlatSamples::F32(vec![0.5]))).collect(); let layer = Layer::new((1, 1), LayerAttributes::default(), Encoding::FAST_LOSSLESS, AnyChannels::sort(list.into())); let bytes = file(vec![layer], IntegerBounds::new((0, 0), (16384, 16384))); - match decode(&bytes, &|_| true) { - Err(Refused::TooLarge(why)) => assert!(why.contains("16384×16384") && why.contains("GB"), "{why}"), - Err(Refused::Unreadable) => panic!("readable"), + let mut src = std::io::Cursor::new(bytes.as_slice()); + let index = crate::exr_index::build(&mut src, FileStamp::Virtual).unwrap(); + // (the fixed limit, whatever the process-wide one) + let all = ReadRequest { max_bytes: crate::exr_read::MAX_DECODE_BYTES, ..ReadRequest::full((0..index.channels.len()).collect()) }; + match read_planes(&mut src, &index, &all).0 { + Err(crate::exr_read::ReadError::TooLarge(why)) => assert!(why.contains("16384×16384") && why.contains("GB"), "{why}"), + Err(e) => panic!("readable: {e:?}"), Ok(_) => panic!("refused"), } assert!(read_exr_channels(&bytes).is_none()); - assert!(cached("/474-too-large.exr", || Some(bytes.as_slice().into())).is_none()); - } - - /// #474: a file forgotten (changed on disk) while it decodes isn't cached under its path when - /// that decode finishes. - #[test] - fn a_file_forgotten_while_it_decodes_is_not_cached() { - let bytes: Arc<[u8]> = flat(&["R"], (8, 8), 1.0).into(); - let cache = ChannelCache::new(CACHE_BUDGET); - let d = cache.get("/changed.exr", Use::Channels, || { - cache.forget("/changed.exr"); - Some(bytes.clone()) - }); - assert!(d.is_some()); - assert!(cache.cached().is_empty()); - } - - /// #295: a multi-layer EXR whose colour is only in named layers (`diffuse.R`, as Blender and - /// Nuke write them) failed to import ("does not contain non-deep rgb channels"); it now - /// shows its colour layer and keeps every channel for EXtractoR. - /// #474: once an effect has read a footage item's channels, the picture of each later frame - /// shares one decode with them: the frame's decode is cached and the channels come from it - /// without reading the file again. - #[test] - fn picture_and_aux_channels_share_one_decode() { - use exr::prelude::*; - let (w, h) = (2usize, 2usize); - let frame = |v: f32| -> Arc<[u8]> { - let ch = |n: &str, v: f32| AnyChannel::new(n, FlatSamples::F32(vec![v; w * h])); - let channels = AnyChannels::sort(vec![ch("Image.R", 0.5), ch("Image.G", 0.5), ch("Image.B", 0.5), ch("GlossDir.R", v)].into()); - let image = Image::from_layer(Layer::new((w, h), LayerAttributes::default(), Encoding::FAST_LOSSLESS, channels)); - let mut bytes = std::io::Cursor::new(Vec::new()); - image.write().to_buffered(&mut bytes).unwrap(); - bytes.into_inner().into() - }; - let paths = ["/474-shared-decode_0001.exr", "/474-shared-decode_0002.exr"]; let pool = crate::MediaPool::new(); - pool.add_bytes(paths[0], frame(0.25)); - pool.add_bytes(paths[1], frame(0.75)); - let mut f = crate::probe_bytes(paths[0], frame(0.25)).unwrap(); - f.kind = effectcraft_project::FootageKind::Sequence; - f.sequence = paths.iter().map(|p| p.to_string()).collect(); - let t1 = f.frame_rate.tick_of(1); - use effectcraft_render::FootageSource; - // The first frame: the picture, then an effect reads the channels. - pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap(); - let aux = pool.aux(effectcraft_project::ItemId(1), &f, effectcraft_time::Tick::ZERO).unwrap(); - assert_eq!(aux.get("GlossDir.R").and_then(|p| p.first()).copied(), Some(0.25)); - // The next frame's picture decodes the file into the cache, so its channels are not read. - let px = pool.frame_at(&f, t1).unwrap().get(0, 0); - let aux = cached(paths[1], || panic!("the frame's decode is reused, the file is not read again")).unwrap(); - assert_eq!(aux.get("GlossDir.R").and_then(|p| p.first()).copied(), Some(0.75)); - assert_eq!(px, pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap().get(0, 0), "the same picture"); - } - - /// An EXR file with an unnamed RGB layer and a named `GlossDir.R` of `v` (2×2). - fn rgb_and_gloss(v: f32) -> Arc<[u8]> { - flat(&["R", "G", "B", "GlossDir.R"], (2, 2), v).into() - } - - /// #474: footage the project says effects read the channels of - /// ([`FootageSource::set_aux_footage`]) costs one decode from its first frame on: a single - /// still with EXtractoR decodes once. Without it the first frame decodes twice (the picture, - /// then the channels once `aux()` asks). - #[test] - fn given_aux_footage_decodes_once_from_the_first_frame() { - use effectcraft_render::FootageSource; - let (given, learned) = ("/474-given-still.exr", "/474-learned-still.exr"); - let pool = crate::MediaPool::new(); - let mut f = std::collections::HashMap::new(); - for p in [given, learned] { - pool.add_bytes(p, rgb_and_gloss(0.25)); - f.insert(p, crate::probe_bytes(p, rgb_and_gloss(0.25)).unwrap()); - } - pool.set_aux_footage(&[given.to_string()]); - take_decodes(); - let t = effectcraft_time::Tick::ZERO; - pool.frame_at(&f[given], t).unwrap(); - let aux = pool.aux(effectcraft_project::ItemId(1), &f[given], t).unwrap(); - assert_eq!(aux.get("GlossDir.R").and_then(|p| p.first()).copied(), Some(0.25)); - assert_eq!(take_decodes(), [0, 1], "the picture and the channels share one decode"); - // Learned only at the first `aux()`: the picture was decoded on its own before. - pool.frame_at(&f[learned], t).unwrap(); - pool.aux(effectcraft_project::ItemId(2), &f[learned], t).unwrap(); - assert_eq!(take_decodes(), [1, 1]); - } - - /// #474: once the project no longer names footage (its effect removed), later frames decode - /// only their picture again; what `aux()` learned is dropped with each new set too. - #[test] - fn a_new_aux_footage_set_returns_to_picture_only() { - use effectcraft_render::FootageSource; - let paths: Vec = (1..=4).map(|i| format!("/474-unset_{i:04}.exr")).collect(); - let pool = crate::MediaPool::new(); - for p in &paths { - pool.add_bytes(p, rgb_and_gloss(0.5)); - } - let mut f = crate::probe_bytes(&paths[0], rgb_and_gloss(0.5)).unwrap(); - f.kind = effectcraft_project::FootageKind::Sequence; - f.sequence = paths.clone(); - let at = |i: i64| f.frame_rate.tick_of(i); - // (counted on this thread, so other tests sharing the channel cache don't change them) - let frame = |i: i64| { - take_decodes(); - pool.frame_at(&f, at(i)).unwrap(); - take_decodes() + pool.add_bytes("/474-too-large.exr", bytes.as_slice().into()); + let f = effectcraft_project::Footage { + path: "/474-too-large.exr".into(), + kind: effectcraft_project::FootageKind::Still, + has_video: true, + width: 16384, + height: 16384, + ..Default::default() }; - pool.set_aux_footage(std::slice::from_ref(&f.path)); - assert_eq!(frame(0), [0, 1], "given: the picture comes from the channel decode"); - pool.set_aux_footage(&[]); - assert!(!cache().lock().held.iter().any(|(p, _)| *p == paths[0]), "no longer kept once no effect reads it"); - assert_eq!(frame(1), [1, 0], "no longer given: the picture alone"); - // Learned by `aux()`, then a new set without it: picture only again. - pool.aux(effectcraft_project::ItemId(1), &f, at(1)).unwrap(); - assert_eq!(frame(2), [0, 1], "learned"); - pool.set_aux_footage(&[]); - assert_eq!(frame(3), [1, 0], "a new set drops what was learned"); - } - - /// #474: the picture made of the cached planes of a file with exact R, G, B channels is the - /// `image` crate's, bit for bit (first such part, alpha or opaque, data window placed with 0 - /// around it), in every alpha interpretation and float curve. - #[test] - fn picture_from_planes_is_the_image_crates() { - use effectcraft_project::{AlphaMode, Footage}; - use effectcraft_render::FloatCurve; - use exr::prelude::*; - let half = |n: &str, v: f32, len: usize| AnyChannel::new(n, FlatSamples::F16((0..len).map(|i| f16::from_f32(v + i as f32 * 0.37 - 1.0)).collect())); - let float = |n: &str, v: f32, len: usize| AnyChannel::new(n, FlatSamples::F32((0..len).map(|i| ((i * 7) % 11) as f32 * v).collect())); - let part = |name: Option<&str>, pos: (i32, i32), size: (usize, usize), list: Vec>| { - let mut attrs = name.map_or_else(LayerAttributes::default, LayerAttributes::named); - attrs.layer_position = Vec2(pos.0, pos.1); - Layer::new(size, attrs, Encoding::SMALL_LOSSLESS, AnyChannels::sort(list.into())) - }; - let display = IntegerBounds::new((1, -1), (5, 4)); - let n = 20; - let files = [ - file( - vec![part(None, (1, -1), (5, 4), vec![half("R", 0.1, n), half("G", 0.2, n), half("B", 0.3, n), float("A", 0.1, n), float("Z", 2.0, n)])], - display, - ), - file(vec![part(None, (0, 0), (3, 2), vec![float("R", 0.4, 6), float("G", 0.5, 6), float("B", 0.6, 6), half("Image.R", 0.1, 6)])], display), - file( - vec![ - part(Some("diffuse"), (1, -1), (5, 4), vec![half("R", 0.1, n), half("G", 0.2, n), half("B", 0.3, n)]), - part(Some("beauty"), (2, 0), (2, 2), vec![half("R", 0.4, 4), half("G", 0.5, 4), half("B", 0.6, 4), half("A", 0.5, 4)]), - ], - display, - ), - ]; - let bits = |i: &effectcraft_raster::Image| i.data.iter().flat_map(|p| p.map(f32::to_bits)).collect::>(); - for (k, bytes) in files.iter().enumerate() { - let path = format!("/474-planes-{k}.exr"); - let d = cache().get(&path, Use::Channels, || Some(bytes.as_slice().into())).unwrap(); - assert!(matches!(d.rgb, Rgb::Planes(..)), "file {k}: {:?}", d.rgb); - let img = crate::probe::load_oriented(bytes, Some(image::ImageFormat::OpenExr)).unwrap(); - for alpha in [AlphaMode::Straight, AlphaMode::Premultiplied, AlphaMode::Ignore] { - for curve in [FloatCurve::Srgb, FloatCurve::Linear, FloatCurve::Gamma24] { - let op = AlphaOp::of(&Footage { alpha, premul_color: [0.2, 0.4, 0.6], ..Default::default() }, curve); - let want = crate::convert::dynamic_to_image(&img, op); - let got = cached_picture(&path, bytes.as_slice().into(), &ReadFile::new(path.as_str(), effectcraft_render::reads::FileStamp::Virtual), op) - .unwrap(); - assert_eq!((got.width, got.height), (want.width, want.height)); - assert_eq!(bits(&got), bits(&want), "file {k} {alpha:?} {curve:?}"); - } - } - } + use effectcraft_render::FootageSource; + assert!(pool.aux(effectcraft_project::ItemId(1), &f, effectcraft_time::Tick::ZERO).is_none()); } /// #2141: one pixel of data in a 60000² display window is refused, not allocated per channel. @@ -1101,8 +337,11 @@ mod tests { assert!(read_exr_channels(&bytes.into_inner()).is_none()); } + /// A file of named layers only (Blender's single-part multilayer) imports at its display + /// window's size and shows black, opaque, as After Effects does; its layers stay readable by + /// effects (EXtractoR, Cryptomatte) and nothing is an error. #[test] - fn layered_exr_without_an_unnamed_rgb_layer_imports() { + fn layered_exr_without_an_unnamed_rgb_layer_imports_black() { use exr::prelude::*; let (w, h) = (4usize, 2usize); let ch = |n: &str, v: f32| AnyChannel::new(n, FlatSamples::F32(vec![v; w * h])); @@ -1115,8 +354,13 @@ mod tests { assert_eq!((f.width, f.height, f.alpha), (4, 2, effectcraft_project::AlphaMode::Ignore)); let pool = crate::MediaPool::new(); pool.add_bytes("/layers.exr", b.clone()); - let px = pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap().get(1, 1); - assert!((px[0] - 1.0).abs() < 1e-4 && px[1] > 0.3 && px[1] < 0.6 && px[2] < 1e-4 && px[3] == 1.0, "diffuse, sRGB-encoded: {px:?}"); + let img = pool.frame_at(&f, effectcraft_time::Tick::ZERO).unwrap(); + assert_eq!((img.width, img.height), (4, 2)); + assert_eq!(img.get(1, 1), [0.0, 0.0, 0.0, 1.0], "black, opaque"); + use effectcraft_render::FootageSource; + let effects = pool.aux(effectcraft_project::ItemId(1), &f, effectcraft_time::Tick::ZERO).expect("the layers, for effects"); + assert_eq!(effects.get("diffuse.R").unwrap(), [1.0; 8].as_slice()); + assert_eq!(effects.get("depth.Z").unwrap(), [7.0; 8].as_slice()); let aux = read_exr_channels(&b).unwrap(); assert_eq!(aux.layers(), ["depth", "diffuse"]); assert_eq!(aux.layer_rgba("diffuse"), ["diffuse.R", "diffuse.G", "diffuse.B", ""].map(String::from)); @@ -1153,70 +397,7 @@ mod tests { assert!(aux.get("ViewLayer.Combined.R").is_some()); } - #[test] - fn multipart_fallback_filters_channels_and_reserves_display_planes() { - use exr::prelude::*; - let part = |name: &str, pos: (i32, i32), size: (usize, usize), channels: Vec>| { - let attrs = LayerAttributes { layer_name: Some(Text::from(name)), layer_position: Vec2(pos.0, pos.1), ..Default::default() }; - Layer::new(size, attrs, Encoding::FAST_LOSSLESS, AnyChannels::sort(channels.into())) - }; - let (w, h) = (2usize, 1usize); - let bytes = file( - vec![ - part("Depth", (0, 0), (1, 1), vec![AnyChannel::new("Z", FlatSamples::F32(vec![7.0]))]), - part( - "Beauty", - (1, 1), - (w, h), - vec![ - AnyChannel::new("R", FlatSamples::F32(vec![0.1; w * h])), - AnyChannel::new("G", FlatSamples::F32(vec![0.2; w * h])), - AnyChannel::new("B", FlatSamples::F32(vec![0.3; w * h])), - ], - ), - ], - IntegerBounds::from_dimensions((3, 2)), - ); - let mut limits = craft_exr::decode::Limits::default(); - limits.max_width = u32::MAX; - limits.max_height = u32::MAX; - limits.max_pixels = u64::MAX; - limits.max_bytes = u64::MAX; - let parts = craft_exr::decode::parts(&bytes, &limits).unwrap(); - assert_eq!(planes_bytes(&parts, &|name| name == "Beauty.R"), Some(3 * 2 * 4)); - assert_eq!(planes_bytes(&parts, &|_| false), Some(0)); - - // Different display windows must not reserve every part at the first part's size. - let mut varied = parts.clone(); - varied[0].display_window.width = 1; - varied[0].display_window.height = 1; - varied[1].display_window.width = 10; - varied[1].display_window.height = 20; - assert_eq!(planes_bytes(&varied, &|_| true), Some(4 + 10 * 20 * 3 * 4)); - assert_eq!(planes_bytes(&varied, &|name| name == "Beauty.R"), Some(10 * 20 * 4)); - varied[1].display_window.width = u32::MAX; - varied[1].display_window.height = u32::MAX; - assert_eq!(planes_bytes(&varied, &|_| true), None); - assert_eq!(planes_bytes(&varied, &|name| name == "Depth.Z"), Some(4)); - - // Skipping the RGB part preserves the first-RGB fallback state and depth samples. - let depth = decode(&bytes, &|name| name == "Depth.Z").unwrap(); - assert_eq!(depth.rgb, Rgb::Unsupported); - assert_eq!(depth.aux.channels.len(), 1); - assert_eq!(depth.aux.get("Depth.Z").unwrap()[0], 7.0); - - let selected = decode(&bytes, &|name| name == "Beauty.R").unwrap(); - assert_eq!(selected.aux.channels.iter().map(|(name, _)| name.as_str()).collect::>(), ["Beauty.R"]); - assert_eq!(selected.aux.get("Beauty.R").unwrap(), [0.0, 0.0, 0.0, 0.0, 0.1, 0.1]); - - // The old app decoder selected the named beauty part when the first part was depth-only, - // and placed its data into the shared display window; retain that layered-picture result. - let image = layered_image(&bytes).unwrap().to_rgba32f(); - assert_eq!(image.get_pixel(1, 1).0, [0.1, 0.2, 0.3, 1.0]); - assert_eq!(image.get_pixel(0, 0).0, [0.0, 0.0, 0.0, 1.0]); - } - - /// Straight RGBA of [`layered_image`] at pixel 0 for a file of single-value channels. + /// Straight RGBA of [`picture_image`] at pixel 0 for a file of single-value channels. fn picture>(channels: &[(S, f32)]) -> Vec { use exr::prelude::*; let (w, h) = (2usize, 2usize); @@ -1224,15 +405,17 @@ mod tests { let image = Image::from_layer(Layer::new((w, h), LayerAttributes::default(), Encoding::FAST_LOSSLESS, AnyChannels::sort(list.into()))); let mut bytes = std::io::Cursor::new(Vec::new()); image.write().to_buffered(&mut bytes).unwrap(); - let img = layered_image(bytes.get_ref()).unwrap().to_rgba32f(); + let img = picture_image(bytes.get_ref()).unwrap().to_rgba32f(); + assert_eq!(img.dimensions(), (2, 2), "the display window's size"); img.get_pixel(0, 0).0.to_vec() } - /// #412: a Blender compositor File Output (multilayer) names its beauty pass `Image`, and its - /// Cryptomatte layers (lowercase `r, g, b, a`) sort first. The picture was CryptoMaterial00; - /// it is the Image layer, and data passes are never the picture. + /// The main picture is After Effects': the unprefixed `R`, `G`, `B` (`A`), else `Y` (`A`) as + /// grey. A file of named layers only (Blender's multilayer `ViewLayer.Combined.R`, a + /// compositor's `Image.R`, Cryptomatte, depth) has none and shows black, opaque (#412 chose a + /// beauty pass by name before; its layers are reached by name, EXtractoR). #[test] - fn layered_exr_shows_the_beauty_pass_not_cryptomatte() { + fn the_picture_is_the_unprefixed_channels_else_black() { let mut blender = vec![]; for layer in ["CryptoMaterial00", "CryptoMaterial01", "CryptoMaterial02"] { blender.extend(["r", "g", "b", "a"].map(|c| (format!("{layer}.{c}"), 0.9))); @@ -1241,8 +424,8 @@ mod tests { blender.extend(["R", "G", "B", "A"].map(|c| (format!("{layer}.{c}"), v))); } blender.push(("Mist.Z".into(), 0.7)); - assert_eq!(picture(&blender), [0.5; 4], "the Image layer"); - // Blender's render-layer names and Nuke's beauty. + let black = [0.0, 0.0, 0.0, 1.0]; + assert_eq!(picture(&blender), black, "named layers only: no Image or beauty pass by name"); assert_eq!( picture(&[ ("ViewLayer.CryptoObject00.r", 0.9), @@ -1252,12 +435,15 @@ mod tests { ("ViewLayer.Combined.G", 0.2), ("ViewLayer.Combined.B", 0.2) ]), - [0.2, 0.2, 0.2, 1.0] + black, + "Blender's Combined pass" ); - // No beauty name: the first colour layer that isn't a data pass. - let no_beauty: Vec<(String, f32)> = blender.iter().filter(|(n, _)| !n.starts_with("Image")).cloned().collect(); - assert_eq!(picture(&no_beauty), [0.3; 4], "GlossCol, not Cryptomatte"); - // Only data and a grey pass: the grey pass, not depth. - assert_eq!(picture(&[("Depth.Z", 9.0), ("AO.Y", 0.25)]), [0.25, 0.25, 0.25, 1.0]); + assert_eq!(picture(&[("Depth.Z", 9.0), ("AO.Y", 0.25)]), black, "a layer's Y is not the picture"); + // Unprefixed channels are, whatever the named layers beside them. + assert_eq!(picture(&[("R", 0.1), ("G", 0.2), ("B", 0.3), ("Image.R", 0.9)]), [0.1, 0.2, 0.3, 1.0]); + assert_eq!(picture(&[("R", 0.1), ("G", 0.2), ("B", 0.3), ("A", 0.5)]), [0.1, 0.2, 0.3, 0.5]); + // Luminance: grey, with its alpha. + assert_eq!(picture(&[("Y", 0.25)]), [0.25, 0.25, 0.25, 1.0]); + assert_eq!(picture(&[("A", 0.5), ("Y", 0.25), ("diffuse.R", 0.9)]), [0.25, 0.25, 0.25, 0.5]); } } diff --git a/crates/media/src/exr_index.rs b/crates/media/src/exr_index.rs new file mode 100644 index 000000000..425077c0a --- /dev/null +++ b/crates/media/src/exr_index.rs @@ -0,0 +1,373 @@ +//! [`ExrIndex`]: what an OpenEXR file holds, read from its headers and offset tables only +//! (#3271): the parts, every channel by its plane name, the Cryptomatte manifests and the +//! channels its picture is made of. +//! +//! The headers and offset tables are read and checked by `craft-exr` +//! ([`craft_exr::seek::Index`]), which also knows where each chunk lies; this index adds the +//! app's view of the file: the plane names and aliases, the manifests, the picture's channels and +//! the file's identity. An index is a few kilobytes and is kept per file ([`get`]): the channel +//! popups, `layer.channels`, the Cryptomatte layer lists, import and the planning of a read use +//! it and never decode pixels. The reader ([`crate::exr_read`]) fetches the chunks it lists. +//! +//! Everything is validated before anything is sized by it: the display window +//! ([`crate::exr_channels::MAX_DISPLAY_PIXELS`]), the data windows (four times that), the chunk +//! count (eight bytes of offset table each, so never more than the file can hold), and every +//! offset (inside the chunk area; a chunk with a bad offset is never read). Every block is held +//! to what its chunk's bytes can decompress to ([`limits`]) when the file is indexed and before +//! it is handed to another decoder ([`safe_to_decode`]); each read checks it again. + +use std::collections::{HashMap, VecDeque}; +use std::io::SeekFrom; +use std::sync::{Arc, Mutex, PoisonError}; + +use craft_exr::channels::ColorLayout; +use craft_exr::decode::{Limits, PartInfo, Window}; +use craft_exr::seek; +use effectcraft_raster::AuxChannels; +use effectcraft_raster::channels3d::BACKGROUND_DEPTH; +use effectcraft_render::reads::FileStamp; + +use crate::exr_channels::{MAX_DISPLAY_PIXELS, channel_name, is_depth, parse_manifest, part_name}; +use crate::exr_read::{ExrSource, Opened, ReadSeek}; + +/// One channel of the file, in file order (parts in order, each part's channels as its header +/// lists them): the order of [`AuxChannels::channels`] when every channel is read. +#[derive(Clone, Debug)] +pub(crate) struct IndexChannel { + /// The plane name (`part.channel`, see [`channel_name`]). + pub(crate) name: String, + /// Its part and its position in the part's channel list. + pub(crate) part: usize, + pub(crate) channel: usize, + /// The value outside the part's data window (the background depth for depth channels). + pub(crate) fill: f32, +} + +/// A file's main picture: its channels (indices into [`ExrIndex::channels`]) in the layout's +/// order, `R`, `G`, `B` (`A`) or `Y` (`A`). +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct MainPicture { + pub(crate) layout: ColorLayout, + pub(crate) ids: Vec, + /// When a picture channel's plane isn't 0 outside the part's data window (a part whose name + /// reads as depth, `depth.R`: its planes keep the background depth for effects), the data + /// window in display pixels, `[x0, y0, x1, y1)`: the picture is 0 outside it, as the `image` + /// crate and After Effects show it. + pub(crate) inside: Option<[usize; 4]>, +} + +impl MainPicture { + /// The red, green, blue and alpha channels (a `Y` picture is grey: `Y` three times). + pub(crate) fn rgba(&self) -> Option<([usize; 3], Option)> { + let id = |i: usize| self.ids.get(i).copied(); + match self.layout { + ColorLayout::Rgb | ColorLayout::Rgba => Some(([id(0)?, id(1)?, id(2)?], id(3))), + ColorLayout::Y | ColorLayout::YA => Some(([id(0)?; 3], id(1))), + } + } + + /// It has an alpha channel. + pub(crate) fn has_alpha(&self) -> bool { + matches!(self.layout, ColorLayout::Rgba | ColorLayout::YA) + } +} + +/// What an OpenEXR file holds ([`get`]). +pub(crate) struct ExrIndex { + /// The headers and chunk tables, as `craft-exr` reads them. + pub(crate) file: seek::Index, + /// The file's identity when indexed: a read of another identity indexes it again. + pub(crate) stamp: FileStamp, + /// The first part's display window: every plane covers it. + pub(crate) display: Window, + pub(crate) channels: Vec, + /// The file's main picture ([`craft_exr::channels::main_picture`]), as After Effects shows + /// it: `None` for a file of named layers only (it shows black; effects reach its layers by + /// name). + pub(crate) picture: Option, + /// The names only (planes empty), manifests and aliases: for the channel lists and for + /// resolving what effects declare. Never handed to an effect. + pub(crate) names: Arc, +} + +impl ExrIndex { + /// The display window's size. + pub(crate) fn size(&self) -> (usize, usize) { + (self.display.width as usize, self.display.height as usize) + } + + /// The channels the picture is made of, in file order (none for a file without a main + /// picture). + pub(crate) fn picture_ids(&self) -> Vec { + let mut ids = self.picture.as_ref().map(|p| p.ids.clone()).unwrap_or_default(); + ids.sort_unstable(); + ids.dedup(); + ids + } + + /// Every channel but the picture's (what [`crate::exr_planes`] means by all channels: the + /// picture is kept converted, by the media pool, not as planes too). + pub(crate) fn aux_ids(&self) -> Vec { + let picture = self.picture_ids(); + (0..self.channels.len()).filter(|i| !picture.contains(i)).collect() + } + + /// The channels named `names` (exact plane names, each once, in file order). + pub(crate) fn ids_named<'a>(&self, names: impl IntoIterator) -> Vec { + let names: std::collections::HashSet<&str> = names.into_iter().collect(); + self.channels.iter().enumerate().filter(|(_, c)| names.contains(c.name.as_str())).map(|(i, _)| i).collect() + } + + /// About the bytes it holds: `craft-exr`'s index (its chunks and header facts), the channels + /// and the manifests. + pub(crate) fn bytes(&self) -> usize { + let names: usize = self.channels.iter().map(|c| c.name.len() * 2 + 64).sum(); + let manifests: usize = self.names.manifests.iter().map(|(l, m)| l.len() + m.iter().map(|(n, _)| n.len() + 32).sum::()).sum(); + self.file.bytes().saturating_add(names).saturating_add(manifests.saturating_mul(2)) + } +} + +/// Why a file has no index. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum IndexError { + /// Not an OpenEXR file this reader takes (decoders may still try the whole file). + Unreadable, + /// An OpenEXR file whose compression can't be decoded (the reason, to show). + Unsupported(&'static str), + /// The file can't be opened or read. + Io, +} + +/// Why an HTJ2K file (OpenEXR 3.4's High-Throughput JPEG 2000) isn't read. +pub(crate) const HTJ2K: &str = "OpenEXR HTJ2K compression isn't supported yet: re-save the file with ZIP, PIZ or DWAA compression"; + +/// The most pixels of a part's data window (the display window's limit, four times over: data +/// windows may reach past it). +const MAX_DATA_PIXELS: usize = 4 * MAX_DISPLAY_PIXELS; + +/// What `craft-exr` may index: data windows of at most [`MAX_DATA_PIXELS`], of any width or +/// height (the display window is checked against [`MAX_DISPLAY_PIXELS`] in [`build`]), and +/// blocks of at most `craft-exr`'s default ratio of bytes per byte of their chunk (four times +/// that for DWA, plus 1 MiB): a hostile header declaring a block of gigabytes over a chunk of a +/// few bytes is refused, by every read and by [`safe_to_decode`]. A read's planes are bounded by +/// its own cap ([`crate::exr_read::MAX_DECODE_BYTES`], or more with more memory: +/// [`effectcraft_render::memory::decode_limit`]). +fn limits() -> Limits { + let mut limits = Limits::none(); + limits.max_pixels = MAX_DATA_PIXELS as u64; + limits.max_ratio = Limits::default().max_ratio; + limits +} + +/// The headers and offset tables of the OpenEXR file in `src`, read and checked by `craft-exr`. +fn index_file(src: &mut dyn ReadSeek) -> Result { + src.seek(SeekFrom::Start(0)).map_err(|e| seek::Error::Io(e.to_string()))?; + // (an index is shared by every request for the file: building one is never called off) + seek::Index::build(src, &limits(), &|| false) +} + +/// The headers of the OpenEXR `bytes` are safe to hand to a decoder (the `image` crate, which +/// allocates every block by its header): they can be read, no part's data window is larger than +/// this reader takes, and no block is larger than its chunk can decompress to ([`limits`]) +/// (#3271 review). A file this reader doesn't cover (deep parts, HTJ2K) is left to the decoder; +/// damaged headers, a part or a block too large, and a failed read are refused. +pub(crate) fn safe_to_decode(bytes: &[u8]) -> bool { + match index_file(&mut std::io::Cursor::new(bytes)) { + Ok(index) => index.check_blocks().is_ok(), + Err(seek::Error::Unsupported(_) | seek::Error::UnsupportedCompression(_)) => true, + Err(_) => false, + } +} + +/// The channel list of `part` as the `exr` crate's validation took it (#3271): sorted by name, +/// every sampling factor non-zero and dividing the data window's position and size. The headers +/// are read leniently, and the crate's decompressors divide by the sampling of every channel of +/// a chunk, requested or not (where panics abort, in the browser, that would end the app). +fn channels_valid(part: &PartInfo) -> bool { + let w = part.data_window; + let divides = |s: usize, pos: i32, size: u32| i64::try_from(s).ok().filter(|s| *s > 0).is_some_and(|s| i64::from(pos) % s == 0 && i64::from(size) % s == 0); + let sorted = part.channels.windows(2).all(|pair| pair.first().zip(pair.get(1)).is_some_and(|(a, b)| a.name.as_bytes() <= b.name.as_bytes())); + sorted && part.channels.iter().all(|c| divides(c.sampling.0, w.x, w.width) && divides(c.sampling.1, w.y, w.height)) +} + +/// Index the OpenEXR file in `src` (identity `stamp`), reading its headers and offset tables +/// only. +pub(crate) fn build(src: &mut dyn ReadSeek, stamp: FileStamp) -> Result { + let file = index_file(src).map_err(|e| match e { + seek::Error::UnsupportedCompression(name) if name.contains("HTJ2K") => IndexError::Unsupported(HTJ2K), + // (memory refused just now: another attempt may succeed, nothing is remembered) + seek::Error::Io(_) | seek::Error::OutOfMemory(_) => IndexError::Io, + _ => IndexError::Unreadable, + })?; + // A block larger than its chunk can decompress to (a hostile header): the file is refused + // as a whole, as every read of it would refuse that chunk. + file.check_blocks().map_err(|_| IndexError::Unreadable)?; + let parts = file.parts(); + // Deep data isn't read (the whole file was refused before). + if parts.iter().any(|p| p.deep || !channels_valid(p)) { + return Err(IndexError::Unreadable); + } + let display = file.display(); + // Each plane covers the display window: a 60000² window over a 1×1 data window was a + // multi-gigabyte allocation per channel (#2141). + (display.width as usize).checked_mul(display.height as usize).filter(|n| *n > 0 && *n <= MAX_DISPLAY_PIXELS).ok_or(IndexError::Unreadable)?; + let manifests = manifests(parts); + let mut channels = vec![]; + let mut aliases = vec![]; + for (pi, p) in parts.iter().enumerate() { + let prefix = part_name(p); + for (ci, ch) in p.channels.iter().enumerate() { + let stored = ch.name.clone(); + let name = channel_name(prefix.as_deref(), &stored); + // A stored `layer.channel` name inside a part named otherwise is also found as stored + // (`Crypto_Material00.R` in part `Crypto_Material`); bare names (`R`) are not. + if prefix.is_some() && name != stored && stored.contains('.') { + aliases.push((stored, name.clone())); + } + let fill = if is_depth(&name) { BACKGROUND_DEPTH } else { 0.0 }; + channels.push(IndexChannel { name, part: pi, channel: ci, fill }); + } + } + let picture = main_picture(parts, display, &channels); + let mut names = AuxChannels::new(display.width, display.height, 1.0); + names.channels = channels.iter().map(|c| (c.name.clone(), vec![])).collect(); + names.manifests = manifests; + names.aliases = aliases; + Ok(ExrIndex { file, stamp, display, channels, picture, names: Arc::new(names) }) +} + +/// The Cryptomatte manifests of the headers (`cryptomatte//name` and `…/manifest`, in any +/// part), sorted. +fn manifests(parts: &[PartInfo]) -> Vec<(String, Vec<(String, u32)>)> { + let mut crypto: HashMap, Option)> = HashMap::new(); + for (key, value) in parts.iter().flat_map(|p| &p.text_attributes) { + let Some(rest) = key.strip_prefix("cryptomatte/") else { continue }; + let Some((id, field)) = rest.split_once('/') else { continue }; + let e = crypto.entry(id.to_string()).or_default(); + match field { + "name" => e.0 = Some(value.clone()), + "manifest" => e.1 = Some(value.clone()), + _ => {} + } + } + let mut out: Vec<(String, Vec<(String, u32)>)> = crypto.into_values().filter_map(|(name, manifest)| Some((name?, parse_manifest(&manifest?)))).collect(); + out.sort(); + out +} + +/// The file's main picture by the OpenEXR convention, as After Effects shows it +/// ([`craft_exr::channels::main_picture`]: the unprefixed `R`, `G`, `B` (`A`) of the first part +/// that has them, else the first unprefixed `Y` (`A`)), as channel ids. The parts' channels are +/// matched as stored (a part's own `R`, not the `part.R` plane name). +fn main_picture(parts: &[PartInfo], display: Window, channels: &[IndexChannel]) -> Option { + let (part, layout, picked) = craft_exr::channels::main_picture(parts.iter().map(|p| p.channels.iter().map(|c| c.name.as_str())))?; + let ids = picked.iter().map(|ci| channels.iter().position(|c| c.part == part && c.channel == *ci)).collect::>>()?; + let filled = ids.iter().any(|id| channels.get(*id).is_some_and(|c| c.fill != 0.0)); + let inside = match filled { + true => Some(data_window_in_display(parts.get(part)?.data_window, display)), + false => None, + }; + Some(MainPicture { layout, ids, inside }) +} + +/// The part of `data` inside `display`, in display pixels from its top left: `[x0, y0, x1, y1)`. +fn data_window_in_display(data: Window, display: Window) -> [usize; 4] { + let clamp = |v: i64, size: u32| usize::try_from(v.clamp(0, i64::from(size))).unwrap_or(0); + let (x0, y0) = (i64::from(data.x) - i64::from(display.x), i64::from(data.y) - i64::from(display.y)); + let (x1, y1) = (x0.saturating_add(i64::from(data.width)), y0.saturating_add(i64::from(data.height))); + [clamp(x0, display.width), clamp(y0, display.height), clamp(x1, display.width), clamp(y1, display.height)] +} + +/// At most this many files are indexed, and their indexes take at most [`INDEXED_BYTES`]; the +/// oldest goes first. +const INDEXED_FILES: usize = 4096; +const INDEXED_BYTES: usize = 64 << 20; + +/// Indexed files by path. +struct Indexes { + map: HashMap>, + order: VecDeque, + bytes: usize, +} + +fn indexes() -> &'static Mutex { + static INDEXES: std::sync::OnceLock> = std::sync::OnceLock::new(); + INDEXES.get_or_init(|| Mutex::new(Indexes { map: HashMap::new(), order: VecDeque::new(), bytes: 0 })) +} + +fn lock() -> std::sync::MutexGuard<'static, Indexes> { + indexes().lock().unwrap_or_else(PoisonError::into_inner) +} + +/// Keep `index` as the index of `path`, dropping the oldest beyond the bounds (the newest stays). +pub(crate) fn keep(path: &str, index: Arc) { + let mut ix = lock(); + let bytes = index.bytes(); + match ix.map.insert(path.to_string(), index) { + Some(old) => ix.bytes = ix.bytes.saturating_sub(old.bytes()), + None => ix.order.push_back(path.to_string()), + } + ix.bytes = ix.bytes.saturating_add(bytes); + for _ in 0..=ix.order.len() { + if (ix.map.len() <= INDEXED_FILES && ix.bytes <= INDEXED_BYTES) || ix.map.len() <= 1 { + break; + } + let Some(old) = ix.order.pop_front() else { break }; + if old == path { + ix.order.push_back(old); + continue; + } + if let Some(gone) = ix.map.remove(&old) { + ix.bytes = ix.bytes.saturating_sub(gone.bytes()); + } + } +} + +/// The index of the file at `path` (read from `source` the first time; kept until +/// [`forget`]). A file whose identity changed since (size, modification time; checked at most +/// once per [`crate::exr_read::STAMP_TTL`], #3334) is indexed again; a read checks it again on +/// the file it opens. +pub(crate) fn get(path: &str, source: &ExrSource) -> Result, IndexError> { + get_opened(path, source).map(|(ix, _)| ix) +} + +/// [`get`], with the file left open when indexing it opened it: a decode that follows reads from +/// it instead of opening the file again (one open per new frame, #3271). +pub(crate) fn get_opened(path: &str, source: &ExrSource) -> Result<(Arc, Option), IndexError> { + let kept = lock().map.get(path).cloned(); + if let Some(ix) = kept { + match source.stamp() { + Ok(stamp) if stamp == ix.stamp => return Ok((ix, None)), + Ok(_) => {} + Err(e) => { + log::debug!("media: {path}: {e}"); + return Err(IndexError::Io); + } + } + } + let mut opened = source.open().map_err(|e| { + log::debug!("media: {path}: {e}"); + IndexError::Io + })?; + // (the identity just read: the next checks within the stamp's lifetime use it) + source.opened_as(opened.stamp); + let ix = Arc::new(build(&mut *opened.reader, opened.stamp)?); + keep(path, ix.clone()); + Ok((ix, Some(opened))) +} + +/// The index of `path` if it is kept. +#[cfg_attr(not(test), allow(dead_code))] +pub(crate) fn cached(path: &str) -> Option> { + lock().map.get(path).cloned() +} + +/// Drop the index of `path` (the file changed on disk), and the identity last read of it. +pub(crate) fn forget(path: &str) { + crate::exr_read::forget_stamp(std::path::Path::new(path)); + let mut ix = lock(); + if let Some(gone) = ix.map.remove(path) { + ix.bytes = ix.bytes.saturating_sub(gone.bytes()); + ix.order.retain(|p| p != path); + } +} diff --git a/crates/media/src/exr_planes.rs b/crates/media/src/exr_planes.rs new file mode 100644 index 000000000..2791295a9 --- /dev/null +++ b/crates/media/src/exr_planes.rs @@ -0,0 +1,1630 @@ +//! The plane store (#3271): decoded OpenEXR channel planes in RAM, one entry per file, +//! shared by every consumer of a frame: the picture of a footage layer and the channels its +//! effects read (EXtractoR, Cryptomatte, the 3D Channel effects). It replaces the pool's own +//! OpenEXR decode and the separate channel cache of #474. +//! +//! - **Single flight.** One decode per entry at a time; requests for it wait instead of +//! decoding again. A request arriving before the decode has started reading adds its +//! channels to it; one arriving later waits, and if that decode doesn't cover it, the next +//! decode reads only the channels still missing. +//! - **Covered requests are served from the store**: an entry holds one set of planes (the +//! union of what was decoded, [`Batch`]), and any request for a subset gets it as it is. +//! - **Never on the wrong thread.** The decode runs on the footage decode threads +//! ([`crate::pool::decode_threads`]); a request on another thread hands it over and blocks +//! plainly. A thread running a decode never waits for another (rayon lets a thread waiting in +//! a parallel loop run other jobs, which could wait on that very decode): it decodes a copy. +//! - **Nothing made before a Reload is kept or served** ([`forget`]): a decode that started +//! before the file was forgotten keeps nothing, and the requests waiting for it ask again. +//! - Kept by the memory accountant (#3298): least recently used offered first, each entry worth +//! what decoding it took. Also bounded by bytes by itself ([`CACHE_BUDGET`] until the caches' +//! budget is set, then the footage frames' cap, [`set_budget`]: the whole budget on the +//! desktop, at most [`crate::exr_channels::WEB_CACHE_CAP`] in the browser); there the newest +//! entry stays even when it alone is over. Entries in use (planes an effect holds, a decode in +//! progress, the last pictures' planes kept for their effects, [`HELD_FILES`]) are never +//! dropped, by either. + +use std::collections::{BTreeSet, VecDeque}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; + +use rayon::prelude::*; + +use effectcraft_raster::channels3d::AuxNeed; +use effectcraft_raster::{AuxChannels, Image}; +use effectcraft_render::reads::ReadFile; + +use crate::convert::AlphaOp; +use crate::exr_channels::CACHE_BUDGET; +use crate::exr_channels::{black_picture, planes_picture}; +use crate::exr_index::{self, ExrIndex, IndexError}; +use crate::exr_read::{ExrSource, Opened, ReadError, ReadRequest, read_planes}; + +/// At most this many entries are kept (unreadable files hold no bytes). +const CACHE_FILES: usize = 64; + +/// At most this many pictures' planes are kept for their effects (the renderer asks for a +/// frame's picture, then its channels): about as many frames as are rendered at once. +const HELD_FILES: usize = 4; + +/// How long a request waits for another's decode before it decodes a copy (a safety net for a +/// decode that hangs). +#[cfg(not(target_arch = "wasm32"))] +const WAIT_LIMIT: std::time::Duration = std::time::Duration::from_secs(10); + +/// How often a request asks again after a decode it waited for was called off or forgotten, +/// and how many rounds it waits at most, before it decodes a copy itself. +const RETRIES: u32 = 3; +const ROUNDS: u32 = 8; + +/// At most this many failed requests are remembered per entry. +const FAILED_KEPT: usize = 8; + +/// What a round of [`PlaneStore::get`] ended with. +enum Step { + Done(Result, Refused>), + /// Ask again (`retry`: the decode waited for was called off, stopped or forgotten). + Again { + retry: bool, + }, +} + +/// A request for `want` of the file `index` describes asks for at least what `failed` asked for +/// (`all` is every channel but the picture's: it doesn't cover a picture channel asked for by id). +fn asks_at_least(index: &ExrIndex, want: &Want, failed: &Want) -> bool { + if failed.all && !want.all { + return false; + } + let aux = if want.all { index.aux_ids() } else { Vec::new() }; + failed.ids.iter().all(|id| want.ids.contains(id) || aux.contains(id)) +} + +/// Decode `want` for this request alone (kept nowhere), noting the file it read. `live`: planes +/// of the file let go but still in memory ([`PlaneStore::live`]). +fn copy(path: &str, source: &ExrSource, index: &Arc, want: &Want, live: usize) -> Result, Refused> { + let b = run(path, source, &Flight::new(index.clone(), want.clone(), live), None); + if let Ok(b) = &b { + crate::reads::note(b.file.clone()); + } + b +} + +/// Decoded planes of a file: the union of the channels read so far. +pub(crate) struct Batch { + /// The index they were read with (channel ids are its). + pub(crate) index: Arc, + /// The channels held, in file order (parallel to `aux.channels`). + pub(crate) ids: Vec, + /// Every channel of the file but the picture's ([`ExrIndex::aux_ids`]; the picture's may be + /// there too). + pub(crate) all: bool, + pub(crate) aux: Arc, + /// The file as read. + pub(crate) file: ReadFile, +} + +impl Batch { + /// Bytes held (the planes; names and manifests are small). + fn bytes(&self) -> usize { + self.aux.channels.iter().map(|(n, p)| n.len() + std::mem::size_of_val(p.as_slice())).sum() + } + + /// The plane of channel `id`. + pub(crate) fn plane(&self, id: usize) -> Option<&[f32]> { + let at = self.ids.binary_search(&id).ok()?; + self.aux.channels.get(at).map(|(_, p)| p.as_slice()) + } + + /// It holds what `want` asks of the file `index` describes. + fn covers(&self, index: &Arc, want: &Want) -> bool { + Arc::ptr_eq(&self.index, index) && (self.all || !want.all) && want.ids.iter().all(|id| self.ids.binary_search(id).is_ok()) + } +} + +/// The channels a request asks for. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct Want { + /// Every channel but the picture's ([`ExrIndex::aux_ids`]): the picture's planes are asked + /// for by name (`ids`). + pub(crate) all: bool, + pub(crate) ids: BTreeSet, +} + +impl Want { + fn add(&mut self, other: &Want) { + self.all |= other.all; + self.ids.extend(other.ids.iter().copied()); + } +} + +/// Who asks. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Use { + /// The picture of a footage item whose effects read its channels next: kept for them. + Picture, + /// Anything else (the channels themselves, a picture alone). + Other, +} + +/// Why a request got no planes. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Refused { + /// Not readable (remembered until the file is forgotten). + Unreadable, + /// More planes than one file may allocate (the reason; remembered). + TooLarge(String), + /// The system refused the memory the planes need just now (the reason): not remembered, + /// but not asked again at once either, nor read as a whole file another way (#3749). + NoMemory(String), + /// The request was called off. + Cancelled, + /// The file changed since it was indexed: index it again and ask again. + Changed, + /// The file was forgotten while it decoded: ask again. + Forgotten, + /// The decode stopped (it panicked, or the file couldn't be opened just then): not + /// remembered, the next request decodes again. + Stopped, + /// The planes held don't fit the limit with the ones missing, but the request fits alone: + /// the store lets the held ones go first, then the request is read on its own (so the held + /// and the new planes are never in memory together). Ask again. + LetGo, +} + +/// A decode in progress: what it reads (until it starts reading) and its outcome. +struct Flight { + state: Mutex, + ready: Condvar, + /// [`QUEUED`], [`RUNNING`] (the decode began where it was asked for) or [`CLAIMED`] (a + /// decode thread took it over before it began, [`Flight::claim`]: the outcome comes through + /// `handed`). + phase: std::sync::atomic::AtomicU8, + handed: Mutex, Refused>>>, + handed_ready: Condvar, + /// What the store held when the decode was asked for (the decode adds to it). Taken when the + /// store lets it go ([`PlaneStore::let_go`]): the requests still holding the flight (its + /// waiters, until they wake) don't keep those planes in memory. + base: Mutex>>, + /// Planes of the file the store let go ([`Refused::LetGo`]) that are still in memory when the + /// decode was asked for: a caller holds them, or a decode that let them go hasn't ended yet + /// ([`PlaneStore::live`]). They count toward the limit with the planes read. + live: usize, + /// The disk cache's drop generation before the file was opened for this request (#3191: a + /// plane entry made of a file reloaded since is refused). + since: u64, + /// The cancel flag and decoding hints of the request that asked for the decode: a decode + /// thread that claims it decodes under them (its own being called off doesn't call off the + /// asker's decode). + hints: filmcraft_media::cancel::Context, + /// When the decode was asked for ([`effectcraft_render::memory::tick`]): what it took is the + /// planes' cost to the memory accountant. + asked: u64, + /// The decode limit's generation when the decode was asked for + /// ([`effectcraft_render::memory::decode_limit_generation`]): a refusal for its size holds + /// only while the limit stays as it was. + limit_generation: u64, +} + +/// [`Flight::phase`] values. +const QUEUED: u8 = 0; +const RUNNING: u8 = 1; +const CLAIMED: u8 = 2; + +/// The disk cache's drop generation now (0 without one): taken before a file is opened. +fn drop_generation() -> u64 { + disk_cache().map_or(0, |d| d.drop_generation()) +} + +struct FlightState { + index: Arc, + want: Want, + /// Reading started: requests no longer add to `want`. + sealed: bool, + outcome: Option, Refused>>, +} + +impl Flight { + fn new(index: Arc, want: Want, live: usize) -> Arc { + Flight::with_base(index, want, None, live, drop_generation()) + } + + fn with_base(index: Arc, want: Want, base: Option>, live: usize, since: u64) -> Arc { + Arc::new(Flight { + state: Mutex::new(FlightState { index, want, sealed: false, outcome: None }), + ready: Condvar::new(), + phase: std::sync::atomic::AtomicU8::new(QUEUED), + handed: Mutex::new(None), + handed_ready: Condvar::new(), + base: Mutex::new(base), + live, + since, + hints: filmcraft_media::cancel::Context::current(), + asked: effectcraft_render::memory::tick(), + limit_generation: effectcraft_render::memory::decode_limit_generation(), + }) + } + + /// Move the flight from [`QUEUED`] to `to`; `false` when it left that phase already. + fn take(&self, to: u8) -> bool { + use std::sync::atomic::Ordering; + self.phase.compare_exchange(QUEUED, to, Ordering::SeqCst, Ordering::SeqCst).is_ok() + } + + /// Take over the decode while it is still queued (a decode thread asking for the planes + /// it would wait for: waiting there could starve the queue it waits on). `false` once it + /// began. + fn claim(&self) -> bool { + self.take(CLAIMED) + } + + /// The decode asked for more than `want` (other requests added to it): a refusal for its + /// size may not hold for `want` alone. + fn asks_beyond(&self, index: &ExrIndex, want: &Want) -> bool { + !asks_at_least(index, want, &self.state().want) + } + + fn claimed(&self) -> bool { + self.phase.load(std::sync::atomic::Ordering::SeqCst) == CLAIMED + } + + /// Hand the claimed decode's outcome to the request that queued it. + fn hand(&self, outcome: Result, Refused>) { + *self.handed.lock().unwrap_or_else(PoisonError::into_inner) = Some(outcome); + self.handed_ready.notify_all(); + } + + /// The outcome a claiming decode thread hands over (a plain block: that decode is running + /// and waits for nothing). + fn take_handed(&self) -> Result, Refused> { + let mut h = self.handed.lock().unwrap_or_else(PoisonError::into_inner); + loop { + if let Some(o) = h.as_ref() { + return o.clone(); + } + h = match self.handed_ready.wait(h) { + Ok(g) => g, + Err(p) => p.into_inner(), + }; + } + } + + /// [`Flight::base`] (`None` once let go). + fn base(&self) -> Option> { + self.base.lock().unwrap_or_else(PoisonError::into_inner).clone() + } + + fn state(&self) -> MutexGuard<'_, FlightState> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn end(&self, outcome: Result, Refused>) { + self.state().outcome = Some(outcome); + self.ready.notify_all(); + } +} + +struct Entry { + path: String, + batch: Option>, + flight: Option>, + /// Requests that failed for good (unreadable, too large), the index they were made with, and + /// why: a request of that index (the file as it was) asking for at + /// least as much fails the same way until the file is forgotten, or the decode limit changed + /// (the last number: its generation when the request was made). + failed: Vec<(Arc, Want, Refused, u64)>, + bytes: usize, + /// When it was last asked for or finished decoding ([`effectcraft_render::memory::tick`]). + used: u64, + /// What decoding its planes took, in microseconds (0: not decoded yet). + cost_us: u64, + /// Planes the store let go ([`Refused::LetGo`]), held weakly, and how many: while something + /// still holds them they are in memory, and count toward a read's limit ([`Entry::live`]). + let_go: Vec<(std::sync::Weak, usize)>, +} + +impl Entry { + /// The planes let go that are still in memory (forgetting those that are gone). + fn live(&mut self) -> usize { + self.let_go.retain(|(w, _)| w.strong_count() > 0); + self.let_go.iter().map(|(_, n)| *n).fold(0, usize::saturating_add) + } + + /// Dropping it would free nothing or lose work in progress: a decode runs, or planes are held + /// (also planes it let go: dropping the entry would forget that they are still in memory). + fn in_use(&self) -> bool { + self.flight.is_some() + || self.batch.as_ref().is_some_and(|b| Arc::strong_count(b) > 1 || Arc::strong_count(&b.aux) > 1) + || self.let_go.iter().any(|(w, _)| w.strong_count() > 0) + } +} + +struct State { + entries: Vec, + /// Pictures' planes kept for their effects, oldest first (at most [`HELD_FILES`]). + held: VecDeque<(String, Arc)>, +} + +/// The request decoding an entry: it stores the outcome and ends the flight, also when the decode +/// panics (then with an error), so no request waits for planes that never come and the entry +/// doesn't stay "decoding". +struct Owning<'a> { + store: &'a PlaneStore, + path: &'a str, + flight: &'a Arc, + ended: bool, +} + +impl Owning<'_> { + fn end(&mut self, outcome: Result, Refused>) -> Result, Refused> { + self.ended = true; + let (outcome, grown) = self.store.finish(self.path, self.flight, outcome); + self.flight.end(outcome.clone()); + effectcraft_render::memory::Accountant::global().note_growth(grown); + outcome + } +} + +impl Drop for Owning<'_> { + fn drop(&mut self) { + if !self.ended { + let _ = self.end(Err(Refused::Stopped)); + } + } +} + +/// Decoded planes by file, bounded by bytes. +pub(crate) struct PlaneStore { + state: Mutex, + /// Bytes it keeps at most ([`set_budget`]). + budget: std::sync::atomic::AtomicUsize, +} + +thread_local! { + /// Store decodes running on this thread: such a thread doesn't wait for another decode. + static DECODING: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Marks a store decode on this thread ([`DECODING`]) until dropped (also when it panics). +struct Decoding; + +impl Decoding { + fn new() -> Decoding { + DECODING.with(|n| n.set(n.get().saturating_add(1))); + Decoding + } +} + +impl Drop for Decoding { + fn drop(&mut self) { + DECODING.with(|n| n.set(n.get().saturating_sub(1))); + } +} + +/// What waiting for another request's decode ended with. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +enum Waited { + Got(Result, Refused>), + /// This request was called off meanwhile. + Cancelled, + /// This thread may not wait, or waited too long: decode a copy. + No, +} + +/// One decode the store ran (tests and measurements): the channels read and what it cost. +#[cfg(test)] +#[derive(Clone, Debug)] +pub(crate) struct DecodeRecord { + pub(crate) channels: Vec, + pub(crate) stats: crate::exr_read::ReadStats, + /// Read from the disk cache, not from the file. + pub(crate) from_disk: bool, +} + +#[cfg(test)] +static DECODES: Mutex> = Mutex::new(Vec::new()); + +/// Paths whose queued decode a decode thread took over (tests), and a signal for each. +#[cfg(test)] +pub(crate) static CLAIMS: Mutex> = Mutex::new(Vec::new()); +#[cfg(test)] +pub(crate) static CLAIM_SIGNAL: Condvar = Condvar::new(); + +/// The decodes of `path` so far (tests; paths are unique per test). +#[cfg(test)] +pub(crate) fn decodes_of(path: &str) -> Vec { + DECODES.lock().unwrap_or_else(PoisonError::into_inner).iter().filter(|(p, _)| p == path).map(|(_, d)| d.clone()).collect() +} + +/// Run before a decode of a path is queued on the decode threads (`QUEUING`), when the +/// queued job begins (`STARTING`) and after it sent its outcome (`SENT`), keyed by path (tests: +/// holding a decode queued, or its decode thread busy after it). +#[cfg(test)] +pub(crate) static QUEUING: Mutex> = Mutex::new(Vec::new()); +#[cfg(test)] +pub(crate) static STARTING: Mutex> = Mutex::new(Vec::new()); +#[cfg(test)] +pub(crate) static SENT: Mutex> = Mutex::new(Vec::new()); +/// Run when the request that queued a decode a decode thread took over got its outcome, before +/// it goes on (tests: holding that request while the decode thread asks again). +#[cfg(test)] +pub(crate) static HANDED: Mutex> = Mutex::new(Vec::new()); + +#[cfg(test)] +fn run_hook(hooks: &Mutex>, path: &str) { + let hook = hooks.lock().unwrap_or_else(PoisonError::into_inner).iter().find(|(p, _)| p == path).map(|(_, h)| h.clone()); + if let Some(h) = hook { + h(path); + } +} + +/// Runs before a decode reads its chunks, with the file's path (tests). +#[cfg(test)] +type Hook = Arc; +#[cfg(test)] +static BEFORE_READ: Mutex> = Mutex::new(Vec::new()); + +/// Run `hook` before each decode of `path` reads its chunks (`None`: no longer). Keyed by path, +/// so tests running at the same time don't see each other's. +#[cfg(test)] +pub(crate) fn set_before_read(path: &str, hook: Option) { + let mut hooks = BEFORE_READ.lock().unwrap_or_else(PoisonError::into_inner); + hooks.retain(|(p, _)| p != path); + if let Some(h) = hook { + hooks.push((path.to_string(), h)); + } +} + +/// Planes of `path` may take at most this many bytes in a read (tests: a cap of the caller's own, +/// below the system's limit; outside tests there is none, `usize::MAX`, and only +/// [`effectcraft_render::memory::decode_limit`] applies). +#[cfg(test)] +static CAPS: Mutex> = Mutex::new(Vec::new()); + +#[cfg(test)] +pub(crate) fn set_cap(path: &str, bytes: usize) { + CAPS.lock().unwrap_or_else(PoisonError::into_inner).push((path.to_string(), bytes)); +} + +/// The most bytes of planes one read of `path` may allocate by the caller's own limit (none: the +/// system's, [`effectcraft_render::memory::decode_limit`]). +fn cap_of(path: &str) -> usize { + #[cfg(test)] + if let Some((_, c)) = CAPS.lock().unwrap_or_else(PoisonError::into_inner).iter().find(|(p, _)| p == path) { + return *c; + } + let _ = path; + usize::MAX +} + +impl PlaneStore { + pub(crate) const fn new(budget: usize) -> PlaneStore { + PlaneStore { state: Mutex::new(State { entries: Vec::new(), held: VecDeque::new() }), budget: std::sync::atomic::AtomicUsize::new(budget) } + } + + fn budget(&self) -> usize { + self.budget.load(std::sync::atomic::Ordering::Relaxed) + } + + /// Keep at most `bytes` from now on, dropping the oldest entries not in use at once. + pub(crate) fn set_budget(&self, bytes: usize) { + self.budget.store(bytes, std::sync::atomic::Ordering::Relaxed); + Self::drop_oldest(&mut self.lock(), bytes, CACHE_FILES, None); + } + + fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// The planes of `want` of the file at `path` (`index`, read from `source`): from the store, + /// from a decode in progress, or decoded now (only what the store doesn't hold yet). The + /// file it was read from is noted ([`crate::reads`]). A request that keeps finding the + /// decodes it waits for called off decodes a copy itself. + #[cfg_attr(not(test), allow(dead_code))] + pub(crate) fn get(&self, path: &str, source: &ExrSource, index: &Arc, want: &Want, by: Use) -> Result, Refused> { + self.get_opened(path, source, index, want, by, None, drop_generation()) + } + + /// [`PlaneStore::get`] with the file already open (`opened`, as indexing it opened it): a + /// decode reads from it instead of opening the file again, so a new frame opens its file + /// once (#3271). Dropped unused when the store serves the request. `since`: the disk cache's + /// drop generation before the file was opened ([`drop_generation`]). + #[allow(clippy::too_many_arguments)] + pub(crate) fn get_opened( + &self, + path: &str, + source: &ExrSource, + index: &Arc, + want: &Want, + by: Use, + mut opened: Option, + since: u64, + ) -> Result, Refused> { + let mut retries = 0; + for _ in 0..ROUNDS { + match self.step(path, source, index, want, by, &mut opened, since) { + Step::Done(r) => return r, + Step::Again { retry: true } if retries >= RETRIES => break, + Step::Again { retry } => retries += u32::from(retry), + } + } + copy(path, source, index, want, self.live(path)) + } + + /// The planes of `path` the store let go ([`Refused::LetGo`]) that are still in memory: a + /// caller holds them (an effect, a Cryptomatte pick), or a decode that let them go hasn't + /// ended yet (#3750 review). A read counts them with its own planes. + fn live(&self, path: &str) -> usize { + self.lock().entries.iter_mut().find(|e| e.path == path).map_or(0, Entry::live) + } + + /// One round of [`PlaneStore::get`]. + #[allow(clippy::too_many_arguments)] + fn step(&self, path: &str, source: &ExrSource, index: &Arc, want: &Want, by: Use, opened: &mut Option, since: u64) -> Step { + let mut st = self.lock(); + // (shared with the footage frames: one least-recently-used order across both) + let clock = effectcraft_render::memory::tick(); + let at = match st.entries.iter().position(|e| e.path == path) { + Some(i) => i, + None => { + st.entries.push(Entry { path: path.to_string(), batch: None, flight: None, failed: vec![], bytes: 0, used: clock, cost_us: 0, let_go: vec![] }); + st.entries.len() - 1 + } + }; + let Some(e) = st.entries.get_mut(at) else { return Step::Done(Err(Refused::Unreadable)) }; + e.used = clock; + // What the store holds first: a failure of a larger request doesn't hide it. + if let Some(b) = e.batch.clone().filter(|b| b.covers(index, want)) { + Self::hold(&mut st, path, &b, by); + drop(st); + crate::reads::note(b.file.clone()); + return Step::Done(Ok(b)); + } + // (a failure of the file as it was before: the file changed since, it is read again) + let limit = effectcraft_render::memory::decode_limit_generation(); + if let Some((_, _, why, _)) = e.failed.iter().find(|(of, failed, refusal, made_at)| { + Arc::ptr_eq(of, index) && (!matches!(refusal, Refused::TooLarge(_)) || *made_at == limit) && asks_at_least(index, want, failed) + }) { + return Step::Done(Err(why.clone())); + } + let live = e.live(); + if let Some(flight) = e.flight.clone() { + { + let mut fs = flight.state(); + if !fs.sealed && Arc::ptr_eq(&fs.index, index) { + fs.want.add(want); + } + } + drop(st); + // A decode thread doesn't wait (see `wait`), but takes over a decode still queued: + // the planes are decoded once, here, and handed to the request that queued them. + if may_not_wait() && flight.claim() { + return match decode_claimed(path, source, &flight, index, want, live) { + // (the held planes go now, not only once the asker ends the decode: this + // request asks again at once) + Err(Refused::LetGo) => { + Self::let_go(&mut self.lock(), path, &flight); + Step::Again { retry: true } + } + r => Step::Done(r), + }; + } + return match self.wait(&flight) { + Waited::Got(Ok(b)) if b.covers(index, want) => { + crate::reads::note(b.file.clone()); + Step::Done(Ok(b)) + } + // Not all it asks for: ask again (the next decode reads what is missing). + Waited::Got(Ok(_)) => Step::Again { retry: false }, + Waited::Got(Err(Refused::Cancelled | Refused::Forgotten | Refused::Stopped | Refused::LetGo)) => Step::Again { retry: true }, + // Too large with what other requests added to it: this request alone may fit. + Waited::Got(Err(Refused::TooLarge(_))) if flight.asks_beyond(index, want) => Step::Again { retry: true }, + Waited::Got(Err(e)) => Step::Done(Err(e)), + Waited::Cancelled => Step::Done(Err(Refused::Cancelled)), + // A copy, kept nowhere (with the planes let go that something still holds now). + Waited::No => Step::Done(copy(path, source, index, want, self.live(path))), + }; + } + // This request decodes: what it asks for, minus what the store holds. + let base = e.batch.clone().filter(|b| Arc::ptr_eq(&b.index, index)); + let flight = Flight::with_base(index.clone(), want.clone(), base, live, since); + e.flight = Some(flight.clone()); + drop(st); + #[cfg(test)] + crate::exr_channels::count_decode(true); + let mut owning = Owning { store: self, path, flight: &flight, ended: false }; + let outcome = run(path, source, &flight, opened.take()); + match owning.end(outcome) { + Ok(b) if b.covers(index, want) => { + let mut st = self.lock(); + Self::hold(&mut st, path, &b, by); + drop(st); + crate::reads::note(b.file.clone()); + Step::Done(Ok(b)) + } + Ok(_) | Err(Refused::Forgotten | Refused::Stopped | Refused::LetGo) => Step::Again { retry: true }, + // (as a waiter: this request alone may fit) + Err(Refused::TooLarge(_)) if flight.asks_beyond(index, want) => Step::Again { retry: true }, + Err(e) => Step::Done(Err(e)), + } + } + + /// Keep only the channels `keep` of the planes `b` of `path` (a picture converted: the pool + /// keeps the picture, its planes would be a second copy of it); nothing when none is left. + /// The set is trimmed in place when nobody else holds it, else the kept planes are copied; + /// when the system can't give the memory for that copy, the set stays as it was. + pub(crate) fn keep_only(&self, path: &str, b: Arc, keep: &BTreeSet) { + if b.ids.iter().all(|id| keep.contains(id)) { + return; + } + let mut st = self.lock(); + let Some(at) = st.entries.iter().position(|e| e.path == path && e.batch.as_ref().is_some_and(|k| Arc::ptr_eq(k, &b))) else { return }; + let held = st.held.iter().any(|(p, h)| p == path && Arc::ptr_eq(h, &b)); + // (taken out of the entry and the held list: then this is likely the only holder) + if let Some(e) = st.entries.get_mut(at) { + e.batch = None; + e.bytes = 0; + } + st.held.retain(|(p, h)| !(p == path && Arc::ptr_eq(h, &b))); + let slimmed = match Arc::try_unwrap(b) { + Ok(mut owned) => match Arc::try_unwrap(owned.aux) { + Ok(mut aux) => { + let channels = std::mem::take(&mut aux.channels); + aux.channels = owned.ids.iter().zip(channels).filter(|(id, _)| keep.contains(id)).map(|(_, c)| c).collect(); + owned.ids.retain(|id| keep.contains(id)); + aux.listed = owned.index.channels.iter().map(|c| c.name.clone()).collect(); + owned.aux = Arc::new(aux); + Ok(owned) + } + Err(shared_aux) => { + owned.aux = shared_aux; + match slim_copy(path, &owned, keep) { + Some(slim) => Ok(slim), + None => Err(Arc::new(owned)), + } + } + }, + Err(shared) => slim_copy(path, &shared, keep).ok_or(shared), + }; + let slim = match slimmed { + Ok(slim) => slim, + // (no memory for the copy: the set stays as it was) + Err(whole) => { + if let Some(e) = st.entries.get_mut(at) { + e.bytes = whole.bytes(); + e.batch = Some(whole.clone()); + } + if held { + st.held.push_back((path.to_string(), whole)); + } + return; + } + }; + if slim.ids.is_empty() { + return; + } + let slim = Arc::new(slim); + if let Some(e) = st.entries.get_mut(at) { + e.bytes = slim.bytes(); + e.batch = Some(slim.clone()); + } + if held { + st.held.push_back((path.to_string(), slim)); + } + } + + /// Keep `b` for the effects of the picture asking (`Use::Picture`), or stop keeping the + /// file's planes once its channels are asked for. + fn hold(st: &mut State, path: &str, b: &Arc, by: Use) { + match by { + Use::Picture => { + if !st.held.iter().any(|(p, _)| p == path) { + st.held.push_back((path.to_string(), b.clone())); + if st.held.len() > HELD_FILES { + st.held.pop_front(); + } + } + } + Use::Other => st.held.retain(|(p, _)| p != path), + } + } + + /// Store the outcome of `flight`'s decode in its entry, unless the file was forgotten + /// meanwhile (then nothing made of it is kept or handed out); drop what doesn't fit. + /// Also the bytes the store grew by (for the memory accountant). + fn finish(&self, path: &str, flight: &Arc, outcome: Result, Refused>) -> (Result, Refused>, usize) { + let mut st = self.lock(); + // (shared with the footage frames: one least-recently-used order across both) + let clock = effectcraft_render::memory::tick(); + let Some(e) = st.entries.iter_mut().find(|e| e.path == path && e.flight.as_ref().is_some_and(|f| Arc::ptr_eq(f, flight))) else { + let outcome = match outcome { + Err(e @ (Refused::Cancelled | Refused::Stopped | Refused::NoMemory(_))) => Err(e), + _ => Err(Refused::Forgotten), + }; + return (outcome, 0); + }; + e.flight = None; + e.used = clock; + let had = e.bytes; + match &outcome { + Ok(b) => { + e.bytes = b.bytes(); + e.batch = Some(b.clone()); + let took = clock.saturating_sub(flight.asked).max(1); + // A decode adding channels to what was held: both decodes made the planes; one + // that read them all anew replaces what was held, and its cost. + e.cost_us = if flight.base().is_some() { e.cost_us.saturating_add(took) } else { took }; + } + Err(why @ (Refused::Unreadable | Refused::TooLarge(_))) => { + let (index, want) = { + let fs = flight.state(); + (fs.index.clone(), fs.want.clone()) + }; + // (failures of another version of the file no longer apply) + // (a refusal for the size counts under the limit it was made under only) + e.failed + .retain(|(of, _, old, made_at)| Arc::ptr_eq(of, &index) && (!matches!(old, Refused::TooLarge(_)) || *made_at == flight.limit_generation)); + if e.failed.len() >= FAILED_KEPT { + e.failed.remove(0); + } + e.failed.push((index, want, why.clone(), flight.limit_generation)); + } + // (the file changed: what is held is of the old one) + Err(Refused::Changed) => { + e.batch = None; + e.bytes = 0; + e.cost_us = 0; + } + // (memory refused just now: another request may get it; the planes held go first, + // then the request is read on its own, below) + Err(Refused::Cancelled | Refused::Forgotten | Refused::Stopped | Refused::NoMemory(_) | Refused::LetGo) => {} + } + if matches!(outcome, Err(Refused::LetGo)) { + Self::let_go(&mut st, path, flight); + } + let grown = st.entries.iter().find(|e| e.path == path).map_or(0, |e| e.bytes.saturating_sub(had)); + Self::drop_oldest(&mut st, self.budget(), CACHE_FILES, Some(path)); + (outcome, grown) + } + + /// Let the planes `flight` was asked to add to go ([`Refused::LetGo`]): the entry of `path` + /// and the pictures' held planes no longer keep them (unless the entry holds others by now), + /// nor the flight (whose waiters may hold it a while yet). + fn let_go(st: &mut State, path: &str, flight: &Flight) { + let Some(base) = flight.base.lock().unwrap_or_else(PoisonError::into_inner).take() else { return }; + let base = &base; + if let Some(e) = st.entries.iter_mut().find(|e| e.path == path && e.batch.as_ref().is_some_and(|b| Arc::ptr_eq(b, base))) { + e.batch = None; + e.bytes = 0; + e.cost_us = 0; + // (still in memory while anything else holds them: counted until they are gone) + e.live(); + e.let_go.push((Arc::downgrade(&base.aux), base.aux.channels.len())); + } + st.held.retain(|(p, h)| !(p == path && Arc::ptr_eq(h, base))); + } + + /// Drop least recently used entries until the rest take at most `bytes` in at most `files` + /// entries, never one in use, the pictures' planes held for their effects, or `newest` (just + /// decoded); entries that hold no bytes (a failure remembered) only when there are too many. + fn drop_oldest(st: &mut State, bytes: usize, files: usize, newest: Option<&str>) { + loop { + if st.entries.iter().map(|e| e.bytes).fold(0usize, usize::saturating_add) <= bytes && st.entries.len() <= files { + break; + } + // (an entry holding no bytes only goes for the count) + let over_count = st.entries.len() > files; + let Some(i) = Self::oldest_droppable(st, newest, over_count) else { break }; + st.entries.remove(i); + } + } + + /// The least recently used entry that may be dropped: not `newest`, not in use, not a + /// picture's planes held for its effects, and holding bytes (unless `empty_too`). + fn oldest_droppable(st: &State, newest: Option<&str>, empty_too: bool) -> Option { + let held = &st.held; + st.entries + .iter() + .enumerate() + .filter(|(_, e)| Some(e.path.as_str()) != newest && !e.in_use() && (e.bytes > 0 || empty_too)) + .filter(|(_, e)| !e.batch.as_ref().is_some_and(|b| held.iter().any(|(_, h)| Arc::ptr_eq(h, b)))) + .min_by_key(|(_, e)| e.used) + .map(|(i, _)| i) + } + + /// The entry the memory accountant may drop next ([`PlaneStore::oldest_droppable`]), with + /// what decoding it took (a typical cost when not timed). + fn oldest_candidate(&self) -> Option { + let st = self.lock(); + let e = st.entries.get(Self::oldest_droppable(&st, None, false)?)?; + let cost_us = + if e.cost_us > 0 { e.cost_us } else { effectcraft_render::memory::default_cost(e.bytes, effectcraft_render::memory::DEFAULT_PLANE_US_PER_MB) }; + Some(effectcraft_render::memory::Candidate { used: e.used, bytes: e.bytes, cost_us, protected: false }) + } + + /// Drop [`PlaneStore::oldest_candidate`]; the bytes freed. + fn drop_candidate(&self) -> usize { + let mut st = self.lock(); + let Some(i) = Self::oldest_droppable(&st, None, false) else { return 0 }; + if i < st.entries.len() { st.entries.remove(i).bytes } else { 0 } + } + + /// Wait for the outcome of another request's decode (`flight`). A thread running a store + /// decode doesn't wait (see the module notes); the time limit is a safety net. + #[cfg(not(target_arch = "wasm32"))] + fn wait(&self, flight: &Flight) -> Waited { + if may_not_wait() { + return Waited::No; + } + let until = std::time::Instant::now() + WAIT_LIMIT; + let mut fs = flight.state(); + loop { + if let Some(o) = fs.outcome.as_ref() { + return Waited::Got(o.clone()); + } + if filmcraft_media::cancel::cancelled() { + return Waited::Cancelled; + } + let left = until.saturating_duration_since(std::time::Instant::now()); + if left.is_zero() { + log::warn!("media: OpenEXR planes took over {} s to decode on another thread; decoding a copy", WAIT_LIMIT.as_secs()); + return Waited::No; + } + fs = match flight.ready.wait_timeout(fs, left.min(std::time::Duration::from_millis(20))) { + Ok((g, _)) => g, + Err(p) => p.into_inner().0, + }; + } + } + + /// (A wasm32 build has one thread: a decode in flight is further down this thread's stack.) + #[cfg(target_arch = "wasm32")] + fn wait(&self, _flight: &Flight) -> Waited { + Waited::No + } + + /// Drop the planes of `path` (the file changed on disk); a decode of it in progress keeps + /// nothing. + pub(crate) fn forget(&self, path: &str) { + let mut st = self.lock(); + st.entries.retain(|e| e.path != path); + st.held.retain(|(p, _)| p != path); + } + + /// Stop keeping the last pictures' planes for their effects. + pub(crate) fn release_held(&self) { + self.lock().held.clear(); + } + + /// The channels kept of `path` and their bytes (tests). + #[cfg(test)] + pub(crate) fn kept(&self, path: &str) -> Option<(Vec, usize)> { + let st = self.lock(); + let e = st.entries.iter().find(|e| e.path == path)?; + let b = e.batch.as_ref()?; + Some((b.aux.channels.iter().map(|(n, _)| n.clone()).collect(), e.bytes)) + } + + #[cfg(test)] + pub(crate) fn cached(&self) -> Vec { + self.lock().entries.iter().filter(|e| e.batch.is_some() || !e.failed.is_empty()).map(|e| e.path.clone()).collect() + } + + #[cfg(test)] + pub(crate) fn is_held(&self, path: &str) -> bool { + self.lock().held.iter().any(|(p, _)| p == path) + } +} + +/// The channels `keep` of `b` (of `path`) in a set of their own, the planes copied; `None` when +/// the system can't give the memory for a copy. +fn slim_copy(path: &str, b: &Batch, keep: &BTreeSet) -> Option { + #[cfg(test)] + if COPIES_REFUSED.lock().unwrap_or_else(PoisonError::into_inner).iter().any(|p| p == path) { + return None; + } + let _ = path; + let mut aux = AuxChannels::new(b.aux.width, b.aux.height, b.aux.scale); + aux.manifests = b.aux.manifests.clone(); + aux.aliases = b.aux.aliases.clone(); + aux.listed = b.index.channels.iter().map(|c| c.name.clone()).collect(); + for (id, (name, plane)) in b.ids.iter().zip(&b.aux.channels) { + if keep.contains(id) { + aux.channels.push((name.clone(), copy_plane(plane)?)); + } + } + let ids = b.ids.iter().copied().filter(|id| keep.contains(id)).collect(); + Some(Batch { index: b.index.clone(), ids, all: b.all, aux: Arc::new(aux), file: b.file.clone() }) +} + +/// One path per plane copied for the disk cache (tests). +#[cfg(test)] +pub(crate) static DISK_COPIES: Mutex> = Mutex::new(Vec::new()); + +/// Paths whose planes [`slim_copy`] finds no memory for (tests). +#[cfg(test)] +pub(crate) static COPIES_REFUSED: Mutex> = Mutex::new(Vec::new()); + +/// This thread may not wait for planes: a decode thread (#3270: a decode doesn't depend on the +/// requests waiting for it; an owner on a frame worker queues its decode on these threads, and +/// a decode thread waiting for it could starve that queue), or one running a store decode. +fn may_not_wait() -> bool { + let on_decode_thread = { + #[cfg(not(target_arch = "wasm32"))] + { + crate::pool::decode_threads().is_some_and(|t| t.current_thread_index().is_some()) + } + #[cfg(target_arch = "wasm32")] + { + false + } + }; + on_decode_thread || DECODING.with(std::cell::Cell::get) > 0 +} + +/// Hands a claimed decode's outcome over when dropped, an error when the decode stopped +/// (panicked): the request that queued it never waits for an outcome that doesn't come. +struct Handing<'a> { + flight: &'a Flight, + outcome: Option, Refused>>, +} + +impl Drop for Handing<'_> { + fn drop(&mut self) { + self.flight.hand(self.outcome.take().unwrap_or(Err(Refused::Stopped))); + } +} + +/// Decode a flight claimed by this thread (see [`Flight::claim`]) here, hand the outcome to the +/// request that queued it, and answer this request with it (or a copy when it doesn't cover it). +fn decode_claimed(path: &str, source: &ExrSource, flight: &Arc, index: &Arc, want: &Want, live: usize) -> Result, Refused> { + #[cfg(test)] + { + CLAIMS.lock().unwrap_or_else(PoisonError::into_inner).push(path.to_string()); + CLAIM_SIGNAL.notify_all(); + } + let mut handing = Handing { flight, outcome: None }; + let outcome = flight.hints.clone().run(|| decode(path, source, flight, flight.base(), None)); + handing.outcome = Some(outcome.clone()); + drop(handing); + match outcome { + Ok(b) if b.covers(index, want) => { + crate::reads::note(b.file.clone()); + Ok(b) + } + // (memory the system refused just now is not asked for again at once, see `NoMemory`; + // planes held to let go first are let go by the store, not read beside in a copy) + Err(e @ (Refused::NoMemory(_) | Refused::LetGo)) => Err(e), + _ => copy(path, source, index, want, live), + } +} + +/// Run `flight`'s decode on the footage decode threads (here when this is one of them, or +/// there are none) and block until it is done. +fn run(path: &str, source: &ExrSource, flight: &Arc, opened: Option) -> Result, Refused> { + #[cfg(not(target_arch = "wasm32"))] + if let Some(threads) = crate::pool::decode_threads() + && threads.current_thread_index().is_none() + { + #[cfg(test)] + let asker = path.to_string(); + let (tx, rx) = std::sync::mpsc::sync_channel(1); + let (path, source, queued) = (path.to_string(), source.clone(), flight.clone()); + // The request's cancel flag and decoding hints go with it. + let hints = filmcraft_media::cancel::Context::current(); + #[cfg(test)] + run_hook(&QUEUING, &path); + threads.spawn(move || { + #[cfg(test)] + run_hook(&STARTING, &path); + // (claimed meanwhile by a decode thread: it decodes, and hands the outcome over) + if queued.take(RUNNING) { + let outcome = hints.run(|| decode(&path, &source, &queued, queued.base(), opened)); + // (let go of the flight before the asker goes on: the flight keeps the outcome + // for its waiters, and a flight still held here would keep the planes looking in + // use, so the store would drop another file's instead) + drop(queued); + let _ = tx.send(outcome); + #[cfg(test)] + run_hook(&SENT, &path); + } + }); + // A plain block: this thread runs nothing else meanwhile. + return match rx.recv() { + Ok(outcome) => outcome, + Err(_) if flight.claimed() => { + let handed = flight.take_handed(); + #[cfg(test)] + run_hook(&HANDED, &asker); + handed + } + // (a decode that panicked sent nothing) + Err(_) => Err(Refused::Stopped), + }; + } + // (claimed by a decode thread before this one began: it hands the outcome over) + if !flight.take(RUNNING) { + return flight.take_handed(); + } + decode(path, source, flight, flight.base(), opened) +} + +/// What a failed read of `path` means for the request. +fn refused(path: &str, e: ReadError) -> Refused { + match e { + ReadError::Cancelled => Refused::Cancelled, + // (a read that failed just now: the next request reads again) + ReadError::Io(why) => { + log::warn!("media: {path}: {why}"); + Refused::Stopped + } + ReadError::TooLarge(why) => { + log::warn!("media: {path}: {why}"); + Refused::TooLarge(why) + } + ReadError::OutOfMemory(why) => { + log::warn!("media: {path}: {why}"); + Refused::NoMemory(why) + } + ReadError::Unreadable(why) => { + log::warn!("media: {path}: {why}"); + Refused::Unreadable + } + } +} + +/// A copy of `plane`, or `None` when the system can't give the memory for it (an allocation that +/// fails aborts the process, so it is asked for first). +fn copy_plane(plane: &[f32]) -> Option> { + let mut copy: Vec = Vec::new(); + copy.try_reserve_exact(plane.len()).ok()?; + copy.extend_from_slice(plane); + Some(copy) +} + +/// Why `planes` planes of a `w` × `h` display window couldn't be had (to show). +fn no_memory_for(w: usize, h: usize, planes: usize) -> String { + let bytes = w.saturating_mul(h).saturating_mul(planes).saturating_mul(std::mem::size_of::()); + format!("its {w}×{h} OpenEXR channels need {:.1} GB more memory than the system can give just now", bytes as f64 / f64::from(1u32 << 30)) +} + +/// Fails the reads of a path as a test says, for the channels read ([`set_read_error`]). +#[cfg(test)] +pub(crate) type ForcedError = Arc Option + Send + Sync>; +#[cfg(test)] +static READ_ERRORS: Mutex> = Mutex::new(Vec::new()); + +/// Make reads of `path` fail as `error` says for the channels read, instead of reading (`None`: +/// read again; tests: memory the system refuses). Keyed by path, so tests running at the same +/// time don't see each other's. +#[cfg(test)] +pub(crate) fn set_read_error(path: &str, error: Option) { + let mut errors = READ_ERRORS.lock().unwrap_or_else(PoisonError::into_inner); + errors.retain(|(p, _)| p != path); + if let Some(e) = error { + errors.push((path.to_string(), e)); + } +} + +/// How a test makes the read of `ids` of `path` fail ([`set_read_error`]); never outside tests. +fn forced_read_error(path: &str, ids: &[usize]) -> Option { + #[cfg(test)] + { + let error = READ_ERRORS.lock().unwrap_or_else(PoisonError::into_inner).iter().find(|(p, _)| p == path).map(|(_, e)| e.clone()); + error.and_then(|e| e(ids)) + } + #[cfg(not(test))] + { + let _ = (path, ids); + None + } +} + +/// Decode what `flight` asks for and `base` doesn't hold, and make the union of both. +fn decode(path: &str, source: &ExrSource, flight: &Arc, base: Option>, opened: Option) -> Result, Refused> { + let _decoding = Decoding::new(); + // The file as indexing opened it, else opened now (a share that doesn't answer just now + // isn't remembered as unreadable). + let opened = match opened { + Some(o) => Ok(o), + None => source.open(), + }; + let mut opened = opened.map_err(|e| { + log::warn!("media: {path}: {e}"); + Refused::Stopped + })?; + let index = flight.state().index.clone(); + if opened.stamp != index.stamp { + // The file changed since it was indexed (the next index check sees its new identity). + source.opened_as(opened.stamp); + let fresh = exr_index::build(&mut *opened.reader, opened.stamp).map_err(|_| Refused::Unreadable)?; + exr_index::keep(path, Arc::new(fresh)); + return Err(Refused::Changed); + } + #[cfg(test)] + { + let hook = BEFORE_READ.lock().unwrap_or_else(PoisonError::into_inner).iter().find(|(p, _)| p == path).map(|(_, h)| h.clone()); + if let Some(h) = hook { + h(path); + } + } + // From here on the request is fixed. + let want = { + let mut fs = flight.state(); + fs.sealed = true; + fs.want.clone() + }; + let wanted: Vec = if want.all { + index.aux_ids().into_iter().chain(want.ids.iter().copied()).collect::>().into_iter().collect() + } else { + want.ids.iter().copied().collect() + }; + let wanted: Vec = wanted.into_iter().filter(|i| *i < index.channels.len()).collect(); + let base = base.filter(|b| Arc::ptr_eq(&b.index, &index)); + let missing: Vec = wanted.iter().copied().filter(|id| !base.as_ref().is_some_and(|b| b.ids.binary_search(id).is_ok())).collect(); + let (w, h) = index.size(); + // The planes the request ends with (those held plus those missing, whether they come from the + // disk cache or the file) must fit the limit, asked before any of them is allocated (#3749). + // The planes held are only kept for later requests: when they don't fit with the missing + // ones, they are let go and the request is read on its own. The store lets them go first + // (`LetGo`), so they are not in memory while the request is read. + // Planes let go before but still in memory (a caller holds them, or the decode that let them + // go hasn't ended) count too (#3750 review): when they are what keeps the request over the + // limit, it is refused for now (not remembered), not read beside them. + if !missing.is_empty() { + let cap = cap_of(path); + let fits = |planes: usize| crate::exr_read::check_total(w, h, planes, cap); + let live = flight.live; + let still_held = || { + log::debug!("media: {path}: {live} OpenEXR channels let go are still in use"); + Refused::NoMemory(format!("its {w}×{h} OpenEXR channels don't fit the memory one file may use beside {live} of its channels still in use")) + }; + let held = base.as_ref().map_or(0, |b| b.ids.len()); + if base.is_some() && fits(held.saturating_add(missing.len()).saturating_add(live)).is_err() { + fits(wanted.len()).map_err(|e| refused(path, e))?; + if fits(wanted.len().saturating_add(live)).is_err() { + return Err(still_held()); + } + return Err(Refused::LetGo); + } + if base.is_none() { + fits(missing.len()).map_err(|e| refused(path, e))?; + if fits(missing.len().saturating_add(live)).is_err() { + return Err(still_held()); + } + } + } + let names: Vec = missing.iter().filter_map(|i| index.channels.get(*i)).map(|c| c.name.clone()).collect(); + // The disk tier first (#3271): what an earlier session or a decode RAM let go of kept, one + // entry per channel (any request is assembled from them, whatever was asked before). + // (a file naming two channels alike can't tell their entries apart: not kept) + let unique = index.channels.iter().map(|c| c.name.as_str()).collect::>().len() == index.channels.len(); + let disk = disk_cache_for(path).filter(|_| !missing.is_empty() && unique); + let since = flight.since; + let key = |name: &str| effectcraft_render::disk_cache::plane_key(path, &opened.stamp, name); + // (read and decompressed side by side on this pool's threads) + let mut kept: Vec>> = match &disk { + Some(d) => names + .par_iter() + .map(|n| { + let (name, plane) = d.get_plane(key(n), w as u32, h as u32)?; + (name == *n && plane.len() == w.saturating_mul(h)).then_some(plane) + }) + .collect(), + None => vec![None; names.len()], + }; + let to_read: Vec = missing.iter().zip(&kept).filter(|(_, k)| k.is_none()).map(|(id, _)| *id).collect(); + let from_disk = to_read.is_empty(); + // (what reading the planes took: their cost, against reading them back from the disk cache) + let read_from = effectcraft_render::memory::tick(); + let (read, stats) = if to_read.is_empty() { + (Ok(vec![]), Default::default()) + } else if let Some(e) = forced_read_error(path, &to_read) { + (Err(e), Default::default()) + } else { + let request = ReadRequest { max_bytes: cap_of(path), ..ReadRequest::full(to_read.clone()) }; + read_planes(&mut *opened.reader, &index, &request) + }; + let read_took = effectcraft_render::memory::tick().saturating_sub(read_from); + #[cfg(test)] + DECODES.lock().unwrap_or_else(PoisonError::into_inner).push((path.to_string(), DecodeRecord { channels: names.clone(), stats: stats.clone(), from_disk })); + #[cfg(not(test))] + let _ = (&stats, from_disk); + let read: Vec> = read.map_err(|e| refused(path, e))?; + let mut read = read.into_iter(); + let planes: Vec> = kept.iter_mut().map(|k| k.take().or_else(|| read.next()).unwrap_or_default()).collect(); + // The union, in file order: the planes held and the ones just read. + let mut new: Vec<(usize, Vec)> = missing.into_iter().zip(planes).collect(); + if let Some(b) = &base { + for (at, id) in b.ids.iter().enumerate() { + if let Some((_, p)) = b.aux.channels.get(at) { + // (the planes held are copied into the new set: memory the system may refuse) + let copy = copy_plane(p).ok_or_else(|| refused(path, ReadError::OutOfMemory(no_memory_for(w, h, b.ids.len()))))?; + new.push((*id, copy)); + } + } + } + new.sort_by_key(|(id, _)| *id); + new.dedup_by_key(|(id, _)| *id); + let all = index.aux_ids().iter().all(|id| new.binary_search_by_key(id, |(i, _)| *i).is_ok()); + let mut aux = AuxChannels::new(w as u32, h as u32, 1.0); + aux.manifests = index.names.manifests.clone(); + aux.aliases = index.names.aliases.clone(); + if new.len() != index.channels.len() { + aux.listed = index.channels.iter().map(|c| c.name.clone()).collect(); + } + let ids: Vec = new.iter().map(|(id, _)| *id).collect(); + aux.channels = new.into_iter().filter_map(|(id, p)| Some((index.channels.get(id)?.name.clone(), p))).collect(); + let file = ReadFile::new(path, opened.stamp); + let batch = Arc::new(Batch { index, ids, all, aux: Arc::new(aux), file }); + // Kept on disk for the next time, each channel read from the file in an entry of its own, + // encoded on the disk cache's writer thread (a file from memory, which can't be checked + // later, isn't). + // (a plane larger than the disk cache may hold, or a cache taking no writes now, is not + // copied at all) + let plane_bytes = w.saturating_mul(h).saturating_mul(std::mem::size_of::()); + if let Some(d) = disk.as_ref().filter(|d| d.accepts_writes() && plane_bytes as u64 <= d.limit_bytes()) { + let mut files = effectcraft_render::reads::ReadFiles::default(); + files.add(batch.file.clone()); + if let Some(entry) = effectcraft_render::disk_cache::EntryFiles::of(&files, None) { + // The planes read now that the disk cache doesn't hold yet. + let fresh: Vec<(u128, &String, &Vec)> = to_read + .iter() + .filter_map(|id| { + let (name, plane) = batch.aux.channels.get(batch.ids.binary_search(id).ok()?)?; + let k = key(name); + (!d.contains(effectcraft_render::disk_cache::Kind::Plane, k)).then_some((k, name, plane)) + }) + .collect(); + // (only planes that cost more to decode again than to read back, #3301) + let bytes = fresh.iter().map(|(_, _, p)| p.len().saturating_mul(std::mem::size_of::())).fold(0, usize::saturating_add); + if !fresh.is_empty() && d.pays_off(bytes, read_took) { + // Copied a job at a time, just before the job is queued (copies, each owned by its + // write: a queued write never keeps the store's set); once the queue refuses a + // job, the rest isn't copied. A plane the system can't give the memory for is + // left out. + let most = d.plane_job_bytes(); + let mut rest = fresh.as_slice(); + while !rest.is_empty() { + let (mut n, mut job_bytes) = (0usize, 0usize); + while let Some((_, _, p)) = rest.get(n) { + let b = p.len().saturating_mul(std::mem::size_of::()); + if n > 0 && job_bytes.saturating_add(b) > most { + break; + } + job_bytes = job_bytes.saturating_add(b); + n += 1; + } + let (job, tail) = rest.split_at(n.min(rest.len())); + rest = tail; + let planes: Vec<(u128, String, Vec)> = job + .par_iter() + .filter_map(|(k, name, plane)| { + let copy = copy_plane(plane)?; + #[cfg(test)] + DISK_COPIES.lock().unwrap_or_else(PoisonError::into_inner).push(path.to_string()); + Some((*k, (*name).clone(), copy)) + }) + .collect(); + if !d.put_planes(w as u32, h as u32, planes, &entry, since) { + break; + } + } + } + } + } + Ok(batch) +} + +/// The disk cache decoded planes are kept in ([`set_disk_cache`]). +static DISK: Mutex>> = Mutex::new(None); + +/// Keep decoded planes in `cache` too (`None`: no disk tier), #3271. Held weakly: switching the +/// disk cache off drops it. +pub(crate) fn set_disk_cache(cache: Option<&Arc>) { + *DISK.lock().unwrap_or_else(PoisonError::into_inner) = cache.map(Arc::downgrade); +} + +fn disk_cache() -> Option> { + DISK.lock().unwrap_or_else(PoisonError::into_inner).as_ref().and_then(std::sync::Weak::upgrade) +} + +/// The disk cache planes of `path` are kept in (tests: only for the paths of the test that set +/// it, [`use_disk_for`], so tests running beside it don't share it). +fn disk_cache_for(path: &str) -> Option> { + #[cfg(test)] + if !DISK_PATHS.lock().unwrap_or_else(PoisonError::into_inner).iter().any(|p| path.starts_with(p.as_str())) { + return None; + } + let _ = path; + disk_cache() +} + +#[cfg(test)] +static DISK_PATHS: Mutex> = Mutex::new(Vec::new()); + +/// Keep the planes of paths under `prefix` in the disk cache (tests). +#[cfg(test)] +pub(crate) fn use_disk_for(prefix: &str) { + DISK_PATHS.lock().unwrap_or_else(PoisonError::into_inner).push(prefix.to_string()); +} + +/// The store all footage shares. +static STORE: PlaneStore = PlaneStore::new(CACHE_BUDGET); + +fn store() -> &'static PlaneStore { + // In the common memory budget (#3271), registered once. + static HOLDER: std::sync::OnceLock> = std::sync::OnceLock::new(); + HOLDER.get_or_init(|| { + let h: Arc = Arc::new(SharedStore); + effectcraft_render::memory::Accountant::global().register(&h); + h + }); + &STORE +} + +/// The shared plane store in the common memory budget (#3271, #3298): decoded planes the effects +/// read, each file's worth what decoding it took, per byte. +struct SharedStore; + +impl effectcraft_render::memory::MemoryHolder for SharedStore { + fn name(&self) -> &'static str { + "footage planes" + } + fn bytes(&self) -> usize { + STORE.lock().entries.iter().map(|e| e.bytes).fold(0, usize::saturating_add) + } + fn oldest(&self) -> Option { + STORE.oldest_candidate() + } + fn drop_oldest(&self) -> usize { + STORE.drop_candidate() + } +} + +/// The most the shared plane store keeps by itself, the footage frames' cap (#3298: the whole +/// common budget on the desktop; in the browser at most [`crate::exr_channels::WEB_CACHE_CAP`]). +/// The memory accountant keeps the planes within the common budget with the other caches. +pub(crate) fn set_budget(bytes: usize) { + let bytes = if cfg!(target_arch = "wasm32") { bytes.min(crate::exr_channels::WEB_CACHE_CAP) } else { bytes }; + store().set_budget(bytes); +} + +/// The bytes the shared plane store keeps at most. +#[cfg(test)] +pub(crate) fn budget() -> usize { + STORE.budget() +} + +/// Is `path` an OpenEXR file by name (the store reads those; other files, and files named so +/// that aren't OpenEXR, go the `image` crate's way). +pub(crate) fn is_exr(path: &str) -> bool { + path.to_ascii_lowercase().ends_with(".exr") +} + +/// The ids `need` reads of the file `index` describes (`None`: all). +fn need_ids(index: &ExrIndex, need: &AuxNeed) -> Option> { + let names = need.resolve(&index.names)?; + Some(index.ids_named(names.iter().map(String::as_str)).into_iter().collect()) +} + +/// The outcome of [`picture`]. +pub(crate) enum Picture { + Done(Result), + Cancelled, + /// Not for the planes (an `image` crate picture, or not an OpenEXR this reader takes): + /// decode the whole file with the `image` crate. + Legacy, +} + +/// The picture of the OpenEXR at `path` made of its planes: its main picture +/// ([`crate::exr_index::MainPicture`]), or black for a file without one (named layers only). +/// With `extra` (an effect reads the footage's channels) those channels are read in the same +/// pass and kept for the effects. +pub(crate) fn picture(path: &str, source: &ExrSource, op: AlphaOp, extra: Option<&AuxNeed>) -> Picture { + let mut extra = extra; + for _ in 0..3 { + // (before the file is opened: see `Flight::since`) + let since = drop_generation(); + let (index, opened) = match exr_index::get_opened(path, source) { + Ok(ix) => ix, + Err(IndexError::Unsupported(why)) => return Picture::Done(Err(why.to_string())), + Err(_) => return Picture::Legacy, + }; + if let Err(why) = picture_fits(path, &index) { + return Picture::Done(Err(why)); + } + let mut want = Want { all: false, ids: index.picture_ids().into_iter().collect() }; + if let Some(need) = extra { + match need_ids(&index, need) { + Some(more) => want.ids.extend(more), + None => want.all = true, + } + } + // (no main picture and nothing for the effects: black, nothing read) + if !want.all && want.ids.is_empty() { + return Picture::Done(picture_of(&index, None, op).ok_or_else(|| "the picture can't be made".to_string())); + } + let by = if extra.is_some() { Use::Picture } else { Use::Other }; + let batch = match store().get_opened(path, source, &index, &want, by, opened, since) { + Ok(b) => b, + Err(Refused::Changed) => continue, + // The channels with it are too many: the picture alone (the effects ask for theirs). + // (also when the system has no memory for them just now, #3749) + Err(Refused::TooLarge(_) | Refused::NoMemory(_)) if extra.is_some() => { + extra = None; + continue; + } + // (never the whole file's decode: the memory isn't there for it either) + Err(Refused::TooLarge(why) | Refused::NoMemory(why)) => return Picture::Done(Err(why)), + // (`LetGo` is asked again inside the store; never here) + Err(Refused::Cancelled | Refused::Forgotten | Refused::LetGo) => return Picture::Cancelled, + // (the whole file's decode says why) + Err(Refused::Stopped | Refused::Unreadable) => return Picture::Legacy, + }; + let img = picture_of(&index, Some(&batch), op); + // The picture is kept by the pool once converted, not twice: its planes go, but for those + // an effect names (EXtractoR reading "R"). + if img.is_some() { + let named = extra.and_then(|n| need_ids(&index, n)).unwrap_or_default(); + let picture: BTreeSet = index.picture_ids().into_iter().filter(|id| !named.contains(id)).collect(); + let keep: BTreeSet = batch.ids.iter().copied().filter(|id| !picture.contains(id)).collect(); + store().keep_only(path, batch, &keep); + } + return match img { + Some(img) => Picture::Done(Ok(img)), + None => Picture::Legacy, + }; + } + Picture::Legacy +} + +/// The picture of the file `index` describes, made of the planes of `batch` (black, opaque, for +/// a file without a main picture, which needs no planes). +fn picture_of(index: &ExrIndex, batch: Option<&Batch>, op: AlphaOp) -> Option { + let Some(main) = &index.picture else { + let (w, h) = index.size(); + return Some(black_picture(u32::try_from(w).ok()?, u32::try_from(h).ok()?, op)); + }; + let batch = batch?; + let ([r, g, b], a) = main.rgba()?; + let a = match a { + Some(a) => Some(batch.plane(a)?), + None => None, + }; + planes_picture(&batch.aux, [batch.plane(r)?, batch.plane(g)?, batch.plane(b)?], a, main.inside, op) +} + +/// The picture of the file `index` describes (float RGBA, 16 bytes a pixel, allocated whole) is +/// no larger than a still may decode to ([`crate::probe::MAX_STILL_PIXELS`]) nor than one read of +/// the file may allocate: else why not, to show. Checked before anything is read, also for the +/// black picture of a file without a main picture. +fn picture_fits(path: &str, index: &ExrIndex) -> Result<(), String> { + let (w, h) = index.size(); + let pixels = (w as u64).saturating_mul(h as u64); + let need = pixels.saturating_mul(16); + let most = (cap_of(path) as u64).min(crate::probe::MAX_STILL_PIXELS.saturating_mul(16)); + if need <= most { + return Ok(()); + } + let gb = |b: u64| b as f64 / f64::from(1u32 << 30); + Err(format!("its {w}×{h} OpenEXR picture needs {:.1} GB of memory, more than the {:.1} GB one file may use", gb(need), gb(most))) +} + +/// The picture of the OpenEXR at `path` (as [`picture`]) of only the display rows `rows` of the +/// footage's `nominal` size: those rows are read (with 1-line chunks exactly those lines, else +/// the chunks holding them) and converted, the others stay empty (#3271: a region of interest). +/// Read for this request alone, not kept in the store or on disk (the pool keeps the picture +/// under a key naming the rows). A file of another size than `nominal` (a sequence frame larger +/// than the first) is shown scaled, so its rows are not those: it is read whole. +pub(crate) fn picture_rows(path: &str, source: &ExrSource, op: AlphaOp, rows: (i64, i64), nominal: (u32, u32)) -> Picture { + let (index, opened) = match exr_index::get_opened(path, source) { + Ok(ix) => ix, + Err(IndexError::Unsupported(why)) => return Picture::Done(Err(why.to_string())), + Err(_) => return Picture::Legacy, + }; + if index.size() != (nominal.0 as usize, nominal.1 as usize) { + drop(opened); + return picture(path, source, op, None); + } + if let Err(why) = picture_fits(path, &index) { + return Picture::Done(Err(why)); + } + // (in file order: the planes are looked up by id) + let ids = index.picture_ids(); + if ids.is_empty() { + return Picture::Done(picture_of(&index, None, op).ok_or_else(|| "the picture can't be made".to_string())); + } + let opened = match opened { + Some(o) => Ok(o), + None => source.open(), + }; + let Ok(mut opened) = opened else { return Picture::Legacy }; + // (a file changed since it was indexed: the whole picture, as `picture` reads it) + if opened.stamp != index.stamp { + return picture(path, source, op, None); + } + let request = ReadRequest { rows: Some(rows.0..rows.1), max_bytes: cap_of(path), ..ReadRequest::full(ids.clone()) }; + let (planes, stats) = match forced_read_error(path, &ids) { + Some(e) => (Err(e), Default::default()), + None => read_planes(&mut *opened.reader, &index, &request), + }; + let names: Vec = ids.iter().filter_map(|i| index.channels.get(*i)).map(|c| c.name.clone()).collect(); + #[cfg(test)] + DECODES.lock().unwrap_or_else(PoisonError::into_inner).push((path.to_string(), DecodeRecord { channels: names.clone(), stats, from_disk: false })); + #[cfg(not(test))] + let _ = stats; + let planes = match planes { + Ok(p) => p, + Err(ReadError::Cancelled) => return Picture::Cancelled, + Err(ReadError::TooLarge(why) | ReadError::OutOfMemory(why)) => return Picture::Done(Err(why)), + Err(_) => return Picture::Legacy, + }; + let (w, h) = index.size(); + let mut aux = AuxChannels::new(w as u32, h as u32, 1.0); + aux.channels = names.into_iter().zip(planes).collect(); + let file = ReadFile::new(path, opened.stamp); + crate::reads::note(file.clone()); + let batch = Batch { index: index.clone(), ids, all: false, aux: Arc::new(aux), file }; + match picture_of(&index, Some(&batch), op) { + Some(img) => Picture::Done(Ok(img)), + None => Picture::Legacy, + } +} + +/// The channels `need` reads of the OpenEXR at `path` (all for [`AuxNeed::All`]), from the +/// store. `None` when it isn't a readable OpenEXR (or the request was called off). +pub(crate) fn aux(path: &str, source: &ExrSource, need: &AuxNeed) -> Option> { + aux_of(path, source, need, false) +} + +/// Every channel of the OpenEXR at `path`, the picture's too ([`FootageSource::aux`]: no render +/// asks for that; a render asks for what its effects read, [`aux`]). +/// +/// [`FootageSource::aux`]: effectcraft_render::FootageSource::aux +pub(crate) fn every_channel(path: &str, source: &ExrSource) -> Option> { + aux_of(path, source, &AuxNeed::All, true) +} + +fn aux_of(path: &str, source: &ExrSource, need: &AuxNeed, with_picture: bool) -> Option> { + for _ in 0..2 { + let since = drop_generation(); + let (index, opened) = exr_index::get_opened(path, source).ok()?; + let mut want = match need_ids(&index, need) { + Some(ids) => Want { all: false, ids }, + None => Want { all: true, ids: BTreeSet::new() }, + }; + if with_picture { + want.ids.extend(index.picture_ids()); + } + match store().get_opened(path, source, &index, &want, Use::Other, opened, since) { + Ok(b) => return Some(b.aux.clone()), + Err(Refused::Changed) => continue, + Err(_) => return None, + } + } + None +} + +/// The channel names (planes empty), manifests and aliases of the OpenEXR at `path`, from its +/// headers alone. Never handed to an effect. +pub(crate) fn names(path: &str, source: &ExrSource) -> Option> { + exr_index::get(path, source).ok().map(|ix| ix.names.clone()) +} + +/// Drop what is kept of `path`: its index and planes. +pub(crate) fn forget(path: &str) { + exr_index::forget(path); + store().forget(path); +} + +/// Stop keeping the last pictures' planes for their effects (which footage effects read changed). +pub(crate) fn release_held() { + store().release_held(); +} + +/// The store all footage shares (tests). +#[cfg(test)] +pub(crate) fn shared() -> &'static PlaneStore { + store() +} + +#[cfg(test)] +mod tests; diff --git a/crates/media/src/exr_planes/tests.rs b/crates/media/src/exr_planes/tests.rs new file mode 100644 index 000000000..ad91319a6 --- /dev/null +++ b/crates/media/src/exr_planes/tests.rs @@ -0,0 +1,2319 @@ +//! The OpenEXR index, reader and plane store (#3271) on synthetic files written here. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use effectcraft_project::{Footage, ItemId}; +use effectcraft_raster::channels3d::{AuxLookup, AuxNeed}; +use effectcraft_render::reads::FileStamp; +use effectcraft_render::{FloatCurve, FootageSource}; +use effectcraft_time::Tick; +use exr::prelude::{ + AnyChannel, AnyChannels, Blocks, Compression, Encoding, FlatSamples, ImageAttributes, IntegerBounds, Layer, LayerAttributes, LineOrder, WritableImage, f16, +}; + +use super::*; +use crate::exr_read::{ExrSource, LIMIT_TESTS}; + +/// A deterministic sample for pixel `i` of channel `c` (an `A` channel gets 0..=1). +fn value(i: usize, c: usize, alpha: bool) -> f32 { + if alpha { ((i * 3 + c) % 11) as f32 / 10.0 } else { ((i * 7 + c * 29) % 97) as f32 / 40.0 - 0.3 } +} + +/// A part named `name` (`None`: unnamed) of `channels` ((name, half)) over `size`, compressed +/// with `compression` in scan lines. +fn part(name: Option<&str>, channels: &[(&str, bool)], size: (usize, usize), compression: Compression) -> Layer> { + let n = size.0 * size.1; + let list: Vec> = channels + .iter() + .enumerate() + .map(|(c, (ch, half))| { + let alpha = ch.rsplit('.').next().is_some_and(|l| l == "A"); + let samples = if *half { + FlatSamples::F16((0..n).map(|i| f16::from_f32(value(i, c, alpha))).collect()) + } else { + FlatSamples::F32((0..n).map(|i| value(i, c, alpha)).collect()) + }; + AnyChannel::new(*ch, samples) + }) + .collect(); + let mut attrs = name.map_or_else(LayerAttributes::default, LayerAttributes::named); + if name == Some("Crypto_Material") { + attrs + .other + .insert(exr::prelude::Text::from("cryptomatte/abc1234/name"), exr::prelude::AttributeValue::Text(exr::prelude::Text::from("Crypto_Material"))); + attrs.other.insert( + exr::prelude::Text::from("cryptomatte/abc1234/manifest"), + exr::prelude::AttributeValue::Text(exr::prelude::Text::from(r#"{"bunny":"13851a76"}"#)), + ); + } + let encoding = Encoding { compression, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing }; + Layer::new(size, attrs, encoding, AnyChannels::sort(list.into())) +} + +/// The bytes of a file of `parts` over a display window of `size`. +fn write(parts: Vec>>, size: (usize, usize)) -> Vec { + let image = exr::prelude::Image::from_layers(ImageAttributes::new(IntegerBounds::from_dimensions(size)), parts); + let mut bytes = std::io::Cursor::new(Vec::new()); + image.write().non_parallel().to_buffered(&mut bytes).unwrap(); + bytes.into_inner() +} + +/// Each part's chunks of the OpenEXR `bytes`, in offset-table order: where each starts and how +/// many bytes it takes (up to the next chunk, or the end of the file). Read with the `exr` crate: +/// `craft-exr`'s index keeps them to itself. +fn chunk_table(bytes: &[u8]) -> Vec> { + let mut src = bytes; + let meta = exr::meta::MetaData::read_from_buffered(&mut src, false).unwrap(); + let tables = exr::meta::MetaData::read_offset_tables(&mut exr::io::PeekRead::new(&mut src), &meta.headers).unwrap(); + let mut starts: Vec = tables.iter().flatten().copied().collect(); + starts.sort_unstable(); + let end = |at: u64| starts.iter().copied().find(|s| *s > at).unwrap_or(bytes.len() as u64); + tables.iter().map(|t| t.iter().map(|at| (*at, end(*at) - at)).collect()).collect() +} + +const SIZE: (usize, usize) = (64, 64); +const RGBA: [(&str, bool); 4] = [("R", true), ("G", true), ("B", true), ("A", true)]; +const CRYPTO: [(&str, bool); 4] = + [("Crypto_Material00.R", false), ("Crypto_Material00.G", false), ("Crypto_Material00.B", false), ("Crypto_Material00.A", false)]; + +/// A multi-part file as renderers write one part per pass: the beauty, a Cryptomatte layer whose +/// channels keep their full names, and depth; one scan line per chunk. +fn multipart() -> Vec { + write( + vec![ + part(Some("beauty"), &RGBA, SIZE, Compression::ZIP1), + part(Some("Crypto_Material"), &CRYPTO, SIZE, Compression::ZIP1), + part(Some("depth"), &[("Z", false)], SIZE, Compression::ZIP1), + ], + SIZE, + ) +} + +/// A single-part ZIPS file with a picture and many passes: every chunk holds every channel. +fn single_part_zips() -> Vec { + let mut list: Vec<(String, bool)> = RGBA.iter().map(|(n, h)| (n.to_string(), *h)).collect(); + for pass in ["diffuse", "specular", "normal", "emit"] { + list.extend(["R", "G", "B"].map(|c| (format!("{pass}.{c}"), true))); + } + list.extend(["R", "G", "B", "A"].map(|c| (format!("CryptoObject00.{c}"), false))); + let names: Vec<(&str, bool)> = list.iter().map(|(n, h)| (n.as_str(), *h)).collect(); + write(vec![part(None, &names, SIZE, Compression::ZIP1)], SIZE) +} + +/// `bytes` written to a temporary file named after `name` (removed by [`Temp`]). +struct Temp(std::path::PathBuf); + +impl Temp { + fn new(name: &str, bytes: &[u8]) -> Temp { + let path = std::env::temp_dir().join(format!("ec-3271-{}-{name}.exr", std::process::id())); + std::fs::write(&path, bytes).unwrap(); + Temp(path) + } +} + +impl Drop for Temp { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +fn bits(img: &Image) -> Vec { + img.data.iter().flat_map(|p| p.map(f32::to_bits)).collect() +} + +/// The picture the `image` crate's decoder shows of `bytes`, converted as the pool converts it. +fn image_crates(bytes: &[u8], f: &Footage) -> Image { + let img = crate::probe::load_oriented(bytes, Some(image::ImageFormat::OpenExr)).unwrap(); + crate::convert::dynamic_to_image(&img, AlphaOp::of(f, FloatCurve::Srgb)) +} + +/// The chunks a decode fetched in all. +fn chunks(r: &DecodeRecord) -> usize { + r.stats.chunks.iter().sum() +} + +/// #3271: the picture of a multi-part file reads the beauty part's chunks and nothing else, +/// converts only its channels, and is the `image` crate's picture bit for bit. +#[test] +fn a_picture_reads_only_its_part() { + let bytes = multipart(); + let file = Temp::new("picture-part", &bytes); + let f = crate::probe(&file.0).unwrap(); + let path = f.path.clone(); + let pool = crate::MediaPool::new(); + let img = pool.frame_at(&f, Tick::ZERO).unwrap(); + assert_eq!(bits(&img), bits(&image_crates(&bytes, &f)), "the image crate's picture"); + let d = decodes_of(&path); + assert_eq!(d.len(), 1, "{d:?}"); + assert_eq!(d[0].channels, ["beauty.A", "beauty.B", "beauty.G", "beauty.R"]); + assert_eq!(d[0].stats.chunks, [SIZE.1, 0, 0], "only the beauty part's chunks"); + let beauty: u64 = chunk_table(&bytes)[0].iter().map(|(_, len)| len).sum(); + assert_eq!(d[0].stats.bytes, beauty, "the beauty part's bytes and nothing else"); +} + +/// #3271: EXtractoR reading 3 channels of a multi-part file reads only their part and converts +/// only those channels; the stored names find them (`Crypto_Material00.R` in part +/// `Crypto_Material`), and the manifest and layer resolve as the file names them. +#[test] +fn three_aux_channels_read_only_their_part() { + let bytes = multipart(); + let file = Temp::new("aux-part", &bytes); + let f = crate::probe(&file.0).unwrap(); + let path = f.path.clone(); + let pool = crate::MediaPool::new(); + let need = AuxNeed::Lookups(["Crypto_Material00.R", "Crypto_Material00.G", "Crypto_Material00.B"].map(|n| AuxLookup::Name(n.into())).to_vec()); + let aux = pool.aux_for(ItemId(1), &f, Tick::ZERO, &need).unwrap(); + let d = decodes_of(&path); + assert_eq!(d.len(), 1); + assert_eq!(d[0].channels.len(), 3, "{:?}", d[0].channels); + assert_eq!(d[0].stats.chunks, [0, SIZE.1, 0], "only the Cryptomatte part's chunks"); + let r = aux.get("Crypto_Material00.R").unwrap(); + assert_eq!(r.len(), SIZE.0 * SIZE.1); + assert_eq!(r.get(5).copied(), Some(value(5, 0, false))); + assert!(aux.get("Crypto_Material00.A").is_none(), "not read"); + assert!(aux.listed.iter().any(|n| n == "depth.Z"), "every name listed"); +} + +/// #3271: lookups by the name a multi-part file stores a channel under work on all channels too +/// (EXtractoR's `Crypto_Material00.R`, Cryptomatte's Layer Name `Crypto_Material`), while the +/// channel list keeps showing `Crypto_Material.Crypto_Material00.R`. +#[test] +fn multipart_channels_are_found_by_their_stored_names() { + let bytes = multipart(); + let path = "/3271-stored-names.exr"; + let pool = crate::MediaPool::new(); + pool.add_bytes(path, bytes.as_slice().into()); + let f = crate::probe_bytes(path, bytes.as_slice().into()).unwrap(); + let aux = pool.aux(ItemId(1), &f, Tick::ZERO).unwrap(); + assert!(aux.names().contains(&"Crypto_Material.Crypto_Material00.R"), "{:?}", aux.names()); + assert!(aux.get("Crypto_Material00.R").is_some()); + let layer = effectcraft_raster::channels3d::crypto_layer_named(&aux, "Crypto_Material", 0).unwrap(); + assert_eq!(layer, "Crypto_Material.Crypto_Material"); + assert_eq!(aux.crypto_rank_planes(&layer).len(), 2); + assert_eq!(aux.manifest(&layer).map(<[_]>::len), Some(1)); + // The names alone, from the headers. + let names = pool.aux_names(ItemId(1), &f, Tick::ZERO).unwrap(); + assert_eq!(names.names(), aux.names()); + assert!(names.channels.iter().all(|(_, p)| p.is_empty()), "no pixels decoded"); +} + +/// The main picture is the first part with unprefixed `R`, `G`, `B`: a depth part before it +/// isn't the picture (nor read for it), the second part's RGBA is. +#[test] +fn a_depth_part_first_leaves_the_picture_to_the_rgba_part() { + let bytes = write(vec![part(Some("depth"), &[("Z", false)], SIZE, Compression::ZIP1), part(Some("beauty"), &RGBA, SIZE, Compression::ZIP1)], SIZE); + let file = Temp::new("depth-first", &bytes); + let f = crate::probe(&file.0).unwrap(); + assert_eq!((f.width, f.height), (SIZE.0 as u32, SIZE.1 as u32)); + let index = crate::exr_index::get(&f.path, &ExrSource::Bytes(bytes.as_slice().into())).unwrap(); + let names: Vec<&str> = index.picture.as_ref().unwrap().ids.iter().map(|i| index.channels[*i].name.as_str()).collect(); + assert_eq!(names, ["beauty.R", "beauty.G", "beauty.B", "beauty.A"]); + let img = crate::MediaPool::new().frame_at(&f, Tick::ZERO).unwrap(); + assert_eq!(bits(&img), bits(&image_crates(&bytes, &f)), "the RGBA part, as the image crate shows it"); + let d = decodes_of(&f.path); + assert_eq!(d.last().unwrap().stats.chunks, [0, SIZE.1], "only the RGBA part's chunks"); +} + +/// The black picture of a file without a main picture is allocated whole like any picture: one +/// larger than one read of the file may allocate is refused with the reason, not allocated (an +/// abort in the browser); within it, it is black at the file's size. +#[test] +fn a_black_picture_too_large_is_refused_not_allocated() { + let bytes = write(vec![part(None, &[("depth.Z", false)], (8, 8), Compression::ZIP1)], (8, 8)); + let path = "/no-picture-too-large.exr"; + let source = ExrSource::Bytes(bytes.as_slice().into()); + let op = AlphaOp::of(&Footage::default(), FloatCurve::Linear); + set_cap(path, 8 * 8 * 16 - 1); + match picture(path, &source, op, None) { + Picture::Done(Err(why)) => assert!(why.contains("8×8") && why.contains("GB"), "{why}"), + _ => panic!("refused"), + } + let fits = "/no-picture-fits.exr"; + set_cap(fits, 8 * 8 * 16); + let Picture::Done(Ok(img)) = picture(fits, &source, op, None) else { panic!("a black picture") }; + assert_eq!((img.width, img.height), (8, 8)); + assert!(img.data.iter().all(|p| *p == [0.0, 0.0, 0.0, 1.0])); +} + +/// A luminance file (`Y` only, no `R`, `G`, `B`) is grey, as before. +#[test] +fn a_luminance_file_is_grey() { + let bytes = write(vec![part(None, &[("Y", true)], SIZE, Compression::ZIP1)], SIZE); + let file = Temp::new("luminance", &bytes); + let f = crate::probe(&file.0).unwrap(); + let path = f.path.clone(); + let source = ExrSource::Bytes(bytes.as_slice().into()); + let Picture::Done(Ok(img)) = picture(&path, &source, AlphaOp::of(&f, FloatCurve::Linear), None) else { panic!("a picture") }; + for (i, px) in img.data.iter().enumerate() { + let y = f16::from_f32(value(i, 0, false)).to_f32(); + assert_eq!([px[0], px[1], px[2], px[3]], [y, y, y, 1.0], "pixel {i}"); + } + assert_eq!( + bits(&crate::MediaPool::new().frame_at(&f, Tick::ZERO).unwrap()), + bits(&crate::convert::dynamic_to_image(&crate::exr_channels::picture_image(&bytes).unwrap(), AlphaOp::of(&f, FloatCurve::Srgb))) + ); +} + +/// #3271: footage whose effects read 3 channels decodes its picture with them in one pass: one +/// read of the file's chunks, one decode, for the picture and the effect. +#[test] +fn picture_and_aux_share_one_read_and_one_decode() { + let bytes = single_part_zips(); + let file = Temp::new("one-decode", &bytes); + let f = crate::probe(&file.0).unwrap(); + let path = f.path.clone(); + let pool = crate::MediaPool::new(); + let need = AuxNeed::Lookups(vec![AuxLookup::Name("normal.R".into()), AuxLookup::Crypto { name: String::new(), index: 0 }]); + pool.set_aux_footage(std::slice::from_ref(&f.path)); + pool.set_aux_needs(&[(f.path.clone(), need.clone())]); + let img = pool.frame_at(&f, Tick::ZERO).unwrap(); + let aux = pool.aux_for(ItemId(1), &f, Tick::ZERO, &need).unwrap(); + let d = decodes_of(&path); + assert_eq!(d.len(), 1, "one decode: {d:?}"); + assert_eq!(chunks(&d[0]), SIZE.1, "each chunk read once"); + assert_eq!(d[0].channels.len(), 4 + 1 + 4, "the picture's, normal.R and the rank planes: {:?}", d[0].channels); + assert!(aux.get("normal.R").is_some() && aux.crypto_rank_planes("CryptoObject").len() == 2); + assert_eq!(bits(&img), bits(&image_crates(&bytes, &f))); +} + +/// The index and an in-memory source of `bytes`. +fn indexed(bytes: &[u8]) -> (Arc, std::io::Cursor>) { + let mut src = std::io::Cursor::new(bytes.to_vec()); + let ix = crate::exr_index::build(&mut src, FileStamp::Virtual).unwrap(); + (Arc::new(ix), src) +} + +/// #3271: a row range decompresses only the chunks holding those rows: with one scan line per +/// chunk (ZIPS) exactly those lines, with 16 (ZIP) the chunks around them; a reduced level +/// skips every other line on ZIPS. The rows read are the full read's, the rest is fill. +#[test] +fn rows_and_levels_skip_lines() { + for (compression, lines) in [(Compression::ZIP1, 10), (Compression::ZIP16, 32)] { + let bytes = write(vec![part(None, &RGBA, (32, 64), compression)], (32, 64)); + let (ix, mut src) = indexed(&bytes); + let all = ReadRequest::full(vec![0, 1, 2, 3]); + let (full, full_stats) = crate::exr_read::read_planes(&mut src, &ix, &all); + let full = full.unwrap(); + assert_eq!(full_stats.lines, 64); + let band = ReadRequest { rows: Some(10..20), ..all.clone() }; + let (got, stats) = crate::exr_read::read_planes(&mut src, &ix, &band); + let got = got.unwrap(); + assert_eq!(stats.lines, lines, "{compression:?}"); + for (g, f) in got.iter().zip(&full) { + for y in 0..64 { + let row = |p: &Vec| p[y * 32..(y + 1) * 32].to_vec(); + if (10..20).contains(&y) { + assert_eq!(row(g), row(f), "row {y}"); + } else { + assert!(row(g).iter().all(|v| *v == 0.0), "row {y} not read"); + } + } + } + } + // Half resolution on ZIPS: half the lines, every other row and column of the full read. + let bytes = write(vec![part(None, &RGBA, (32, 64), Compression::ZIP1)], (32, 64)); + let (ix, mut src) = indexed(&bytes); + let (full, _) = crate::exr_read::read_planes(&mut src, &ix, &ReadRequest::full(vec![3])); + let (half, stats) = crate::exr_read::read_planes(&mut src, &ix, &ReadRequest { level: 1, ..ReadRequest::full(vec![3]) }); + let (full, half) = (full.unwrap(), half.unwrap()); + assert_eq!(stats.lines, 32); + assert_eq!(crate::exr_read::level_size((32, 64), 1), (16, 32)); + for y in 0..32 { + for x in 0..16 { + assert_eq!(half[0][y * 16 + x].to_bits(), full[0][y * 2 * 32 + x * 2].to_bits(), "({x}, {y})"); + } + } +} + +/// #474: requests for a file at the same time decode it once; the others wait for that decode +/// and share its planes. +#[test] +fn concurrent_requests_decode_a_file_once() { + let bytes: Arc<[u8]> = single_part_zips().into(); + let path = "/3271-concurrent.exr"; + let source = ExrSource::Bytes(bytes.clone()); + let store = PlaneStore::new(CACHE_BUDGET); + let index = crate::exr_index::get(path, &source).unwrap(); + let barrier = std::sync::Barrier::new(8); + let got: Vec> = std::thread::scope(|s| { + let jobs: Vec<_> = (0..8) + .map(|_| { + s.spawn(|| { + barrier.wait(); + store.get(path, &source, &index, &Want { all: true, ids: (0..4).collect() }, Use::Other).unwrap() + }) + }) + .collect(); + jobs.into_iter().map(|j| j.join().unwrap()).collect() + }); + assert!(got.iter().all(|b| Arc::ptr_eq(b, &got[0])), "every caller has the same planes"); + assert_eq!(decodes_of(path).len(), 1, "one decode"); +} + +/// #3271: a request for channels a decode in progress doesn't read waits for it, then decodes +/// only what is still missing; the planes it gets hold both. +#[test] +fn a_request_not_covered_decodes_only_what_is_missing() { + let bytes: Arc<[u8]> = single_part_zips().into(); + let path = "/3271-follow-up.exr"; + let source = ExrSource::Bytes(bytes); + let store = PlaneStore::new(CACHE_BUDGET); + let index = crate::exr_index::get(path, &source).unwrap(); + let picture: BTreeSet = index.picture_ids().into_iter().collect(); + let normal: BTreeSet = index.ids_named(["normal.R", "normal.G"]).into_iter().collect(); + store.get(path, &source, &index, &Want { all: false, ids: picture.clone() }, Use::Other).unwrap(); + let b = store.get(path, &source, &index, &Want { all: false, ids: normal.clone() }, Use::Other).unwrap(); + let d = decodes_of(path); + assert_eq!(d.len(), 2); + assert_eq!(d[1].channels, ["normal.G", "normal.R"], "only the missing channels"); + assert!(picture.iter().chain(&normal).all(|id| b.plane(*id).is_some()), "both"); + // Covered now: no decode. + store.get(path, &source, &index, &Want { all: false, ids: picture }, Use::Other).unwrap(); + assert_eq!(decodes_of(path).len(), 2); +} + +/// #474: the store is bounded by bytes, least recently used out first; the newest file stays +/// even when it alone is over the budget, and unreadable files are remembered without bytes +/// (not read again) until forgotten. +#[test] +fn the_store_evicts_least_recently_used_by_bytes() { + let bytes: Arc<[u8]> = write(vec![part(None, &RGBA, (32, 32), Compression::ZIP1)], (32, 32)).into(); + let one = 4 * (32 * 32 * 4 + 1); + let store = PlaneStore::new(2 * one); + let all = Want { all: true, ids: (0..4).collect() }; + let get = |p: &str| { + let source = ExrSource::Bytes(bytes.clone()); + let index = crate::exr_index::get(p, &source).unwrap(); + store.get(p, &source, &index, &all, Use::Other).map(|_| ()) + }; + get("/3271-evict-a.exr").unwrap(); + get("/3271-evict-b.exr").unwrap(); + get("/3271-evict-a.exr").unwrap(); // a is now more recent than b + get("/3271-evict-c.exr").unwrap(); + assert_eq!(store.cached(), ["/3271-evict-a.exr", "/3271-evict-c.exr"], "b was least recently used"); + let small = PlaneStore::new(one / 2); + for p in ["/3271-evict-big.exr", "/3271-evict-big2.exr"] { + let source = ExrSource::Bytes(bytes.clone()); + let index = crate::exr_index::get(p, &source).unwrap(); + assert!(small.get(p, &source, &index, &all, Use::Other).is_ok()); + assert_eq!(small.cached(), [p], "the newest stays"); + } + // An unreadable file (its chunk table points past the end): remembered, not read again. + let mut broken = bytes.to_vec(); + broken.truncate(broken.len() - 64); + let source = ExrSource::Bytes(broken.into()); + let path = "/3271-evict-broken.exr"; + let index = crate::exr_index::get(path, &source).unwrap(); + assert!(store.get(path, &source, &index, &all, Use::Other).is_err()); + assert!(store.get(path, &source, &index, &all, Use::Other).is_err()); + assert_eq!(decodes_of(path).len(), 1, "not read again"); + store.forget(path); + assert!(!store.cached().contains(&path.to_string())); +} + +/// #3271 CI: a decode thread that is slow to finish its job after handing the planes over (a +/// busy machine) doesn't make them look in use: the store still drops the least recently used +/// file, not another one. +#[test] +fn a_decode_thread_finishing_late_does_not_pin_the_planes() { + let bytes: Arc<[u8]> = write(vec![part(None, &RGBA, (32, 32), Compression::ZIP1)], (32, 32)).into(); + let one = 4 * (32 * 32 * 4 + 1); + let store = PlaneStore::new(2 * one); + let all = Want { all: true, ids: (0..4).collect() }; + let get = |p: &str| { + let source = ExrSource::Bytes(bytes.clone()); + let index = crate::exr_index::get(p, &source).unwrap(); + store.get(p, &source, &index, &all, Use::Other).map(|_| ()) + }; + let (a, b, c) = ("/3271-late-a.exr", "/3271-late-b.exr", "/3271-late-c.exr"); + // b's decode thread stays in its job (at most 10 s) after it sent the planes. + let (go, wait) = std::sync::mpsc::channel::<()>(); + let wait = std::sync::Mutex::new(wait); + SENT.lock().unwrap().push(( + b.to_string(), + Arc::new(move |_: &str| { + let _ = wait.lock().unwrap().recv_timeout(std::time::Duration::from_secs(10)); + }), + )); + get(a).unwrap(); + get(b).unwrap(); + get(a).unwrap(); + get(c).unwrap(); + let cached = store.cached(); + let _ = go.send(()); + SENT.lock().unwrap().retain(|(p, _)| p != b); + assert_eq!(cached, [a, c], "b was least recently used"); +} + +/// #474 / #3191: a file forgotten (Reload Footage) while it decodes keeps nothing of that decode, +/// and the request asks again: no planes made before the reload are kept or served. +#[test] +fn a_file_forgotten_while_it_decodes_is_not_kept() { + let bytes: Arc<[u8]> = write(vec![part(None, &RGBA, (8, 8), Compression::ZIP1)], (8, 8)).into(); + let path = "/3271-forgotten.exr"; + let source = ExrSource::Bytes(bytes); + let store = Arc::new(PlaneStore::new(CACHE_BUDGET)); + let index = crate::exr_index::get(path, &source).unwrap(); + let forgot = Arc::new(AtomicU64::new(0)); + { + let (store, forgot) = (store.clone(), forgot.clone()); + set_before_read( + path, + Some(Arc::new(move |p: &str| { + if p == "/3271-forgotten.exr" && forgot.fetch_add(1, Ordering::SeqCst) == 0 { + store.forget(p); + } + })), + ); + } + let got = store.get(path, &source, &index, &Want { all: true, ids: (0..4).collect() }, Use::Other); + set_before_read(path, None); + assert!(got.is_ok()); + assert_eq!(decodes_of(path).len(), 2, "decoded again after the reload"); + assert_eq!(store.cached(), [path], "only the second decode is kept"); +} + +/// #3270 review (the pool's flights): a request made after a file was forgotten while its decode +/// is in flight doesn't join that decode (it would get the old file's planes): the flight lives +/// in the file's entry, which forget drops, so the request decodes the file anew at once. +#[test] +fn a_request_after_forget_does_not_join_the_old_decode() { + let bytes: Arc<[u8]> = write(vec![part(None, &RGBA, (8, 8), Compression::ZIP1)], (8, 8)).into(); + let path = "/3271-forget-join.exr"; + let source = ExrSource::Bytes(bytes); + let store = Arc::new(PlaneStore::new(CACHE_BUDGET)); + let index = crate::exr_index::get(path, &source).unwrap(); + let all = Want { all: true, ids: (0..4).collect() }; + let calls = Arc::new(AtomicU64::new(0)); + let (tx, rx) = std::sync::mpsc::channel(); + { + let (store, calls, source, index, all) = (store.clone(), calls.clone(), source.clone(), index.clone(), all.clone()); + let tx = std::sync::Mutex::new(Some(tx)); + set_before_read( + path, + Some(Arc::new(move |p: &str| { + if p != "/3271-forget-join.exr" || calls.fetch_add(1, Ordering::SeqCst) > 0 { + return; + } + // The old decode is in flight (this thread runs it): the file changes. + store.forget(p); + let (store, source, index, all) = (store.clone(), source.clone(), index.clone(), all.clone()); + let tx = tx.lock().unwrap().take(); + let asked = std::thread::spawn(move || store.get("/3271-forget-join.exr", &source, &index, &all, Use::Other).map(|_| ())); + // A request that joined the old decode would wait on this very thread. + let done = std::time::Instant::now() + std::time::Duration::from_secs(5); + while !asked.is_finished() && std::time::Instant::now() < done { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let finished = asked.is_finished(); + if let Some(tx) = tx { + let _ = tx.send((finished, if finished { asked.join().ok() } else { None })); + } + })), + ); + } + let got = store.get(path, &source, &index, &all, Use::Other); + set_before_read(path, None); + let (finished, asked) = rx.recv().unwrap(); + assert!(finished, "the request after forget decoded on its own, without waiting for the old decode"); + assert!(asked.is_some_and(|r| r.is_ok())); + assert!(got.is_ok()); + assert!(decodes_of(path).len() >= 2, "the file was decoded anew after forget"); +} + +/// #3270 review (CodeRabbit): forgetting one file leaves the decodes of other files alone: a +/// decode of file A in flight while file B is forgotten is still kept and joined (staleness is +/// per file, not one store-wide counter). +#[test] +fn forgetting_another_file_keeps_a_decode_in_flight() { + let bytes: Arc<[u8]> = write(vec![part(None, &RGBA, (8, 8), Compression::ZIP1)], (8, 8)).into(); + let (a, b) = ("/3271-forget-other-a.exr", "/3271-forget-other-b.exr"); + let store = Arc::new(PlaneStore::new(CACHE_BUDGET)); + let all = Want { all: true, ids: (0..4).collect() }; + let source = ExrSource::Bytes(bytes); + let index = crate::exr_index::get(a, &source).unwrap(); + // B is in the store first. + let index_b = crate::exr_index::get(b, &source).unwrap(); + store.get(b, &source, &index_b, &all, Use::Other).unwrap(); + let joiner = Arc::new(std::sync::Mutex::new(None)); + { + let (store, joiner, source, index, all) = (store.clone(), joiner.clone(), source.clone(), index.clone(), all.clone()); + let calls = AtomicU64::new(0); + set_before_read( + a, + Some(Arc::new(move |p: &str| { + if p != "/3271-forget-other-a.exr" || calls.fetch_add(1, Ordering::SeqCst) > 0 { + return; + } + // A's decode is in flight: B changes on disk, and another request asks for A. + store.forget("/3271-forget-other-b.exr"); + let (store, source, index, all) = (store.clone(), source.clone(), index.clone(), all.clone()); + *joiner.lock().unwrap() = + Some(std::thread::spawn(move || store.get("/3271-forget-other-a.exr", &source, &index, &all, Use::Other).map(|_| ()))); + })), + ); + } + let got = store.get(a, &source, &index, &all, Use::Other); + set_before_read(a, None); + assert!(got.is_ok()); + let joined = joiner.lock().unwrap().take().unwrap().join().unwrap(); + assert!(joined.is_ok()); + assert_eq!(decodes_of(a).len(), 1, "the other request joined A's decode (or found it kept)"); + assert_eq!(store.cached(), [a], "A's decode is kept, B is forgotten"); +} + +/// #474: the planes of a picture whose effects read the footage's channels are kept for them +/// (the renderer asks for the picture, then the channels) until the channels are asked for. +#[test] +fn a_pictures_planes_are_held_for_its_effects() { + let bytes: Arc<[u8]> = single_part_zips().into(); + let path = "/3271-held.exr"; + let source = ExrSource::Bytes(bytes); + let store = PlaneStore::new(1); + let index = crate::exr_index::get(path, &source).unwrap(); + let all = Want { all: true, ids: (0..4).collect() }; + drop(store.get(path, &source, &index, &all, Use::Picture).unwrap()); + assert!(store.is_held(path)); + drop(store.get(path, &source, &index, &all, Use::Other).unwrap()); + assert!(!store.is_held(path), "the channels were asked for"); + assert_eq!(decodes_of(path).len(), 1); +} + +/// #474: footage the project says effects read the channels of decodes once from its first frame +/// (the picture with the channels). Learned only when `aux()` first asks, the picture was read +/// alone before, and the channels then read only what it didn't. +#[test] +fn given_aux_footage_decodes_once_from_the_first_frame() { + use crate::exr_channels::take_decodes; + let bytes: Arc<[u8]> = single_part_zips().into(); + let (given, learned) = ("/3271-given.exr", "/3271-learned.exr"); + let pool = crate::MediaPool::new(); + let mut f = std::collections::HashMap::new(); + for p in [given, learned] { + pool.add_bytes(p, bytes.clone()); + f.insert(p, crate::probe_bytes(p, bytes.clone()).unwrap()); + } + pool.set_aux_footage(&[given.to_string()]); + take_decodes(); + pool.frame_at(&f[given], Tick::ZERO).unwrap(); + assert!(pool.aux_for(ItemId(1), &f[given], Tick::ZERO, &AuxNeed::All).unwrap().get("diffuse.R").is_some()); + assert_eq!(take_decodes(), [0, 1], "the picture and the channels share one decode"); + pool.frame_at(&f[learned], Tick::ZERO).unwrap(); + pool.aux_for(ItemId(2), &f[learned], Tick::ZERO, &AuxNeed::All).unwrap(); + assert_eq!(take_decodes(), [0, 2]); + let d = decodes_of(learned); + assert_eq!(d[0].channels.len(), 4, "the picture alone"); + assert_eq!(d[1].channels.len(), crate::exr_index::cached(learned).unwrap().aux_ids().len(), "all but the picture: a picture read alone isn't kept twice"); +} + +/// #474: the picture made of the planes of a file with exact R, G, B channels is the `image` +/// crate's, bit for bit (first such part, alpha or opaque, data window placed with 0 around it), +/// in every alpha interpretation and float curve. +#[test] +fn picture_from_planes_is_the_image_crates() { + use effectcraft_project::AlphaMode; + let display = (5usize, 4usize); + let files = [ + write(vec![part(None, &[("R", true), ("G", true), ("B", true), ("A", false), ("Z", false)], display, Compression::ZIP16)], display), + write(vec![part(None, &[("R", false), ("G", false), ("B", false), ("Image.R", true)], display, Compression::RLE)], display), + write( + vec![ + part(Some("diffuse"), &[("R", true), ("G", true), ("B", true)], display, Compression::ZIP1), + part(Some("beauty"), &RGBA, display, Compression::PIZ), + ], + display, + ), + ]; + for (k, bytes) in files.iter().enumerate() { + let path = format!("/3271-planes-{k}.exr"); + let source = ExrSource::Bytes(bytes.as_slice().into()); + assert!(crate::exr_index::get(&path, &source).unwrap().picture.is_some(), "file {k}"); + let img = crate::probe::load_oriented(bytes, Some(image::ImageFormat::OpenExr)).unwrap(); + for alpha in [AlphaMode::Straight, AlphaMode::Premultiplied, AlphaMode::Ignore] { + for curve in [FloatCurve::Srgb, FloatCurve::Linear, FloatCurve::Gamma24] { + let op = AlphaOp::of(&Footage { alpha, premul_color: [0.2, 0.4, 0.6], ..Default::default() }, curve); + let want = crate::convert::dynamic_to_image(&img, op); + let Picture::Done(Ok(got)) = picture(&path, &source, op, None) else { panic!("file {k}: a picture") }; + assert_eq!(bits(&got), bits(&want), "file {k} {alpha:?} {curve:?}"); + } + } + } +} + +/// #474 / #3271: a decode that stops (a panic, on the decode threads or on the thread asking) +/// leaves nothing behind: the entry isn't "decoding" or "unreadable", the next request decodes. +#[test] +fn a_decode_that_panics_is_not_left_in_the_store() { + let bytes: Arc<[u8]> = write(vec![part(None, &RGBA, (8, 8), Compression::ZIP1)], (8, 8)).into(); + let all = Want { all: true, ids: (0..4).collect() }; + for (k, inline) in [false, true].into_iter().enumerate() { + let path = format!("/3271-panics-{k}.exr"); + let source = ExrSource::Bytes(bytes.clone()); + let store = PlaneStore::new(CACHE_BUDGET); + let index = crate::exr_index::get(&path, &source).unwrap(); + let panicked = Arc::new(AtomicU64::new(0)); + { + let (watch, panicked) = (path.clone(), panicked.clone()); + set_before_read( + &path, + Some(Arc::new(move |p: &str| { + if p == watch && panicked.fetch_add(1, Ordering::SeqCst) == 0 { + panic!("a decoder bug"); + } + })), + ); + } + let ask = || store.get(&path, &source, &index, &all, Use::Other); + if inline { + // On a decode thread the decode runs right there, and the panic comes through. + let threads = crate::pool::decode_threads().unwrap(); + let r = threads.install(|| std::panic::catch_unwind(std::panic::AssertUnwindSafe(ask))); + assert!(r.is_err(), "the panic came through"); + assert!(store.cached().is_empty(), "nothing left"); + assert!(ask().is_ok(), "decodes again"); + } else { + // Handed to the decode threads: the request asks again by itself. + assert!(ask().is_ok()); + } + set_before_read(&path, None); + assert_eq!(panicked.load(Ordering::SeqCst), 2, "inline: {inline}"); + assert_eq!(store.cached(), std::slice::from_ref(&path)); + } +} + +/// #474: a file counts as used when its decode finishes: one asked for first but decoded after +/// another is the newer of the two, so concurrent frames don't evict each other's files before +/// their effects read them. +#[test] +fn a_file_is_used_as_of_its_decode() { + let bytes: Arc<[u8]> = write(vec![part(None, &RGBA, (32, 32), Compression::ZIP1)], (32, 32)).into(); + let one = 4 * (32 * 32 * 4 + 1); + let store = Arc::new(PlaneStore::new(2 * one)); + let all = Want { all: true, ids: (0..4).collect() }; + let get = { + let (store, bytes, all) = (store.clone(), bytes.clone(), all.clone()); + move |p: &str| { + let source = ExrSource::Bytes(bytes.clone()); + let index = crate::exr_index::get(p, &source).unwrap(); + store.get(p, &source, &index, &all, Use::Other).map(|_| ()) + } + }; + { + let get = get.clone(); + let nested = Arc::new(AtomicU64::new(0)); + set_before_read( + "/3271-used-first.exr", + Some(Arc::new(move |p: &str| { + // Another frame's file is asked for and decoded while this one decodes. + if p == "/3271-used-first.exr" && nested.fetch_add(1, Ordering::SeqCst) == 0 { + get("/3271-used-second.exr").unwrap(); + } + })), + ); + } + get("/3271-used-first.exr").unwrap(); + set_before_read("/3271-used-first.exr", None); + get("/3271-used-third.exr").unwrap(); + assert_eq!(store.cached(), ["/3271-used-first.exr", "/3271-used-third.exr"], "the file decoded first went first"); +} + +/// #474: frames rendered at once (each asks for its picture, then its effects for the channels +/// while other frames decode) decode each file once, though the budget holds only one: a +/// picture's planes are kept for its effects, and planes in use are never dropped. +#[test] +fn concurrent_frames_decode_each_file_once() { + let rgbz = [("R", false), ("G", false), ("B", false), ("Z", false)]; + let bytes: Arc<[u8]> = write(vec![part(None, &rgbz, (64, 64), Compression::ZIP1)], (64, 64)).into(); + let store = PlaneStore::new(4 * (64 * 64 * 4 + 1)); + let all = Want { all: true, ids: (0..4).collect() }; + let (next, frames) = (std::sync::atomic::AtomicUsize::new(0), 24); + std::thread::scope(|s| { + for _ in 0..4 { + s.spawn(|| { + loop { + let i = next.fetch_add(1, Ordering::Relaxed); + if i >= frames { + break; + } + let path = format!("/3271-frames/{i:04}.exr"); + let source = ExrSource::Bytes(bytes.clone()); + let index = crate::exr_index::get(&path, &source).unwrap(); + drop(store.get(&path, &source, &index, &all, Use::Picture).unwrap()); + std::thread::sleep(std::time::Duration::from_millis(3)); + let b = store.get(&path, &source, &index, &all, Use::Other).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(2)); + assert_eq!(b.aux.get("Z").and_then(|z| z.first()).copied(), Some(value(0, 3, false))); + } + }); + } + }); + for i in 0..frames { + assert_eq!(decodes_of(&format!("/3271-frames/{i:04}.exr")).len(), 1, "frame {i}: one decode"); + } +} + +/// #474: once the project no longer names footage (its effect removed), later frames decode +/// only their picture's channels again; what `aux()` learned is dropped with each new set too. +#[test] +fn a_new_aux_footage_set_returns_to_picture_only() { + let bytes: Arc<[u8]> = single_part_zips().into(); + let paths: Vec = (1..=4).map(|i| format!("/3271-unset_{i:04}.exr")).collect(); + let pool = crate::MediaPool::new(); + for p in &paths { + pool.add_bytes(p, bytes.clone()); + } + let mut f = crate::probe_bytes(&paths[0], bytes.clone()).unwrap(); + f.kind = effectcraft_project::FootageKind::Sequence; + f.sequence = paths.clone(); + let at = |i: i64| f.frame_rate.tick_of(i); + let all = crate::exr_index::get(&paths[0], &ExrSource::Bytes(bytes.clone())).unwrap().channels.len(); + // The channels the frame's decode read. + let frame = |i: usize| { + pool.frame_at(&f, at(i as i64)).unwrap(); + decodes_of(&paths[i]).first().map(|d| d.channels.len()) + }; + pool.set_aux_footage(std::slice::from_ref(&f.path)); + assert_eq!(frame(0), Some(all), "given: the picture with the channels"); + pool.set_aux_footage(&[]); + assert!(!shared().is_held(&paths[0]), "no longer kept once no effect reads it"); + assert_eq!(frame(1), Some(4), "no longer given: the picture alone"); + // Learned by `aux_for()`, then a new set without it: picture only again. + pool.aux_for(ItemId(1), &f, at(1), &AuxNeed::All).unwrap(); + assert_eq!(frame(2), Some(all), "learned"); + pool.set_aux_footage(&[]); + assert_eq!(frame(3), Some(4), "a new set drops what was learned"); +} + +/// [`part`] with its data window at `pos`. +fn part_at(name: Option<&str>, channels: &[(&str, bool)], size: (usize, usize), pos: (i32, i32), compression: Compression) -> Layer> { + let mut p = part(name, channels, size, compression); + p.attributes.layer_position = exr::prelude::Vec2(pos.0, pos.1); + p +} + +/// The bytes of a file of `parts` over the display window `display`. +fn write_in(parts: Vec>>, display: IntegerBounds) -> Vec { + let image = exr::prelude::Image::from_layers(ImageAttributes::new(display), parts); + let mut bytes = std::io::Cursor::new(Vec::new()); + image.write().non_parallel().to_buffered(&mut bytes).unwrap(); + bytes.into_inner() +} + +/// #474 review: data windows placed inside and around the display window make the `image` +/// crate's picture too. +#[test] +fn picture_from_planes_with_data_window_offsets_is_the_image_crates() { + let display = IntegerBounds::new((1, -1), (5, 4)); + let files = [ + write_in(vec![part_at(None, &[("R", true), ("G", true), ("B", true), ("A", false), ("Z", false)], (5, 4), (1, -1), Compression::ZIP16)], display), + write_in(vec![part_at(None, &[("R", false), ("G", false), ("B", false), ("Image.R", true)], (3, 2), (0, 0), Compression::RLE)], display), + write_in( + vec![ + part_at(Some("diffuse"), &[("R", true), ("G", true), ("B", true)], (5, 4), (1, -1), Compression::ZIP1), + part_at(Some("beauty"), &RGBA, (2, 2), (2, 0), Compression::PIZ), + ], + display, + ), + ]; + for (k, bytes) in files.iter().enumerate() { + let path = format!("/3271-offsets-{k}.exr"); + let source = ExrSource::Bytes(bytes.as_slice().into()); + assert!(crate::exr_index::get(&path, &source).unwrap().picture.is_some(), "file {k}"); + let f = Footage::default(); + let Picture::Done(Ok(got)) = picture(&path, &source, AlphaOp::of(&f, FloatCurve::Linear), None) else { panic!("file {k}: a picture") }; + let img = crate::probe::load_oriented(bytes, Some(image::ImageFormat::OpenExr)).unwrap(); + assert_eq!(bits(&got), bits(&crate::convert::dynamic_to_image(&img, AlphaOp::of(&f, FloatCurve::Linear))), "file {k}"); + } +} + +/// #3271 review: a request that failed (a broken part) doesn't hide what the store holds, nor +/// fail smaller requests: the picture read before is served, and read again when asked alone. +#[test] +fn a_failed_request_fails_only_requests_as_large() { + let mut bytes = multipart(); + // The depth part is last: its chunks now point past the end of the file. + bytes.truncate(bytes.len() - 200); + let path = "/3271-broken-part.exr"; + let source = ExrSource::Bytes(bytes.into()); + let store = PlaneStore::new(CACHE_BUDGET); + let index = crate::exr_index::get(path, &source).unwrap(); + let picture = Want { all: false, ids: index.picture_ids().into_iter().collect() }; + let all = Want { all: true, ids: (0..4).collect() }; + let held = store.get(path, &source, &index, &picture, Use::Picture).unwrap(); + assert_eq!(store.get(path, &source, &index, &all, Use::Other).err(), Some(Refused::Unreadable)); + assert!(Arc::ptr_eq(&store.get(path, &source, &index, &picture, Use::Other).unwrap(), &held), "served from the store"); + assert_eq!(store.get(path, &source, &index, &all, Use::Other).err(), Some(Refused::Unreadable), "remembered"); + assert_eq!(decodes_of(path).len(), 2); + // Another store: the picture alone after the failure decodes. + let other = PlaneStore::new(CACHE_BUDGET); + assert!(other.get(path, &source, &index, &all, Use::Other).is_err()); + assert!(other.get(path, &source, &index, &picture, Use::Other).is_ok(), "a smaller request isn't refused"); +} + +/// #3271 review: when the picture with the channels its effects read is more than one file may +/// allocate, the picture is read alone instead of failing. +#[test] +fn a_picture_too_large_with_its_channels_is_read_alone() { + let bytes: Arc<[u8]> = single_part_zips().into(); + let path = "/3271-too-large-with-aux.exr"; + let pool = crate::MediaPool::new(); + pool.add_bytes(path, bytes.clone()); + let f = crate::probe_bytes(path, bytes.clone()).unwrap(); + // Room for the picture's 4 planes, not for all of them. + set_cap(path, 5 * SIZE.0 * SIZE.1 * 4); + pool.set_aux_footage(&[path.to_string()]); + let img = pool.frame_at(&f, Tick::ZERO).unwrap(); + assert_eq!(bits(&img), bits(&image_crates(&bytes, &f))); + let d = decodes_of(path); + assert_eq!(d.last().map(|d| d.channels.len()), Some(4), "{d:?}"); +} + +/// #3750 review: two requests that each fit under the read's limit, merged into one decode that +/// doesn't, each get their planes: a refusal for the merged size is not handed to a request +/// whose own planes fit (they are read again for it alone). +#[test] +fn a_merged_decode_too_large_leaves_each_request_that_fits_its_planes() { + let bytes: Arc<[u8]> = single_part_zips().into(); + let path = "/3750-merged-too-large.exr"; + let source = ExrSource::Bytes(bytes); + let store = Arc::new(PlaneStore::new(CACHE_BUDGET)); + let index = crate::exr_index::get(path, &source).unwrap(); + let picture: BTreeSet = index.picture_ids().into_iter().collect(); + let first = Want { all: false, ids: picture.clone() }; + // (10 passes: with the picture's 4 planes 14, over the limit of 12) + let passes: BTreeSet = (0..index.channels.len()).filter(|i| !picture.contains(i)).take(10).collect(); + let second = Want { all: false, ids: passes.clone() }; + set_cap(path, 12 * SIZE.0 * SIZE.1 * 4); + // Before the first request's decode reads: the second request joins it. + let (tx, rx) = std::sync::mpsc::channel(); + let joined = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let merged_seen = Arc::new(std::sync::atomic::AtomicBool::new(false)); + { + let (store, source, index, second, joined, merged_seen) = + (store.clone(), source.clone(), index.clone(), second.clone(), joined.clone(), merged_seen.clone()); + let hook: Hook = Arc::new(move |_: &str| { + if joined.swap(true, Ordering::SeqCst) { + return; + } + let (s, src, idx, want, tx) = (store.clone(), source.clone(), index.clone(), second.clone(), tx.clone()); + std::thread::spawn(move || { + let _ = tx.send(s.get(path, &src, &idx, &want, Use::Other).map(|b| b.ids.clone())); + }); + let until = std::time::Instant::now() + std::time::Duration::from_secs(10); + while std::time::Instant::now() < until { + let merged = store + .lock() + .entries + .iter() + .find(|e| e.path == path) + .and_then(|e| e.flight.clone()) + .is_some_and(|f| second.ids.iter().all(|id| f.state().want.ids.contains(id))); + if merged { + merged_seen.store(true, Ordering::SeqCst); + break; + } + std::thread::sleep(std::time::Duration::from_millis(2)); + } + }); + set_before_read(path, Some(hook)); + } + let got_first = store.get(path, &source, &index, &first, Use::Other).map(|b| b.ids.clone()); + let got_second = rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap(); + set_before_read(path, None); + assert!(joined.load(Ordering::SeqCst)); + assert!(merged_seen.load(Ordering::SeqCst), "the second request joined the first one's decode"); + let got_first = got_first.expect("the picture alone fits"); + let got_second = got_second.expect("the passes alone fit"); + assert!(picture.iter().all(|id| got_first.contains(id)), "{got_first:?}"); + assert!(passes.iter().all(|id| got_second.contains(id)), "{got_second:?}"); +} + +/// #474: at most CACHE_FILES entries are kept, however small. +#[test] +fn the_store_keeps_a_bounded_number_of_files() { + let bytes: Arc<[u8]> = write(vec![part(None, &[("R", true)], (2, 2), Compression::ZIP1)], (2, 2)).into(); + let store = PlaneStore::new(CACHE_BUDGET); + let all = Want { all: true, ids: (0..4).collect() }; + for i in 0..CACHE_FILES + 10 { + let path = format!("/3271-many/{i}.exr"); + let source = ExrSource::Bytes(bytes.clone()); + let index = crate::exr_index::get(&path, &source).unwrap(); + store.get(&path, &source, &index, &all, Use::Other).unwrap(); + } + assert!(store.cached().len() <= CACHE_FILES); +} + +/// `bytes` with the data window's right edge (`xMax`) moved to `x_max`. +fn with_data_window_x_max(mut bytes: Vec, x_max: i32) -> Vec { + let tag = b"dataWindow\0box2i\0\x10\0\0\0"; + let at = bytes.windows(tag.len()).position(|w| w == tag).unwrap() + tag.len() + 8; + bytes[at..at + 4].copy_from_slice(&x_max.to_le_bytes()); + bytes +} + +/// #3271 review (never crash): a tiny file whose data window is a billion pixels wide over one +/// chunk made the decompressor reserve gigabytes for a block (an abort, not an error). Every +/// way in refuses it with an error: import, the picture, the channels, the names. +#[test] +fn a_hostile_data_window_is_refused_not_allocated() { + for compression in [Compression::PIZ, Compression::ZIP1, Compression::B44] { + let small = write(vec![part(None, &[("R", true)], (1, 1), compression)], (1, 1)); + let bytes = with_data_window_x_max(small, (1 << 30) - 3); + let path = format!("/3271-hostile-{compression:?}.exr"); + assert!(!crate::exr_index::safe_to_decode(&bytes)); + assert!(crate::exr_index::build(&mut std::io::Cursor::new(bytes.as_slice()), FileStamp::Virtual).is_err()); + assert!(crate::exr_channels::read_exr_channels(&bytes).is_none()); + assert!(crate::exr_channels::picture_image(&bytes).is_none()); + let b: Arc<[u8]> = bytes.into(); + assert!(crate::probe_bytes(&path, b.clone()).is_err(), "import refuses it"); + let pool = crate::MediaPool::new(); + pool.add_bytes(&path, b); + let f = Footage { path: path.clone(), kind: effectcraft_project::FootageKind::Still, has_video: true, width: 1, height: 1, ..Default::default() }; + assert!(pool.frame_at(&f, Tick::ZERO).is_err()); + assert!(pool.aux(ItemId(1), &f, Tick::ZERO).is_none()); + assert!(pool.aux_names(ItemId(1), &f, Tick::ZERO).is_none()); + } +} + +/// #3271 review (never crash): damaged files (bytes changed in the offset table, the chunk +/// headers or the pixels) read as an error or as some pixels, never a panic. +#[test] +fn damaged_files_never_panic() { + let files = [single_part_zips(), multipart(), write(vec![part(None, &RGBA, (16, 40), Compression::PIZ)], (16, 40))]; + for good in &files { + // (the good file indexes and reads whole through the same path) + let (ix, mut src) = indexed(good); + let all = ReadRequest::full((0..ix.channels.len()).collect()); + assert!(crate::exr_read::read_planes(&mut src, &ix, &all).0.is_ok()); + assert!(crate::exr_channels::read_exr_channels(good).is_some()); + let start = chunk_table(good).iter().flatten().map(|(at, _)| *at).min().unwrap() as usize; + // From a little before the chunks (the offset tables) to the end, in steps. + let from = start.saturating_sub(64); + let (mut reads, mut read_ok) = (0, 0); + for (i, at) in (from..good.len()).step_by(((good.len() - from) / 150).max(1)).enumerate() { + let mut bad = good.clone(); + bad[at] ^= [0xff, 0x80, 0x01, 0x7f][i % 4]; + let _ = crate::exr_channels::read_exr_channels(&bad); + let _ = crate::exr_channels::picture_image(&bad); + let mut src = std::io::Cursor::new(bad.as_slice()); + if let Ok(ix) = crate::exr_index::build(&mut src, FileStamp::Virtual) { + let req = ReadRequest { rows: Some(3..9), level: 1, ..ReadRequest::full((0..ix.channels.len()).collect()) }; + reads += 1; + read_ok += usize::from(crate::exr_read::read_planes(&mut src, &ix, &req).0.is_ok()); + } + } + // Most damage lies in the chunks: the index stands and the reader meets the damage. + assert!(reads > 50 && read_ok > 0, "{reads} damaged files indexed, {read_ok} read"); + } +} + +/// #3271 review (never crash): damaged headers are refused before a decoder sees them +/// ([`crate::exr_index::safe_to_decode`] guards the `image` crate's decoder), and so is a part +/// larger than this reader takes; a file the reader doesn't cover but whose headers are sound +/// (HTJ2K) is left to the decoders to report. +#[test] +fn damaged_headers_are_not_safe_to_decode() { + let good = write(vec![part(None, &RGBA, (8, 8), Compression::ZIP1)], (8, 8)); + assert!(crate::exr_index::safe_to_decode(&good)); + // Cut inside the headers. + let cut = good.windows(11).position(|w| w == b"compression").unwrap(); + assert!(!crate::exr_index::safe_to_decode(&good[..cut]), "headers cut short"); + // Not an OpenEXR file. + let mut magic = good.clone(); + magic[0] ^= 0xff; + assert!(!crate::exr_index::safe_to_decode(&magic), "no signature"); + // Offset tables longer than the file. + let first_chunk = chunk_table(&good)[0][0].0 as usize; + assert!(!crate::exr_index::safe_to_decode(&good[..first_chunk - 8]), "tables cut short"); + assert!(!crate::exr_index::safe_to_decode(&with_data_window_x_max(good.clone(), (1 << 30) - 3)), "a part too large"); + // HTJ2K (compression 11): sound headers, left to the decoders. + let mut htj2k = good.clone(); + let tag = b"compression\0compression\0\x01\0\0\0"; + let at = htj2k.windows(tag.len()).position(|w| w == tag).unwrap() + tag.len(); + htj2k[at] = 11; + assert_eq!( + crate::exr_index::build(&mut std::io::Cursor::new(htj2k.as_slice()), FileStamp::Virtual).err(), + Some(crate::exr_index::IndexError::Unsupported(crate::exr_index::HTJ2K)) + ); + assert!(crate::exr_index::safe_to_decode(&htj2k)); +} + +/// #3271 review (never crash): the headers are read leniently, so a channel list the `exr` +/// crate's validation refused (a zero sampling factor, which its decompressors divide by, or +/// channels out of order) is refused when indexing, before any chunk is decompressed. +#[test] +fn an_invalid_channel_list_is_refused() { + let good = write(vec![part(None, &[("G", true), ("R", true)], (4, 4), Compression::ZIP1)], (4, 4)); + let tag = b"channels\0chlist\0"; + let list = good.windows(tag.len()).position(|w| w == tag).unwrap() + tag.len() + 4; + // Each entry: name, NUL, pixel type (4), linear (1), reserved (3), x and y sampling (4 + 4). + let mut zero = good.clone(); + let x_sampling = list + 2 + 4 + 1 + 3; + zero[x_sampling..x_sampling + 4].copy_from_slice(&0i32.to_le_bytes()); + let mut swapped = good.clone(); + swapped[list] = b'R'; + swapped[list + 2 + 16] = b'G'; + assert!(crate::exr_index::build(&mut std::io::Cursor::new(good.as_slice()), FileStamp::Virtual).is_ok()); + for bad in [zero, swapped] { + assert!(crate::exr_index::build(&mut std::io::Cursor::new(bad.as_slice()), FileStamp::Virtual).is_err()); + assert!(crate::exr_channels::read_exr_channels(&bad).is_none()); + assert!(crate::exr_channels::picture_image(&bad).is_none()); + } +} + +/// #3271 review: rows and levels on every compression: the rows read are the full read's, +/// whole chunks are decompressed (1, 16, 32 or 256 lines), and a level is the full read's +/// every other row and column. +#[test] +fn rows_and_levels_on_every_compression() { + let cases = [ + (Compression::Uncompressed, 1), + (Compression::RLE, 1), + (Compression::ZIP1, 1), + (Compression::ZIP16, 16), + (Compression::PXR24, 16), + (Compression::PIZ, 32), + (Compression::B44, 32), + (Compression::DWAA(None), 32), + (Compression::DWAB(None), 256), + ]; + for (compression, per_chunk) in cases { + let bytes = write(vec![part(None, &RGBA, (32, 64), compression)], (32, 64)); + let (ix, mut src) = indexed(&bytes); + let all = ReadRequest::full(vec![0, 1, 2, 3]); + let full = crate::exr_read::read_planes(&mut src, &ix, &all).0.unwrap(); + let (band, stats) = crate::exr_read::read_planes(&mut src, &ix, &ReadRequest { rows: Some(10..20), ..all.clone() }); + let band = band.unwrap(); + // The chunks holding rows 10..20, each `per_chunk` lines (the last one shorter). + let lines: usize = (0..64usize).step_by(per_chunk).filter(|y0| *y0 < 20 && y0 + per_chunk > 10).map(|y0| per_chunk.min(64 - y0)).sum(); + assert_eq!(stats.lines, lines, "{compression:?}"); + for (b, f) in band.iter().zip(&full) { + assert_eq!( + b[10 * 32..20 * 32].iter().map(|v| v.to_bits()).collect::>(), + f[10 * 32..20 * 32].iter().map(|v| v.to_bits()).collect::>(), + "{compression:?}" + ); + } + let (half, _) = crate::exr_read::read_planes(&mut src, &ix, &ReadRequest { level: 1, ..all.clone() }); + let half = half.unwrap(); + for y in 0..32 { + for x in 0..16 { + assert_eq!(half[0][y * 16 + x].to_bits(), full[0][y * 2 * 32 + x * 2].to_bits(), "{compression:?} ({x}, {y})"); + } + } + } + // Tiles: rows read as in the full read. + let mut tiled = part(None, &RGBA, (32, 64), Compression::ZIP16); + tiled.encoding.blocks = Blocks::Tiles(exr::prelude::Vec2(16, 16)); + let bytes = write(vec![tiled], (32, 64)); + let (ix, mut src) = indexed(&bytes); + let all = ReadRequest::full(vec![0, 1, 2, 3]); + let full = crate::exr_read::read_planes(&mut src, &ix, &all).0.unwrap(); + let (band, stats) = crate::exr_read::read_planes(&mut src, &ix, &ReadRequest { rows: Some(10..20), ..all.clone() }); + assert_eq!(stats.chunks, [4], "two rows of two tiles"); + assert_eq!(band.unwrap()[0][10 * 32..20 * 32], full[0][10 * 32..20 * 32]); +} + +/// #3271: a new frame of an OpenEXR on disk opens its file once: indexing it and decoding the +/// picture share the open file. +#[test] +fn a_new_frame_opens_its_file_once() { + let dir = std::env::temp_dir().join(format!("ec-3271-open-once-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("plate_0001.exr"); + std::fs::write(&file, multipart()).unwrap(); + let f = crate::probe(&file).unwrap(); + let before = crate::opens_under(&dir); + let pool = crate::MediaPool::new(); + pool.frame_at(&f, Tick::ZERO).unwrap(); + assert_eq!(crate::opens_under(&dir) - before, 1, "one open for the index and the decode"); + assert_eq!(decodes_of(&f.path).len(), 1); + let _ = std::fs::remove_dir_all(&dir); +} + +/// #3271: decoded channels are kept in the disk cache, one entry per channel: once RAM has let +/// them go they are read back from there, bit for bit (Cryptomatte IDs included), whatever was +/// asked for before (the picture first, then the channels, then all of it after an eviction); +/// Reload Footage drops them. +/// The tests that set the process-wide disk cache take turns (one would switch off another's). +static DISK_TESTS: Mutex<()> = Mutex::new(()); + +#[test] +fn decoded_planes_are_kept_on_disk_and_read_back_exactly() { + let _disk = DISK_TESTS.lock().unwrap_or_else(PoisonError::into_inner); + use effectcraft_render::disk_cache::{DiskCache, Kind}; + let dir = std::env::temp_dir().join(format!("ec-3271-disk-planes-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("crypto_0001.exr"); + std::fs::write(&file, multipart()).unwrap(); + let dc = DiskCache::open(dir.join("cache"), 1 << 30).unwrap(); + // (every decode is written, however quick: not decided by this machine's speed) + dc.set_read_us_per_mb(0); + // (only this test's files use it) + use_disk_for(&dir.to_string_lossy()); + set_disk_cache(Some(&dc)); + let f = crate::probe(&file).unwrap(); + let pool = crate::MediaPool::new(); + // The picture first, then every channel: 4, then the other 5 read from the file. + pool.frame_at(&f, Tick::ZERO).unwrap(); + let first = pool.aux(ItemId(1), &f, Tick::ZERO).unwrap(); + dc.flush(); + assert_eq!(dc.keys(Kind::Plane).len(), 9, "one entry per channel: {:?}", dc.stats()); + // RAM lets go: all of it again comes from disk, without reading the file. + pool.forget(&f.path); + let again = pool.aux(ItemId(1), &f, Tick::ZERO).unwrap(); + let bits = |a: &AuxChannels| a.channels.iter().map(|(n, p)| (n.clone(), p.iter().map(|v| v.to_bits()).collect::>())).collect::>(); + assert_eq!(bits(&again), bits(&first), "bit for bit"); + // Reload Footage: the entries go, the file is decoded again. + dc.drop_files([f.path.clone()]); + dc.flush(); + pool.forget(&f.path); + pool.aux(ItemId(1), &f, Tick::ZERO).unwrap(); + // #3750 review: a disk cache too small for one plane gets no copies of the planes at all. + dc.flush(); + dc.set_max_bytes(1024); + let small = dir.join("crypto_0002.exr"); + std::fs::write(&small, multipart()).unwrap(); + let g = crate::probe(&small).unwrap(); + pool.aux(ItemId(2), &g, Tick::ZERO).unwrap(); + set_disk_cache(None); + let copies = DISK_COPIES.lock().unwrap().iter().filter(|p| **p == g.path).count(); + assert_eq!(copies, 0, "no plane copied for a cache it can't go in"); + assert!(DISK_COPIES.lock().unwrap().contains(&f.path), "copied while it could"); + let from_disk: Vec = decodes_of(&f.path).iter().map(|d| d.from_disk).collect(); + assert_eq!(from_disk, [false, false, true, false]); + let _ = std::fs::remove_dir_all(&dir); +} + +/// #3271: a decode thread asking for planes whose decode is still queued on the decode threads +/// (an aux request on a frame worker queued it, then the picture's decode asks) takes it over +/// instead of decoding a copy: one decode, and both requests get its planes. The queued job is +/// held back until the claim (a hook), so the order is the same every time. +#[test] +fn a_decode_thread_takes_over_a_queued_decode() { + let bytes: Arc<[u8]> = single_part_zips().into(); + let path = "/3271-claimed.exr"; + let source = ExrSource::Bytes(bytes); + let store = Arc::new(PlaneStore::new(CACHE_BUDGET)); + let index = crate::exr_index::get(path, &source).unwrap(); + let all = Want { all: true, ids: (0..4).collect() }; + let threads = crate::pool::decode_threads().unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + // When the asker queues its decode: a decode thread asks for the same planes. + { + let (store, source, index, all, tx) = (store.clone(), source.clone(), index.clone(), all.clone(), tx.clone()); + let hook: Hook = Arc::new(move |_: &str| { + let (store, source, index, all, tx) = (store.clone(), source.clone(), index.clone(), all.clone(), tx.clone()); + threads.spawn(move || { + let _ = tx.send(store.get(path, &source, &index, &all, Use::Other).map(|b| b.ids.len())); + }); + }); + QUEUING.lock().unwrap().push((path.to_string(), hook)); + } + // The queued job waits until that decode thread claimed it. + let hold: Hook = Arc::new(|p: &str| { + let claims = CLAIMS.lock().unwrap(); + let _ = CLAIM_SIGNAL.wait_timeout_while(claims, std::time::Duration::from_secs(10), |c| !c.iter().any(|c| c == p)); + }); + STARTING.lock().unwrap().push((path.to_string(), hold)); + let asked = store.get(path, &source, &index, &all, Use::Other).map(|b| b.ids.len()); + let claimed = rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap(); + QUEUING.lock().unwrap().retain(|(p, _)| p != path); + STARTING.lock().unwrap().retain(|(p, _)| p != path); + assert!(CLAIMS.lock().unwrap().iter().any(|p| p == path), "claimed"); + assert!(asked.is_ok() && claimed == asked, "{claimed:?} {asked:?}"); + assert_eq!(decodes_of(path).len(), 1, "decoded once"); +} + +/// #3271: the plane store in the common memory budget: trimmed least recently used first, +/// never the planes a picture holds for its effects or planes still in use. +#[test] +fn the_plane_store_is_trimmed_by_the_accountant() { + use effectcraft_render::memory::{Accountant, MemoryHolder}; + struct Local(Arc); + impl MemoryHolder for Local { + fn name(&self) -> &'static str { + "planes" + } + fn bytes(&self) -> usize { + self.0.lock().entries.iter().map(|e| e.bytes).sum() + } + fn oldest(&self) -> Option { + self.0.oldest_candidate() + } + fn drop_oldest(&self) -> usize { + self.0.drop_candidate() + } + } + let bytes: Arc<[u8]> = write(vec![part(None, &RGBA, (32, 32), Compression::ZIP1)], (32, 32)).into(); + let store = Arc::new(PlaneStore::new(CACHE_BUDGET)); + let all = Want { all: true, ids: (0..4).collect() }; + let get = |p: &str, by: Use| { + let source = ExrSource::Bytes(bytes.clone()); + let index = crate::exr_index::get(p, &source).unwrap(); + store.get(p, &source, &index, &all, by).unwrap() + }; + drop(get("/3271-acc-a.exr", Use::Other)); + drop(get("/3271-acc-b.exr", Use::Picture)); + let in_use = get("/3271-acc-c.exr", Use::Other); + let acc = Accountant::new(1); + let holder: Arc = Arc::new(Local(store.clone())); + acc.register(&holder); + acc.balance(); + assert_eq!(store.cached(), ["/3271-acc-b.exr", "/3271-acc-c.exr"], "held for effects, and in use"); + drop(in_use); +} + +/// #3271: with the localizer on, a network OpenEXR is copied in the background and then read +/// from its local copy, with the same pixels; what is read is still named by the share's path +/// and identity (caches key it the same either way). +#[test] +fn a_localized_network_file_is_read_from_its_copy() { + let _serial = crate::localize::TEST_SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + let root = std::env::temp_dir().join(format!("ec-3271-localized-{}", std::process::id())); + let (share, local) = (root.join("share"), root.join("local")); + std::fs::create_dir_all(&share).unwrap(); + crate::localize::treat_as_network(&share); + let file = share.join("plate_0001.exr"); + std::fs::write(&file, multipart()).unwrap(); + let f = crate::probe(&file).unwrap(); + let pool = crate::MediaPool::new(); + pool.set_localizer(Some(effectcraft_render::LocalizeConfig { folder: local.clone(), max_bytes: 1 << 30, network: vec![], disk_space: None })); + let from_share = pool.frame_at(&f, Tick::ZERO).unwrap(); + let until = std::time::Instant::now() + std::time::Duration::from_secs(10); + while crate::localize::status().is_some_and(|s| s.files == 0) && std::time::Instant::now() < until { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert!(pool.localize_status().is_some_and(|s| s.files == 1), "{:?}", pool.localize_status()); + pool.forget(&f.path); + let before = crate::opens_under(&local); + let (img, read) = crate::reads::captured(|| pool.frame_at(&f, Tick::ZERO).unwrap()); + assert!(crate::opens_under(&local) > before, "read from the local copy"); + assert_eq!(bits(&img), bits(&from_share)); + let stamp = FileStamp::of_metadata(&std::fs::metadata(&file).unwrap()); + assert!(read.files().iter().any(|r| *r.path == *f.path && r.stamp == stamp), "named by the share's file: {read:?}"); + pool.set_localizer(None); + let _ = std::fs::remove_dir_all(&root); +} + +/// #3271: a viewer region of interest reads only the footage rows it shows of an OpenEXR layer +/// (with one scan line per chunk, only those lines are decompressed), and the region renders +/// bit for bit what reading the whole frame renders, at full and reduced resolution and at +/// several layer scales. In a collapsed precomp the whole frame is read (its layers are placed +/// through the precomp layer too). +#[test] +fn a_region_of_interest_reads_only_its_rows() { + use effectcraft_project::{Comp, ItemKind, LayerSource, Project, Value, build}; + use effectcraft_render::{RenderOpts, Renderer}; + use effectcraft_time::FrameRate; + /// A pool reading whole frames (the region's rows ignored). + struct Whole<'a>(&'a crate::MediaPool); + impl FootageSource for Whole<'_> { + fn frame(&self, item: ItemId, f: &Footage, t: Tick) -> Option> { + self.0.frame(item, f, t) + } + fn frame_with(&self, item: ItemId, f: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve) -> Option> { + self.0.frame_with(item, f, t, size, float) + } + } + let bytes: Arc<[u8]> = single_part_zips().into(); + let path = "/3271-roi.exr"; + let fresh = || { + let pool = crate::MediaPool::new(); + pool.add_bytes(path, bytes.clone()); + pool + }; + let f = crate::probe_bytes(path, bytes.clone()).unwrap(); + let mut p = Project::default(); + let comp = Comp::new(96, 96, FrameRate::FPS_30, Tick::from_seconds_f64(1.0)); + let cid = p.add_item("Comp", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(comp.clone().into())); + let fid = p.add_item("plate", effectcraft_color::Label::Aqua, None, ItemKind::Footage(f)); + let mut l = build::layer(&mut p, &comp, "plate", LayerSource::Footage { item: fid }, (64, 64), None); + l.props.prop_mut("transform/position").unwrap().value = Value::Vec3([50.0, 46.0, 0.0]); + l.props.prop_mut("transform/rotation").unwrap().value = Value::Scalar(12.0); + p.comp_mut(cid).unwrap().layers = vec![l.clone()].into(); + // The same layer inside a collapsed precomp, moved by the precomp layer. + let inner = p.add_item("Inner", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(comp.clone().into())); + p.comp_mut(inner).unwrap().layers = vec![l].into(); + let outer = p.add_item("Outer", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(comp.clone().into())); + let mut pre = build::layer(&mut p, &comp, "Inner", LayerSource::Comp { item: inner }, (96, 96), None); + pre.switches.collapse = true; + pre.props.prop_mut("transform/position").unwrap().value = Value::Vec3([40.0, 60.0, 0.0]); + p.comp_mut(outer).unwrap().layers = vec![pre].into(); + for (layer_scale, scale) in [(100.0, 1.0), (100.0, 0.5), (30.0, 0.25), (30.0, 1.0), (250.0, 0.5)] { + for c in [cid, inner] { + p.comp_mut(c).unwrap().layers[0].props.prop_mut("transform/scale").unwrap().value = Value::Vec3([layer_scale * 0.9, layer_scale * 1.1, 100.0]); + } + let opts = RenderOpts { scale, roi: Some([38.0, 40.0, 24.0, 10.0]), ..Default::default() }; + let whole = Renderer::new(&p, &Whole(&fresh()), opts).comp_frame(cid, Tick::ZERO); + let before = decodes_of(path).len(); + let rows = Renderer::new(&p, &fresh(), opts).comp_frame(cid, Tick::ZERO); + assert_eq!(bits(&rows), bits(&whole), "{layer_scale}% at {scale}"); + // (a layer shrunk this far shows all of its rows in the region, grown by the warp's reach) + if layer_scale >= 100.0 { + let d = decodes_of(path); + let last = d.get(before..).and_then(|d| d.last()).expect("a read of the region's rows"); + assert!(last.stats.lines < SIZE.1, "{layer_scale}% at {scale}: {} lines", last.stats.lines); + } + // Collapsed: the whole frame. + let whole = Renderer::new(&p, &Whole(&fresh()), opts).comp_frame(outer, Tick::ZERO); + let before = decodes_of(path).len(); + let collapsed = Renderer::new(&p, &fresh(), opts).comp_frame(outer, Tick::ZERO); + assert_eq!(bits(&collapsed), bits(&whole), "collapsed, {layer_scale}% at {scale}"); + assert!(decodes_of(path).get(before..).unwrap_or_default().iter().all(|d| d.stats.lines == SIZE.1), "collapsed: the whole frame"); + } +} + +/// A source that calls the request off after `cancel_after` reads, or fails every read from +/// byte `fail_from` on (tests of a read in several batches). +struct Flaky { + inner: std::io::Cursor>, + reads: usize, + cancel_after: Option<(usize, Arc)>, + fail_from: Option, +} + +impl std::io::Read for Flaky { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + self.reads += 1; + if let Some((n, flag)) = &self.cancel_after + && self.reads > *n + { + flag.store(true, Ordering::SeqCst); + } + if self.fail_from.is_some_and(|at| self.inner.position() >= at) { + return Err(std::io::Error::other("the share went away")); + } + self.inner.read(buf) + } +} + +impl std::io::Seek for Flaky { + fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result { + self.inner.seek(pos) + } +} + +/// #3271: a file of more chunks than one batch is read in several (the next batch is read while +/// the one before decompresses, adjacent chunks in one read): the planes are the file's values, +/// also for a row range across batch boundaries; called off between batches it stops; a read +/// failing in a later batch is an I/O error. +#[test] +fn a_read_in_several_batches_is_whole_and_stops_between_them() { + let (w, h) = (8usize, 700usize); + let channels = [("A", true), ("B", false), ("G", true), ("R", true)]; + let bytes = write(vec![part(None, &channels, (w, h), Compression::ZIP1)], (w, h)); + let (ix, mut src) = indexed(&bytes); + let expect = |c: usize, i: usize| { + let (name, half) = channels[c]; + let v = value(i, c, name == "A"); + if half { f16::from_f32(v).to_f32() } else { v } + }; + let all = ReadRequest::full(vec![0, 1, 2, 3]); + let (planes, stats) = crate::exr_read::read_planes(&mut src, &ix, &all); + let planes = planes.unwrap(); + assert_eq!(stats.lines, h, "every line, in three batches"); + for (c, p) in planes.iter().enumerate() { + assert!(p.iter().enumerate().all(|(i, v)| v.to_bits() == expect(c, i).to_bits()), "channel {c}"); + } + let band = ReadRequest { rows: Some(250..520), ..all.clone() }; + let (got, stats) = crate::exr_read::read_planes(&mut src, &ix, &band); + let got = got.unwrap(); + assert_eq!(stats.lines, 270); + for (c, p) in got.iter().enumerate() { + for (i, v) in p.iter().enumerate() { + let want = if (250..520).contains(&(i / w)) { expect(c, i) } else { 0.0 }; + assert_eq!(v.to_bits(), want.to_bits(), "channel {c}, sample {i}"); + } + } + // Called off while the first batch is read: it stops before the next. + let flag = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let mut flaky = Flaky { inner: std::io::Cursor::new(bytes.clone()), reads: 0, cancel_after: Some((1, flag.clone())), fail_from: None }; + let (got, _) = filmcraft_media::cancel::with_cancel(&flag, || crate::exr_read::read_planes(&mut flaky, &ix, &all)); + assert_eq!(got.err(), Some(ReadError::Cancelled)); + // Chunks that follow each other in the file are read in one go, not one read per chunk. + let mut counted = Flaky { inner: std::io::Cursor::new(bytes.clone()), reads: 0, cancel_after: None, fail_from: None }; + assert!(crate::exr_read::read_planes(&mut counted, &ix, &all).0.is_ok()); + assert!(counted.reads <= 12, "{} reads for {h} chunks", counted.reads); + // (a failed read has no stats: the reads it made tell how far it went) + assert!(flaky.reads < counted.reads, "stopped early: {} of {} reads", flaky.reads, counted.reads); + // A read failing in a later batch (at chunk 300): an I/O error after the first was read. + let at = chunk_table(&bytes)[0][300].0; + let mut flaky = Flaky { inner: std::io::Cursor::new(bytes), reads: 0, cancel_after: None, fail_from: Some(at) }; + let (got, _) = crate::exr_read::read_planes(&mut flaky, &ix, &all); + assert!(matches!(got, Err(ReadError::Io(_))), "{got:?}"); + assert!(flaky.reads > 1, "the batches before it were read"); +} + +/// #3271: dropping entries for bytes (a decode over the budget, the memory accountant) drops +/// only entries that hold bytes: an unreadable file stays remembered (and isn't read again) +/// until there are too many entries. +#[test] +fn trimming_for_bytes_keeps_remembered_failures() { + let bytes: Arc<[u8]> = write(vec![part(None, &RGBA, (32, 32), Compression::ZIP1)], (32, 32)).into(); + let one = 4 * (32 * 32 * 4 + 1); + let store = PlaneStore::new(one); + let all = Want { all: true, ids: (0..4).collect() }; + let mut broken = bytes.to_vec(); + broken.truncate(broken.len() - 64); + let broken = ExrSource::Bytes(broken.into()); + let path = "/3271-trim-broken.exr"; + let index = crate::exr_index::get(path, &broken).unwrap(); + assert!(store.get(path, &broken, &index, &all, Use::Other).is_err()); + for p in ["/3271-trim-a.exr", "/3271-trim-b.exr"] { + let source = ExrSource::Bytes(bytes.clone()); + let index = crate::exr_index::get(p, &source).unwrap(); + assert!(store.get(p, &source, &index, &all, Use::Other).is_ok()); + } + while store.drop_candidate() > 0 {} + assert_eq!(store.cached(), [path], "the planes went, the failure stays"); + assert!(store.get(path, &broken, &index, &all, Use::Other).is_err()); + assert_eq!(decodes_of(path).len(), 1, "not read again"); +} + +/// #3271 (user test): the decoded planes have no budget of their own; the plane store follows +/// the footage frames' cap (#3298: the whole common budget on the desktop). A cap of 10000 MB +/// lets the plane store hold far more than 1 GB, and a change resizes it at once. +#[test] +fn the_footage_budget_sizes_the_plane_store() { + use effectcraft_render::FootageSource; + let pool = crate::MediaPool::new(); + pool.set_cache_budget(10_000 << 20); + assert_eq!(super::budget(), 10_000 << 20); + assert!(super::budget() > 1 << 30, "more than the old fixed 1 GB"); + pool.set_cache_budget(3_000 << 20); + assert_eq!(super::budget(), 3_000 << 20, "resized at run time"); + // (back to the default for the tests beside it) + pool.set_cache_budget(CACHE_BUDGET); +} + +/// #3271 (user decision): the footage frames and the decoded planes have one least-recently-used +/// order: filling the frame cache drops the oldest plane sets, filling the plane store drops the +/// oldest frames; neither side has a share of its own. (#3298: they share the one budget with +/// every cache, and the accountant orders by value; at the same cost per byte, as here, that is +/// least recently used first.) +#[test] +fn frames_and_planes_make_room_for_each_other() { + use effectcraft_render::memory::{Accountant, Candidate, MemoryHolder}; + struct Planes(Arc); + impl MemoryHolder for Planes { + fn name(&self) -> &'static str { + "planes" + } + fn bytes(&self) -> usize { + self.0.lock().entries.iter().map(|e| e.bytes).sum() + } + fn oldest(&self) -> Option { + self.0.oldest_candidate() + } + fn drop_oldest(&self) -> usize { + self.0.drop_candidate() + } + } + /// A holder whose items all cost the same per byte (decode times vary from run to run). + struct SameCost(Arc); + impl MemoryHolder for SameCost { + fn name(&self) -> &'static str { + self.0.name() + } + fn bytes(&self) -> usize { + self.0.bytes() + } + fn oldest(&self) -> Option { + self.0.oldest().map(|c| Candidate { cost_us: c.bytes as u64, ..c }) + } + fn drop_oldest(&self) -> usize { + self.0.drop_oldest() + } + } + let bytes: Arc<[u8]> = write(vec![part(None, &RGBA, (32, 32), Compression::ZIP1)], (32, 32)).into(); + let one = 4 * (32 * 32 * 4 + 1); + let budget = 5 * one; + let store = Arc::new(PlaneStore::new(budget)); + let pool = crate::MediaPool::with_budget(budget); + let acc = Accountant::new(budget); + let holders: Vec> = vec![Arc::new(SameCost(Arc::new(Planes(store.clone())))), Arc::new(SameCost(pool.memory_holder()))]; + for h in &holders { + acc.register(h); + } + let all = Want { all: true, ids: (0..4).collect() }; + let planes = |p: &str| { + let source = ExrSource::Bytes(bytes.clone()); + let index = crate::exr_index::get(p, &source).unwrap(); + drop(store.get(p, &source, &index, &all, Use::Other).unwrap()); + }; + // Plane sets first, then frames: the frames push the oldest plane sets out. + planes("/3271-share-p1.exr"); + planes("/3271-share-p2.exr"); + planes("/3271-share-p3.exr"); + for f in ["/f1", "/f2", "/f3"] { + pool.keep_test_frame(f, 32, 32); + acc.balance(); + } + assert_eq!(pool.test_frames(), ["/f1", "/f2", "/f3"], "the frames stay"); + assert!(!store.cached().contains(&"/3271-share-p1.exr".to_string()), "the oldest plane set went: {:?}", store.cached()); + assert!(store.cached().contains(&"/3271-share-p3.exr".to_string())); + // Now plane sets: they push the oldest frames out. + for p in ["/3271-share-p4.exr", "/3271-share-p5.exr", "/3271-share-p6.exr"] { + planes(p); + acc.balance(); + } + let frames = pool.test_frames(); + assert!(!frames.contains(&"/f1".to_string()), "the oldest frame went: {frames:?}"); + assert!(store.cached().contains(&"/3271-share-p6.exr".to_string()), "the newest plane set stays"); + assert!(acc.total() <= budget, "{} of {budget}", acc.total()); +} + +/// #3271 (rule: picture channels are never kept twice): once the picture is converted (the +/// media pool keeps it), its R, G, B, A planes leave the plane store; the channels the effects +/// read stay, and a picture channel an effect names itself (EXtractoR reading "R") stays too. +#[test] +fn the_picture_planes_are_not_kept_beside_the_picture() { + let bytes: Arc<[u8]> = + write(vec![part(None, &[("R", true), ("G", true), ("B", true), ("A", true), ("Z", false), ("N", false)], (16, 8), Compression::ZIP1)], (16, 8)).into(); + let source = ExrSource::Bytes(bytes); + let op = crate::convert::AlphaOp::of(&Footage::default(), FloatCurve::Linear); + let plane = 16 * 8 * 4; + for (path, need, kept) in [ + ("/3271-slim-aux.exr", AuxNeed::Lookups(vec![AuxLookup::Name("Z".into())]), vec!["Z"]), + ("/3271-slim-named.exr", AuxNeed::Lookups(vec![AuxLookup::Name("Z".into()), AuxLookup::Name("R".into())]), vec!["R", "Z"]), + ("/3271-slim-all.exr", AuxNeed::All, vec!["N", "Z"]), + ] { + let Picture::Done(Ok(_)) = picture(path, &source, op, Some(&need)) else { panic!("{path}: a picture") }; + let (names, bytes) = shared().kept(path).expect("the effects' channels are kept"); + assert_eq!(names, kept, "{path}"); + assert_eq!(bytes, kept.iter().map(|n| n.len() + plane).sum::(), "{path}"); + forget(path); + } + // The picture alone keeps nothing. + let path = "/3271-slim-none.exr"; + let Picture::Done(Ok(_)) = picture(path, &source, op, None) else { panic!("a picture") }; + assert!(shared().kept(path).is_none()); + forget(path); +} + +/// #3750 review: slimming a set someone else still holds copies the planes it keeps; when the +/// system can't give the memory for the copy, the set stays as it was (nothing aborts). +#[test] +fn a_shared_set_stays_whole_when_its_copy_finds_no_memory() { + let bytes: Arc<[u8]> = + write(vec![part(None, &[("R", true), ("G", true), ("B", true), ("A", true), ("Z", false)], (16, 8), Compression::ZIP1)], (16, 8)).into(); + let path = "/3750-slim-no-memory.exr"; + let source = ExrSource::Bytes(bytes); + let store = PlaneStore::new(CACHE_BUDGET); + let index = crate::exr_index::get(path, &source).unwrap(); + let all = Want { all: true, ids: index.picture_ids().into_iter().collect() }; + let whole = store.get(path, &source, &index, &all, Use::Other).unwrap(); + let z: BTreeSet = index.aux_ids().into_iter().collect(); + COPIES_REFUSED.lock().unwrap().push(path.to_string()); + // (`whole` is still held here: the planes kept would be copied) + store.keep_only(path, whole.clone(), &z); + COPIES_REFUSED.lock().unwrap().retain(|p| p != path); + let kept = store.lock().entries.iter().find(|e| e.path == path).and_then(|e| e.batch.clone()); + assert!(kept.is_some_and(|k| Arc::ptr_eq(&k, &whole)), "the whole set is kept"); + // With memory for the copy: the kept channel alone. + store.keep_only(path, whole.clone(), &z); + assert_eq!(store.kept(path).map(|(n, _)| n), Some(vec!["Z".to_string()])); +} + +/// #3750 review: a frame of another size than its footage's (a sequence frame larger than the +/// first, shown scaled) is read whole under a region of interest, so the region shows what the +/// whole frame shows; the region's rows are of the footage's size, not of that frame. +#[test] +fn a_frame_of_another_size_is_read_whole_under_a_region() { + use effectcraft_project::{Comp, ItemKind, LayerSource, Project, build}; + use effectcraft_render::{RenderOpts, Renderer}; + use effectcraft_time::FrameRate; + struct Whole<'a>(&'a crate::MediaPool); + impl FootageSource for Whole<'_> { + fn frame(&self, item: ItemId, f: &Footage, t: Tick) -> Option> { + self.0.frame(item, f, t) + } + fn frame_with(&self, item: ItemId, f: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve) -> Option> { + self.0.frame_with(item, f, t, size, float) + } + } + let bytes: Arc<[u8]> = single_part_zips().into(); + let path = "/3750-roi-other-size.exr"; + let fresh = || { + let pool = crate::MediaPool::new(); + pool.add_bytes(path, bytes.clone()); + pool + }; + // (the footage's size is half the file's: a later, larger frame) + let mut f = crate::probe_bytes(path, bytes.clone()).unwrap(); + f.width = SIZE.0 as u32 / 2; + f.height = SIZE.1 as u32 / 2; + let mut p = Project::default(); + let comp = Comp::new(96, 96, FrameRate::FPS_30, Tick::from_seconds_f64(1.0)); + let cid = p.add_item("Comp", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(comp.clone().into())); + let fid = p.add_item("plate", effectcraft_color::Label::Aqua, None, ItemKind::Footage(f)); + let l = build::layer(&mut p, &comp, "plate", LayerSource::Footage { item: fid }, (SIZE.0 as u32 / 2, SIZE.1 as u32 / 2), None); + p.comp_mut(cid).unwrap().layers = vec![l].into(); + let opts = RenderOpts { roi: Some([30.0, 40.0, 30.0, 8.0]), ..Default::default() }; + let whole = Renderer::new(&p, &Whole(&fresh()), opts).comp_frame(cid, Tick::ZERO); + let before = decodes_of(path).len(); + let rows = Renderer::new(&p, &fresh(), opts).comp_frame(cid, Tick::ZERO); + assert_eq!(bits(&rows), bits(&whole)); + let after = decodes_of(path).get(before..).unwrap_or_default().to_vec(); + assert!(!after.is_empty() && after.iter().all(|d| d.stats.lines == SIZE.1), "read whole: {after:?}"); +} + +/// #3271 review (#3301): a remembered failure belongs to the file as it was. A file that was +/// unreadable and is then replaced on disk (no Reload Footage: the new index comes from its new +/// stamp) is read again, not refused with the old file's failure. +#[test] +fn a_failure_is_forgotten_once_the_file_changes() { + let good: Arc<[u8]> = write(vec![part(None, &RGBA, (8, 8), Compression::ZIP1)], (8, 8)).into(); + let mut broken = good.to_vec(); + broken.truncate(broken.len() - 64); + let path = "/3271-failed-then-fixed.exr"; + let store = PlaneStore::new(CACHE_BUDGET); + let all = Want { all: true, ids: (0..4).collect() }; + let source = ExrSource::Bytes(broken.into()); + let old = crate::exr_index::get(path, &source).unwrap(); + assert!(store.get(path, &source, &old, &all, Use::Other).is_err()); + assert!(store.get(path, &source, &old, &all, Use::Other).is_err(), "remembered for the same file"); + // The file is replaced: another index (here read under another name, as the file's new stamp + // would give it). + let source = ExrSource::Bytes(good); + let new = crate::exr_index::get("/3271-failed-then-fixed-new.exr", &source).unwrap(); + assert!(!Arc::ptr_eq(&old, &new)); + assert!(store.get(path, &source, &new, &all, Use::Other).is_ok(), "the new file is read"); +} + +/// #3271 review: a failed picture request (too large here) doesn't refuse a later request for +/// the other channels: "all channels" is every channel but the picture's, so it doesn't ask for +/// what failed. +/// Memory the system refuses during a read is a read that failed just now, not a file too large: +/// it isn't remembered, and the next request reads again (a file too large is remembered). +#[test] +fn an_allocation_failure_is_not_remembered() { + use crate::exr_read::{ReadError, read_error}; + assert!(matches!(read_error(craft_exr::seek::Error::OutOfMemory("planes".into())), ReadError::OutOfMemory(why) if why.contains("planes"))); + assert!(matches!(read_error(craft_exr::seek::Error::LimitExceeded("planes".into())), ReadError::TooLarge(_))); + // A read that failed just now (here: the file can't be opened) is a stop, and the next + // request for the same channels reads them. + let bytes: Arc<[u8]> = single_part_zips().into(); + let path = "/oom-not-remembered.exr"; + let store = PlaneStore::new(CACHE_BUDGET); + let index = crate::exr_index::get(path, &ExrSource::Bytes(bytes.clone())).unwrap(); + let want = Want { all: false, ids: index.picture_ids().into_iter().collect() }; + let gone = ExrSource::File(std::env::temp_dir().join("ec-oom-not-remembered-missing.exr")); + assert_eq!(store.get(path, &gone, &index, &want, Use::Other).err(), Some(Refused::Stopped)); + assert!(store.get(path, &ExrSource::Bytes(bytes), &index, &want, Use::Other).is_ok(), "read again, not refused from memory"); +} + +#[test] +fn a_failed_picture_leaves_the_other_channels_readable() { + let bytes: Arc<[u8]> = + write(vec![part(None, &[("R", true), ("G", true), ("B", true), ("A", true), ("Z", false)], (8, 8), Compression::ZIP1)], (8, 8)).into(); + let path = "/3271-failed-picture.exr"; + // (room for three planes: the picture's four don't fit, the depth plane does) + set_cap(path, 3 * 8 * 8 * 4); + let store = PlaneStore::new(CACHE_BUDGET); + let source = ExrSource::Bytes(bytes); + let index = crate::exr_index::get(path, &source).unwrap(); + let picture = Want { all: false, ids: index.picture_ids().into_iter().collect() }; + assert!(matches!(store.get(path, &source, &index, &picture, Use::Other), Err(Refused::TooLarge(_)))); + assert!(store.get(path, &source, &index, &picture, Use::Other).is_err(), "remembered"); + let rest = store.get(path, &source, &index, &Want { all: true, ids: Default::default() }, Use::Other).expect("the other channels"); + assert!(rest.aux.get("Z").is_some()); +} + +/// #3749: a read over the fixed floor is allowed up to what the system's memory gives (the +/// session's figure), never under the floor, and refused with a reason beyond it. The floor is +/// small here: the real one is 8 GiB. +#[test] +fn a_read_over_the_floor_is_allowed_up_to_the_systems_memory() { + let _only = LIMIT_TESTS.lock().unwrap_or_else(PoisonError::into_inner); + let bytes = write(vec![part(None, &RGBA, (8, 8), Compression::ZIP1)], (8, 8)); + let mut src = std::io::Cursor::new(bytes.as_slice()); + let index = crate::exr_index::build(&mut src, FileStamp::Virtual).unwrap(); + // Four channels of 8×8 f32 are 1024 bytes; the floor is 512. + let request = ReadRequest { floor: 512, ..ReadRequest::full(vec![0, 1, 2, 3]) }; + let read = |src: &mut std::io::Cursor<&[u8]>| crate::exr_read::read_planes(src, &index, &request).0; + effectcraft_render::memory::set_decode_limit(None); + effectcraft_render::memory::set_decode_limit_source(None); + assert!(matches!(read(&mut src), Err(crate::exr_read::ReadError::TooLarge(_))), "over the floor, memory unknown"); + effectcraft_render::memory::set_decode_limit(Some(2048)); + assert_eq!(read(&mut src).map(|p| p.len()).ok(), Some(4), "the system's memory allows it"); + effectcraft_render::memory::set_decode_limit(Some(800)); + assert!(matches!(read(&mut src), Err(crate::exr_read::ReadError::TooLarge(_))), "still more than the system's memory"); + effectcraft_render::memory::set_decode_limit(None); +} + +/// #3749: a refusal for the request's size is remembered only while the decode limit stays as it +/// was: when the system's memory figure arrives or changes, the request is decided anew. +#[test] +fn a_refusal_for_size_is_decided_anew_when_the_decode_limit_changes() { + let _only = LIMIT_TESTS.lock().unwrap_or_else(PoisonError::into_inner); + let bytes: Arc<[u8]> = write(vec![part(None, &RGBA, (8, 8), Compression::ZIP1)], (8, 8)).into(); + let path = "/3749-refusal-generation.exr"; + // Room for one plane of 8×8 f32: four are refused. + set_cap(path, 8 * 8 * 4); + let store = PlaneStore::new(CACHE_BUDGET); + let source = ExrSource::Bytes(bytes); + let index = crate::exr_index::get(path, &source).unwrap(); + let want = Want { all: false, ids: (0..4).collect() }; + // (the refusal is made before anything is read: the decodes are counted as they begin) + let begun = Arc::new(AtomicU64::new(0)); + { + let begun = begun.clone(); + set_before_read( + path, + Some(Arc::new(move |_: &str| { + begun.fetch_add(1, Ordering::SeqCst); + })), + ); + } + let refused = || matches!(store.get(path, &source, &index, &want, Use::Other), Err(Refused::TooLarge(_))); + assert!(refused()); + assert!(refused()); + assert_eq!(begun.load(Ordering::SeqCst), 1, "the second refusal came from memory"); + // (figures under the fixed floor: only the change counts, no other test's limit moves) + effectcraft_render::memory::set_decode_limit(Some(1000)); + effectcraft_render::memory::set_decode_limit(Some(2000)); + assert!(refused(), "still over the caller's own limit"); + assert_eq!(begun.load(Ordering::SeqCst), 2, "decided anew after the limit changed"); + set_before_read(path, None); + effectcraft_render::memory::set_decode_limit(None); +} + +/// A file of an 8×8 picture and a depth plane: five planes of 256 bytes. +fn picture_and_depth() -> Vec { + write(vec![part(None, &[("R", true), ("G", true), ("B", true), ("A", true), ("Z", false)], (8, 8), Compression::ZIP1)], (8, 8)) +} + +/// #3749 (#3301 review): the limit is for the planes a request ends with, not for the ones read +/// just now: channels added to the planes held count with them. When together they are over +/// the limit the planes held are let go and the request is read on its own (it fits alone); a +/// request that doesn't fit alone is refused, whatever is held. +#[test] +fn channels_added_to_the_planes_held_count_toward_the_limit() { + let path = "/3749-held-and-added.exr"; + // Room for four planes: the picture fits, one more with it is five. + set_cap(path, 4 * 8 * 8 * 4); + let store = PlaneStore::new(CACHE_BUDGET); + let source = ExrSource::Bytes(picture_and_depth().into()); + let index = crate::exr_index::get(path, &source).unwrap(); + let picture = Want { all: false, ids: index.picture_ids().into_iter().collect() }; + store.get(path, &source, &index, &picture, Use::Other).expect("the picture fits"); + let rest = Want { all: true, ids: Default::default() }; + let depth = store.get(path, &source, &index, &rest, Use::Other).expect("the depth plane fits alone"); + assert!(depth.aux.get("Z").is_some()); + assert!(depth.aux.get("R").is_none(), "the picture's planes were let go: four held and one more are five"); + // (nothing else holds the depth plane: let go, it is gone, see + // `planes_let_go_but_still_held_count_toward_the_limit`) + drop(depth); + // The picture again: it fits alone, the depth plane is let go in turn. + let again = store.get(path, &source, &index, &picture, Use::Other).expect("the picture fits alone"); + assert!(again.aux.get("R").is_some() && again.aux.get("Z").is_none()); + // Everything at once is five planes: refused, however it is asked. + let everything = Want { all: true, ids: (0..5).collect() }; + assert!(matches!(store.get(path, &source, &index, &everything, Use::Other).err(), Some(Refused::TooLarge(_)))); +} + +/// #3750 review: when the planes held are let go because they don't fit the limit with the ones +/// a request adds, they are let go before the request is read: the held planes and the new ones +/// are never in memory together (the store, the decode and its flight all let go of them). Also +/// for a picture's planes held for its effects. +#[test] +fn planes_let_go_are_gone_before_the_request_is_read() { + let path = "/3750-let-go-before-read.exr"; + // Room for four planes: the picture fits, one more with it is five. + set_cap(path, 4 * 8 * 8 * 4); + let store = PlaneStore::new(CACHE_BUDGET); + let source = ExrSource::Bytes(picture_and_depth().into()); + let index = crate::exr_index::get(path, &source).unwrap(); + let picture = Want { all: false, ids: index.picture_ids().into_iter().collect() }; + let held = Arc::downgrade(&store.get(path, &source, &index, &picture, Use::Picture).expect("the picture fits")); + assert!(held.upgrade().is_some() && store.is_held(path), "kept for the effects"); + // Each decode that reads notes whether the picture's planes are still in memory. + let alive = Arc::new(Mutex::new(Vec::new())); + { + let (alive, held) = (alive.clone(), held.clone()); + let hook: Hook = Arc::new(move |_: &str| alive.lock().unwrap().push(held.upgrade().is_some())); + set_before_read(path, Some(hook)); + } + let rest = Want { all: true, ids: Default::default() }; + let depth = store.get(path, &source, &index, &rest, Use::Other).expect("the depth plane fits alone"); + set_before_read(path, None); + assert!(depth.aux.get("Z").is_some() && depth.aux.get("R").is_none()); + let alive = alive.lock().unwrap().clone(); + assert_eq!(alive.last(), Some(&false), "the picture's planes were gone when the depth plane was read: {alive:?}"); + assert_eq!(decodes_of(path).last().map(|d| d.channels.len()), Some(1), "the depth plane alone was read"); +} + +/// Notes, for each read of `path`'s planes, whether `old` was still in memory then. +fn alive_at_reads(path: &str, old: std::sync::Weak) -> Arc>> { + let alive = Arc::new(Mutex::new(Vec::new())); + let noted = alive.clone(); + set_read_error( + path, + Some(Arc::new(move |_: &[usize]| { + noted.lock().unwrap().push(old.strong_count() > 0); + None + })), + ); + alive +} + +/// #3750 review: planes the store let go that a caller still holds (an effect, a Cryptomatte +/// pick) are in memory: they count toward the limit, and a request that doesn't fit beside them +/// is refused for now (not remembered) instead of read beside them; once they are gone it is +/// read. +#[test] +fn planes_let_go_but_still_held_count_toward_the_limit() { + let path = "/3750-let-go-still-held.exr"; + // Room for four planes: the picture fits, one more with it is five. + set_cap(path, 4 * 8 * 8 * 4); + let store = PlaneStore::new(CACHE_BUDGET); + let source = ExrSource::Bytes(picture_and_depth().into()); + let index = crate::exr_index::get(path, &source).unwrap(); + let picture = Want { all: false, ids: index.picture_ids().into_iter().collect() }; + // A caller keeps the picture's planes. + let held = store.get(path, &source, &index, &picture, Use::Other).expect("the picture fits").aux.clone(); + let alive = alive_at_reads(path, Arc::downgrade(&held)); + let rest = Want { all: true, ids: Default::default() }; + let refused = store.get(path, &source, &index, &rest, Use::Other).err(); + assert!(matches!(&refused, Some(Refused::NoMemory(why)) if why.contains("still in use")), "{refused:?}"); + drop(held); + let depth = store.get(path, &source, &index, &rest, Use::Other).expect("read once they are gone: not remembered"); + set_read_error(path, None); + assert!(depth.aux.get("Z").is_some() && depth.aux.get("R").is_none()); + let alive = alive.lock().unwrap().clone(); + assert_eq!(alive, vec![false], "read once, after the planes held were gone"); +} + +/// #3750 review: a decode thread that took over a decode whose held planes are let go asks +/// again while the request that queued the decode still holds that decode's flight: the flight +/// no longer keeps the planes, so they are gone, not read beside, when the request is read. +#[test] +fn a_claimed_decode_is_not_read_beside_the_planes_it_let_go() { + let path = "/3750-claimed-let-go.exr"; + set_cap(path, 4 * 8 * 8 * 4); + let source = ExrSource::Bytes(picture_and_depth().into()); + let store = Arc::new(PlaneStore::new(CACHE_BUDGET)); + let index = crate::exr_index::get(path, &source).unwrap(); + let picture = Want { all: false, ids: index.picture_ids().into_iter().collect() }; + let old = Arc::downgrade(&store.get(path, &source, &index, &picture, Use::Other).expect("the picture fits").aux); + let alive = alive_at_reads(path, old.clone()); + let rest = Want { all: true, ids: Default::default() }; + let threads = crate::pool::decode_threads().unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + let done = Arc::new(std::sync::atomic::AtomicBool::new(false)); + // When the asker queues its decode: a decode thread asks for the same planes. + { + let (store, source, index, rest, tx, done) = (store.clone(), source.clone(), index.clone(), rest.clone(), tx.clone(), done.clone()); + let hook: Hook = Arc::new(move |_: &str| { + let (store, source, index, rest, tx, done) = (store.clone(), source.clone(), index.clone(), rest.clone(), tx.clone(), done.clone()); + threads.spawn(move || { + let got = store.get(path, &source, &index, &rest, Use::Other); + done.store(true, Ordering::SeqCst); + let _ = tx.send(got.map(|b| b.ids.len())); + }); + }); + QUEUING.lock().unwrap().push((path.to_string(), hook)); + } + // The queued job waits until that decode thread claimed it... + let hold: Hook = Arc::new(|p: &str| { + let claims = CLAIMS.lock().unwrap(); + let _ = CLAIM_SIGNAL.wait_timeout_while(claims, std::time::Duration::from_secs(10), |c| !c.iter().any(|c| c == p)); + }); + STARTING.lock().unwrap().push((path.to_string(), hold)); + // ...and the asker, handed the let-go, holds its flight until the decode thread has asked + // again. + { + let done = done.clone(); + let wait: Hook = Arc::new(move |_: &str| { + let until = std::time::Instant::now() + std::time::Duration::from_secs(10); + while !done.load(Ordering::SeqCst) && std::time::Instant::now() < until { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + }); + HANDED.lock().unwrap().push((path.to_string(), wait)); + } + let asked = store.get(path, &source, &index, &rest, Use::Other).map(|b| b.ids.len()); + let claimed = rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap(); + QUEUING.lock().unwrap().retain(|(p, _)| p != path); + STARTING.lock().unwrap().retain(|(p, _)| p != path); + HANDED.lock().unwrap().retain(|(p, _)| p != path); + set_read_error(path, None); + assert!(CLAIMS.lock().unwrap().iter().any(|p| p == path), "claimed"); + assert_eq!(claimed.ok(), Some(1), "the decode thread reads the depth plane alone"); + assert_eq!(asked.ok(), Some(1), "so does the asker"); + assert!(old.upgrade().is_none()); + let alive = alive.lock().unwrap().clone(); + assert!(!alive.is_empty() && !alive.contains(&true), "no read beside the planes let go: {alive:?}"); +} + +/// #3749 (#3301 review): planes the disk cache gives back count toward the limit of a request +/// like the ones read from the file. +#[test] +fn planes_from_the_disk_cache_count_toward_the_limit() { + let _disk = DISK_TESTS.lock().unwrap_or_else(PoisonError::into_inner); + use effectcraft_render::disk_cache::DiskCache; + let dir = std::env::temp_dir().join(format!("ec-3749-disk-union-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("union_0001.exr"); + std::fs::write(&file, picture_and_depth()).unwrap(); + let dc = DiskCache::open(dir.join("cache"), 1 << 30).unwrap(); + dc.set_read_us_per_mb(0); + use_disk_for(&dir.to_string_lossy()); + set_disk_cache(Some(&dc)); + let path = file.to_string_lossy().to_string(); + let source = ExrSource::File(file.clone()); + let index = crate::exr_index::get(&path, &source).unwrap(); + let all = Want { all: true, ids: (0..5).collect() }; + let first = PlaneStore::new(CACHE_BUDGET).get(&path, &source, &index, &all, Use::Other).is_ok(); + dc.flush(); + // All five planes are in the disk cache (a store without them in RAM reads them back)... + let warm = PlaneStore::new(CACHE_BUDGET).get(&path, &source, &index, &all, Use::Other).is_ok(); + let from_disk = decodes_of(&path).last().is_some_and(|d| d.from_disk); + // ...and a request may use four. + set_cap(&path, 4 * 8 * 8 * 4); + let refused = PlaneStore::new(CACHE_BUDGET).get(&path, &source, &index, &all, Use::Other).err(); + set_disk_cache(None); + let _ = std::fs::remove_dir_all(&dir); + assert!(first && warm && from_disk, "decoded without a limit, then read back from the disk cache"); + assert!(matches!(refused, Some(Refused::TooLarge(_))), "{refused:?}"); +} + +/// #3749: a plane the system cannot give is not an aborted process: `craft-exr` asks for the +/// planes' memory first and reports what it can't get, memory refused just now (not remembered, +/// not read again at once); a plane over the read's limit (the decode limit handed to it) is a +/// refusal for size with `craft-exr`'s reason. +#[test] +fn a_plane_the_system_cannot_give_is_refused_not_allocated() { + use crate::exr_read::{ReadError, read_error}; + use craft_exr::seek::Error; + let gone = read_error(Error::OutOfMemory("4096 bytes of planes".into())); + assert!(matches!(&gone, ReadError::OutOfMemory(why) if why.contains("4096 bytes of planes")), "{gone:?}"); + let over = read_error(Error::LimitExceeded("the requested rows need 4096 bytes".into())); + assert!(matches!(&over, ReadError::TooLarge(why) if why.contains("4096 bytes")), "{over:?}"); +} + +/// A source that counts the bytes read from it. +struct Counted { + inner: R, + read: usize, +} + +impl std::io::Read for Counted { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let n = self.inner.read(buf)?; + self.read += n; + Ok(n) + } +} + +impl std::io::Seek for Counted { + fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result { + self.inner.seek(to) + } +} + +/// #3749 review: one decompressed block may take 8 GiB at most, whatever memory the read may +/// use: a file whose block is larger (a data window a billion pixels wide over one large chunk, +/// so that the chunk could hold it) is refused for its size before anything is read, also with a +/// decode limit far above the block. +#[test] +fn a_block_over_the_fixed_limit_is_refused_whatever_the_decode_limit() { + let _only = LIMIT_TESTS.lock().unwrap_or_else(PoisonError::into_inner); + let f32s = [("R", false), ("G", false), ("B", false), ("A", false)]; + let small = write(vec![part(None, &f32s, (1, 1), Compression::ZIP1)], (1, 1)); + // One line of 2^30 - 2 pixels of four f32 channels: a block of 16 GiB... + let mut bytes = with_data_window_x_max(small, (1 << 30) - 3); + // ...over a chunk long enough to hold it at craft-exr's ratio (2^16 bytes a byte). + bytes.extend(std::iter::repeat_n(0u8, 300 << 10)); + let index = crate::exr_index::build(&mut std::io::Cursor::new(bytes.as_slice()), FileStamp::Virtual).expect("indexed: the chunk can hold the block"); + // The read may use 64 GiB (the floor is tiny, the system's figure high). + effectcraft_render::memory::set_decode_limit(Some(64 << 30)); + let request = ReadRequest { floor: 8, ..ReadRequest::full(vec![0, 1, 2, 3]) }; + let mut src = Counted { inner: std::io::Cursor::new(bytes.as_slice()), read: 0 }; + let (read, _) = crate::exr_read::read_planes(&mut src, &index, &request); + effectcraft_render::memory::set_decode_limit(None); + assert!(matches!(&read, Err(crate::exr_read::ReadError::TooLarge(why)) if why.contains("one block of this read may use")), "{read:?}"); + assert_eq!(src.read, 0, "refused before anything was read"); +} + +/// Reads of `path` fail for lack of memory when `fails` says so for the channels read; the reads +/// asked for are counted. +fn no_memory_when(path: &str, fails: impl Fn(&[usize]) -> bool + Send + Sync + 'static) -> Arc { + let asked = Arc::new(AtomicU64::new(0)); + let counted = asked.clone(); + set_read_error( + path, + Some(Arc::new(move |ids: &[usize]| { + counted.fetch_add(1, Ordering::SeqCst); + fails(ids).then(|| crate::exr_read::ReadError::OutOfMemory("no memory just now".into())) + })), + ); + asked +} + +/// #3749 review: memory the system refuses during a read is neither read again at once (the +/// store's retries, a copy) nor remembered: the request is refused with the reason, and the next +/// request reads again. +#[test] +fn memory_the_system_cannot_give_is_neither_retried_nor_remembered() { + let path = "/3749-no-memory.exr"; + let source = ExrSource::Bytes(picture_and_depth().into()); + let store = PlaneStore::new(CACHE_BUDGET); + let index = crate::exr_index::get(path, &source).unwrap(); + let want = Want { all: true, ids: (0..5).collect() }; + let asked = no_memory_when(path, |_| true); + let refused = store.get(path, &source, &index, &want, Use::Other).err(); + assert!(matches!(&refused, Some(Refused::NoMemory(why)) if why.contains("no memory just now")), "{refused:?}"); + assert_eq!(asked.load(Ordering::SeqCst), 1, "read once, not again at once"); + let asked = no_memory_when(path, |_| false); + assert!(store.get(path, &source, &index, &want, Use::Other).is_ok(), "not remembered: the memory is there now"); + assert_eq!(asked.load(Ordering::SeqCst), 1); + set_read_error(path, None); +} + +/// #3750 review: a decode thread that took over a queued decode the system has no memory for +/// hands the refusal to the request that queued it and answers its own request with it too: the +/// file is read once, not again at once for a copy. +#[test] +fn a_claimed_decode_without_memory_is_not_read_again() { + let path = "/3750-claimed-no-memory.exr"; + let source = ExrSource::Bytes(picture_and_depth().into()); + let store = Arc::new(PlaneStore::new(CACHE_BUDGET)); + let index = crate::exr_index::get(path, &source).unwrap(); + let want = Want { all: true, ids: (0..5).collect() }; + let asked = no_memory_when(path, |_| true); + let threads = crate::pool::decode_threads().unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + // When the asker queues its decode: a decode thread asks for the same planes. + { + let (store, source, index, want, tx) = (store.clone(), source.clone(), index.clone(), want.clone(), tx.clone()); + let hook: Hook = Arc::new(move |_: &str| { + let (store, source, index, want, tx) = (store.clone(), source.clone(), index.clone(), want.clone(), tx.clone()); + threads.spawn(move || { + let _ = tx.send(store.get(path, &source, &index, &want, Use::Other).err()); + }); + }); + QUEUING.lock().unwrap().push((path.to_string(), hook)); + } + // The queued job waits until that decode thread claimed it. + let hold: Hook = Arc::new(|p: &str| { + let claims = CLAIMS.lock().unwrap(); + let _ = CLAIM_SIGNAL.wait_timeout_while(claims, std::time::Duration::from_secs(10), |c| !c.iter().any(|c| c == p)); + }); + STARTING.lock().unwrap().push((path.to_string(), hold)); + let queued = store.get(path, &source, &index, &want, Use::Other).err(); + let claimed = rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap(); + QUEUING.lock().unwrap().retain(|(p, _)| p != path); + STARTING.lock().unwrap().retain(|(p, _)| p != path); + set_read_error(path, None); + assert!(CLAIMS.lock().unwrap().iter().any(|p| p == path), "claimed"); + assert!(matches!(&claimed, Some(Refused::NoMemory(_))), "{claimed:?}"); + assert!(matches!(&queued, Some(Refused::NoMemory(_))), "{queued:?}"); + assert_eq!(asked.load(Ordering::SeqCst), 1, "read once, not again for a copy"); +} + +/// #3749 review: a picture whose channels the system has no memory for just now is read alone +/// without the effects' channels, and refused with the reason when even that doesn't fit; never +/// handed to the whole file's decode (which would ask for more memory, infallibly). +#[test] +fn a_picture_without_memory_is_read_alone_or_refused_never_decoded_whole() { + let path = "/3749-no-memory-picture.exr"; + let source = ExrSource::Bytes(picture_and_depth().into()); + let op = AlphaOp::of(&Footage::default(), FloatCurve::Linear); + // With the depth plane it is five planes, more than the system gives: the picture alone. + no_memory_when(path, |ids| ids.len() > 4); + let Picture::Done(Ok(img)) = picture(path, &source, op, Some(&AuxNeed::All)) else { panic!("the picture alone") }; + assert_eq!((img.width, img.height), (8, 8)); + // Not even the picture: refused with the reason, also for some of its rows. + no_memory_when(path, |_| true); + match picture(path, &source, op, None) { + Picture::Done(Err(why)) => assert!(why.contains("no memory just now"), "{why}"), + _ => panic!("refused with the reason"), + } + match picture_rows(path, &source, op, (0, 4), (8, 8)) { + Picture::Done(Err(why)) => assert!(why.contains("no memory just now"), "{why}"), + _ => panic!("rows refused with the reason"), + } + set_read_error(path, None); +} + +/// #3749 review: only a refusal for size is decided anew when the decode limit changes; an +/// unreadable request stays refused, also when another request fails under the new limit. +#[test] +fn an_unreadable_request_stays_refused_when_the_decode_limit_changes() { + let _only = LIMIT_TESTS.lock().unwrap_or_else(PoisonError::into_inner); + let path = "/3749-unreadable-generation.exr"; + let source = ExrSource::Bytes(picture_and_depth().into()); + let store = PlaneStore::new(CACHE_BUDGET); + let index = crate::exr_index::get(path, &source).unwrap(); + let asked = Arc::new(AtomicU64::new(0)); + { + let counted = asked.clone(); + set_read_error( + path, + Some(Arc::new(move |_: &[usize]| { + counted.fetch_add(1, Ordering::SeqCst); + Some(crate::exr_read::ReadError::Unreadable("damaged".into())) + })), + ); + } + let red = Want { all: false, ids: [0].into_iter().collect() }; + let unreadable = |want: &Want| matches!(store.get(path, &source, &index, want, Use::Other), Err(Refused::Unreadable)); + assert!(unreadable(&red)); + // (figures under the fixed floor: only the change counts, no other test's limit moves) + effectcraft_render::memory::set_decode_limit(Some(1000)); + effectcraft_render::memory::set_decode_limit(Some(2000)); + assert!(unreadable(&red)); + assert_eq!(asked.load(Ordering::SeqCst), 1, "remembered across the change"); + // Another request fails under the new limit: the first refusal is still remembered. + assert!(unreadable(&Want { all: false, ids: [4].into_iter().collect() })); + assert!(unreadable(&red)); + assert_eq!(asked.load(Ordering::SeqCst), 2, "only the other request was read"); + effectcraft_render::memory::set_decode_limit(None); + set_read_error(path, None); +} + +/// A two-rank Cryptomatte file of `size` with a picture: "cube" and "sphere" meet along a +/// diagonal whose pixels hold both IDs (rank 00 the nearer, 55-75 %, rank 01 the other one with +/// the rest), IDs and coverage stored as 32-bit floats. +fn crypto_edges(size: (usize, usize)) -> Vec { + use effectcraft_raster::channels3d::{crypto_float, crypto_hash}; + let (w, h) = size; + let (cube, sphere) = (crypto_float(crypto_hash("cube")), crypto_float(crypto_hash("sphere"))); + let mut ch: Vec> = vec![vec![0.0; w * h]; 4]; + for y in 0..h { + for x in 0..w { + let i = y * w + x; + let d = x as f64 + 0.7 * y as f64 - w as f64 * 0.6; + let edge = d.abs() < 1.5; + let (first, second) = if d < 0.0 { (cube, sphere) } else { (sphere, cube) }; + let c = if edge { 0.55 + 0.1 * ((x * 3 + y) % 3) as f32 } else { 1.0 }; + ch[0][i] = first; + ch[1][i] = c; + ch[2][i] = if edge { second } else { 0.0 }; + ch[3][i] = if edge { 1.0 - c } else { 0.0 }; + } + } + let mut list: Vec> = ["CryptoObject00.R", "CryptoObject00.G", "CryptoObject00.B", "CryptoObject00.A"] + .iter() + .zip(ch) + .map(|(n, v)| AnyChannel::new(*n, FlatSamples::F32(v))) + .collect(); + for c in ["R", "G", "B", "A"] { + list.push(AnyChannel::new(c, FlatSamples::F16(vec![f16::from_f32(0.5); w * h]))); + } + let encoding = Encoding { compression: Compression::ZIP1, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing }; + write(vec![Layer::new(size, LayerAttributes::default(), encoding, AnyChannels::sort(list.into()))], size) +} + +/// The effects' view of a footage layer's channels (tests). +struct ChannelsHost(Arc); + +impl effectcraft_effects::EffectHost for ChannelsHost { + fn layer(&self, _: u64, _: bool) -> Option { + None + } + fn audio(&self, _: u64, _: f64, _: usize, _: u32) -> Option> { + None + } + fn aux(&self) -> Option> { + Some(self.0.clone()) + } +} + +/// #3334, on an OpenEXR written here and read through the pool: Cryptomatte at half resolution +/// is the full-resolution output box-filtered down (2 × 2 pixels averaged, bit for bit), along +/// edges where two IDs share a pixel; the channels the effect reads are the same set for every +/// request of the frame (the GPU keeps its matte by them). +#[test] +fn cryptomatte_at_half_resolution_is_the_full_resolution_matte_box_filtered() { + let size = (23usize, 17usize); + let file = Temp::new("crypto-half", &crypto_edges(size)); + let f = crate::probe(&file.0).unwrap(); + let pool = crate::MediaPool::new(); + let need = AuxNeed::All; + let aux = pool.aux_for(ItemId(1), &f, Tick::ZERO, &need).unwrap(); + assert!(Arc::ptr_eq(&aux, &pool.aux_for(ItemId(1), &f, Tick::ZERO, &need).unwrap()), "the same channels for the frame"); + assert_eq!(aux.crypto_rank_planes("CryptoObject").len(), 2); + let host = ChannelsHost(aux); + let spec = effectcraft_effects::find("ec.3d.cryptomatte").unwrap(); + let layer = [size.0 as f64, size.1 as f64]; + let mut params = + effectcraft_effects::Params { values: spec.params.iter().map(|ps| (ps.id.to_string(), effectcraft_effects::default_value(ps, layer))).collect() }; + params.values.insert("selection".into(), effectcraft_project::Value::Str("cube".into())); + params.values.insert("matteOnly".into(), effectcraft_project::Value::Bool(true)); + let run = |k: u32| { + let ctx = effectcraft_effects::EffectCtx { + params: ¶ms, + time: 0.0, + layer_size: layer, + seed: 0, + adjustment: false, + env: effectcraft_effects::EffectEnv { host: Some(&host), ..Default::default() }, + }; + let (w, h) = ((size.0 as u32).div_ceil(k), (size.1 as u32).div_ceil(k)); + (spec.render)(&ctx, effectcraft_effects::Buf { img: Image::filled(w, h, [1.0; 4]), offset: [0.0; 2], scale: 1.0 / k as f64 }).img + }; + let (full, half) = (run(1), run(2)); + let mut partial = 0; + for y in 0..half.height { + for x in 0..half.width { + let mut sum = 0.0f64; + for sy in y * 2..y * 2 + 2 { + for sx in x * 2..x * 2 + 2 { + if sx < full.width && sy < full.height { + sum += full.get(sx as i64, sy as i64)[0] as f64; + } + } + } + let m = (sum / 4.0) as f32; + assert_eq!(half.get(x as i64, y as i64), [m, m, m, 1.0], "pixel {x}, {y}"); + partial += usize::from(m > 0.0 && m < 1.0); + } + } + assert!(partial > 4, "edges: {partial}"); +} + +/// #3334: a warm frame checks its file's identity on disk at most once: repeated requests for +/// the channels within the stamp's lifetime use the identity read before, and Reload Footage +/// (forget) reads it again. +#[test] +fn a_warm_frame_checks_its_file_at_most_once() { + /// Removes the folder when dropped, also when an assertion fails. + struct TempDir(std::path::PathBuf); + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let dir = std::env::temp_dir().join(format!("ec-3334-stamps-{}", std::process::id())); + // (a run that stopped before its cleanup left the folder: start from an empty one) + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let _cleanup = TempDir(dir.clone()); + let file = dir.join("crypto_0001.exr"); + std::fs::write(&file, crypto_edges((8, 8))).unwrap(); + let f = crate::probe(&file).unwrap(); + let pool = crate::MediaPool::new(); + let need = AuxNeed::All; + pool.aux_for(ItemId(1), &f, Tick::ZERO, &need).unwrap(); + let started = std::time::Instant::now(); + let before = crate::stamp_checks_under(&dir); + for _ in 0..8 { + pool.aux_for(ItemId(1), &f, Tick::ZERO, &need).unwrap(); + pool.aux(ItemId(1), &f, Tick::ZERO).unwrap(); + } + let checks = crate::stamp_checks_under(&dir) - before; + // (a slow machine may cross the stamp's lifetime once meanwhile) + let lifetimes = (started.elapsed().as_secs_f64() / crate::exr_read::STAMP_TTL.as_secs_f64()).ceil() as usize; + assert!(checks <= lifetimes.max(1), "{checks} identity checks for 16 requests"); + assert!(crate::exr_read::stamp_kept(&file)); + // Reload Footage: the identity read goes with the index; the file is read again at once. + pool.forget(&f.path); + assert!(!crate::exr_read::stamp_kept(&file), "forgotten"); + std::fs::write(&file, crypto_edges((8, 9))).unwrap(); + let again = pool.aux_for(ItemId(1), &f, Tick::ZERO, &need).unwrap(); + assert_eq!(again.height, 9, "the new file"); +} diff --git a/crates/media/src/exr_read.rs b/crates/media/src/exr_read.rs new file mode 100644 index 000000000..71a3d4b82 --- /dev/null +++ b/crates/media/src/exr_read.rs @@ -0,0 +1,333 @@ +//! The OpenEXR reader (#3271): where a file's bytes come from ([`ExrSource`], its identity and +//! how it is opened) and the app's side of a read ([`ReadRequest`] of the index's channels, the +//! memory one read may take, cancellation and the errors shown). The reading itself is +//! `craft-exr`'s ([`craft_exr::seek`]): +//! +//! - **No whole-file read.** A request reads the headers it is given ([`ExrIndex`]) and then +//! exactly the bytes of the chunks it needs; a multi-part file's other parts are never read. +//! - **Rows and levels.** A request names display rows and a level (every 2^level-th row and +//! column). With one scan line per chunk (NONE, RLE, ZIPS) a chunk is a line and the lines not +//! needed are not read or decompressed; with larger chunks (ZIP, PIZ, DWA, tiles) whole chunks +//! are skipped and the rows within a chunk are only skipped when converting. +//! - **Cancellable** while chunks are read ([`filmcraft_media::cancel::cancelled`]). +//! - **Bit-identical** to the high-level reader: the same decompression, each line clipped to +//! the display window, the fill value outside the data window, `u32` samples as `f32`. + +use std::io::{Read, Seek}; +use std::ops::Range; +use std::sync::Arc; + +use craft_exr::seek; +use effectcraft_render::reads::FileStamp; + +use crate::exr_index::ExrIndex; + +/// A source to read an OpenEXR file from: in-memory bytes or a file on disk. +pub(crate) trait ReadSeek: Read + Seek + Send {} +impl ReadSeek for T {} + +/// Where an OpenEXR file's bytes come from. +#[derive(Clone, Debug)] +pub(crate) enum ExrSource { + /// Registered in memory (`MediaPool::add_bytes`, web builds, tests). + Bytes(Arc<[u8]>), + /// A file, opened for each read and read in place. + File(std::path::PathBuf), + /// A network file read from its verified local copy ([`crate::localize`]): it opens the + /// copy, but its identity (and every entry made of it) is the original's. + Localized { original: std::path::PathBuf, copy: std::path::PathBuf, stamp: FileStamp }, +} + +/// An opened [`ExrSource`]. +pub(crate) struct Opened { + pub(crate) reader: Box, + pub(crate) stamp: FileStamp, +} + +/// How long a file's identity, once read, stands for it ([`recent_stamp`], #3334): every request +/// for a file's channels checked it, one or two `fs::metadata` calls each (1–7 ms on a network +/// share), several per frame. A file rewritten in place is seen at most this late; Reload Footage +/// forgets it at once ([`forget_stamp`]). +pub(crate) const STAMP_TTL: std::time::Duration = std::time::Duration::from_secs(1); + +/// At most this many files' identities are remembered (the oldest checks go first). +#[cfg(not(target_arch = "wasm32"))] +const STAMPS_KEPT: usize = 4096; + +#[cfg(not(target_arch = "wasm32"))] +type Stamps = std::collections::HashMap; + +#[cfg(not(target_arch = "wasm32"))] +fn stamps() -> std::sync::MutexGuard<'static, Stamps> { + static STAMPS: std::sync::OnceLock> = std::sync::OnceLock::new(); + STAMPS.get_or_init(Default::default).lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// [`recent_stamp`] in the browser: no clock there (and no files, only registered bytes). +#[cfg(target_arch = "wasm32")] +pub(crate) fn recent_stamp(path: &std::path::Path) -> std::io::Result { + std::fs::metadata(path).map(|m| FileStamp::of_metadata(&m)) +} + +/// The identity of the file at `path` (size and modification time): as read within the last +/// [`STAMP_TTL`], else read now. A file that can't be read is asked again every time. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn recent_stamp(path: &std::path::Path) -> std::io::Result { + let now = std::time::Instant::now(); + if let Some((stamp, at)) = stamps().get(path) + && now.saturating_duration_since(*at) < STAMP_TTL + { + return Ok(*stamp); + } + #[cfg(test)] + crate::count_stamp(path); + let stamp = std::fs::metadata(path).map(|m| FileStamp::of_metadata(&m))?; + note_stamp(path, stamp, now); + Ok(stamp) +} + +/// Remember `stamp` as the identity of the file at `path` read at `at` (a file just opened). +#[cfg(not(target_arch = "wasm32"))] +fn note_stamp(path: &std::path::Path, stamp: FileStamp, at: std::time::Instant) { + let mut s = stamps(); + if s.len() >= STAMPS_KEPT && !s.contains_key(path) { + s.retain(|_, (_, t)| at.saturating_duration_since(*t) < STAMP_TTL); + if s.len() >= STAMPS_KEPT { + s.clear(); + } + } + s.insert(path.to_path_buf(), (stamp, at)); +} + +/// Forget the identity read of the file at `path` (Reload Footage: the next request reads it). +pub(crate) fn forget_stamp(path: &std::path::Path) { + #[cfg(not(target_arch = "wasm32"))] + stamps().remove(path); + #[cfg(target_arch = "wasm32")] + let _ = path; +} + +/// Whether the identity of the file at `path` is remembered (tests). +#[cfg(test)] +pub(crate) fn stamp_kept(path: &std::path::Path) -> bool { + stamps().contains_key(path) +} + +impl ExrSource { + /// Its identity (a file's size and modification time), without opening it: a file's as read + /// within the last [`STAMP_TTL`] ([`recent_stamp`]); a localized file's as it was when its + /// verified copy was chosen (moments ago: [`recent_stamp`] too). + pub(crate) fn stamp(&self) -> std::io::Result { + match self { + ExrSource::Bytes(_) => Ok(FileStamp::Virtual), + ExrSource::File(path) => recent_stamp(path), + ExrSource::Localized { stamp, .. } => Ok(*stamp), + } + } + + /// The file was just opened and found to be `stamp`: later checks within [`STAMP_TTL`] use it. + pub(crate) fn opened_as(&self, stamp: FileStamp) { + #[cfg(not(target_arch = "wasm32"))] + if let ExrSource::File(path) = self { + note_stamp(path, stamp, std::time::Instant::now()); + } + #[cfg(target_arch = "wasm32")] + let _ = stamp; + } + + /// Open it: a file only when it is a regular file (a project can name `/dev/zero` or a FIFO, + /// #2134), with its identity from the open file. + pub(crate) fn open(&self) -> std::io::Result { + match self { + ExrSource::Bytes(b) => Ok(Opened { reader: Box::new(std::io::Cursor::new(b.clone())), stamp: FileStamp::Virtual }), + ExrSource::File(path) => { + #[cfg(test)] + crate::count_open(path); + 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!("{} is not a file", path.display()))); + } + Ok(Opened { stamp: FileStamp::of_metadata(&meta), reader: Box::new(file) }) + } + ExrSource::Localized { original, copy, stamp } => { + let local = || -> std::io::Result { + #[cfg(test)] + crate::count_open(copy); + let file = std::fs::File::open(copy)?; + let meta = file.metadata()?; + // (the copy must still be complete: its size is the original's) + let complete = matches!(stamp, FileStamp::Native { len, .. } if *len == meta.len()); + if !meta.is_file() || !complete { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("{}: not a complete copy", copy.display()))); + } + Ok(Opened { stamp: *stamp, reader: Box::new(file) }) + }; + // (a copy evicted or damaged meanwhile: the share) + local().or_else(|_| ExrSource::File(original.clone()).open()) + } + } + } +} + +/// What to read: channels (indices into [`ExrIndex::channels`]), display rows, and a level. +#[derive(Clone, Debug)] +pub(crate) struct ReadRequest { + pub(crate) channels: Vec, + /// Rows of the display window (full resolution); `None`: all. + pub(crate) rows: Option>, + /// Every 2^level-th row and column of the display window (0: full resolution). + pub(crate) level: u32, + /// The most bytes of planes the read may allocate (the caller's own limit; `usize::MAX`: only + /// the system's, [`effectcraft_render::memory::decode_limit`]). + pub(crate) max_bytes: usize, + /// The fixed limit the system's memory may raise ([`MAX_DECODE_BYTES`]). + pub(crate) floor: usize, +} + +impl ReadRequest { + /// Every row of `channels` at full resolution. + pub(crate) fn full(channels: Vec) -> ReadRequest { + ReadRequest { channels, rows: None, level: 0, max_bytes: usize::MAX, floor: MAX_DECODE_BYTES } + } +} + +/// What a read did, for measurements and tests. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct ReadStats { + /// Chunks fetched, per part. + pub(crate) chunks: Vec, + /// Bytes of chunks read from the source. + pub(crate) bytes: u64, + /// Scan lines decompressed (rows of the chunks fetched). + pub(crate) lines: usize, +} + +/// Why a read gave no planes. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum ReadError { + /// A chunk can't be decompressed, or the file doesn't hold it. + Unreadable(String), + /// Reading the file failed just now (a seek or read error, no memory for a chunk): another + /// read may succeed. + Io(String), + /// The planes need more memory than one read may allocate (the reason, to show). + TooLarge(String), + /// The system refused the memory the planes need just now (the reason, to show): not a file + /// too large, but not to be asked again at once either (#3749). + OutOfMemory(String), + /// The request was called off. + Cancelled, +} + +/// The most bytes of planes one read allocates at least (every requested channel is a +/// display-window plane of f32): a header can ask for far more than the file holds, and a file's +/// size on disk says nothing about it. With more memory in the machine the limit is higher +/// ([`effectcraft_render::memory::decode_limit`], #3749). +#[cfg(target_pointer_width = "64")] +pub(crate) const MAX_DECODE_BYTES: usize = 8 << 30; +#[cfg(not(target_pointer_width = "64"))] +pub(crate) const MAX_DECODE_BYTES: usize = 512 << 20; + +/// The tests that move the process-wide decode limit, or rely on it, take turns (it also dates +/// the remembered refusals). +#[cfg(test)] +pub(crate) static LIMIT_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// What a failed `craft-exr` read means here. Memory the system refused just now is +/// [`ReadError::OutOfMemory`]: the plane store doesn't remember it (another request may +/// succeed), but doesn't read it again at once nor fall back to decoding the whole file +/// either; a file too large is remembered until the file or the limit changes. +pub(crate) fn read_error(e: seek::Error) -> ReadError { + match e { + seek::Error::Cancelled => ReadError::Cancelled, + seek::Error::Io(why) => ReadError::Io(why), + seek::Error::OutOfMemory(why) => ReadError::OutOfMemory(format!("its OpenEXR channels need more memory than the system can give just now ({why})")), + seek::Error::LimitExceeded(why) => ReadError::TooLarge(format!("its OpenEXR channels need more memory than one file may use ({why})")), + seek::Error::Malformed(why) | seek::Error::Unsupported(why) | seek::Error::UnsupportedCompression(why) => ReadError::Unreadable(why), + other => ReadError::Unreadable(other.to_string()), + } +} + +/// The most bytes one decompressed block of a read may take, whatever the read's limit +/// ([`MAX_DECODE_BYTES`]: 8 GiB, 512 MiB in the browser): the decompressor allocates a block +/// whole before it looks at the data, and a block is one strip of the file, so a larger one is a +/// damaged or hostile header, not a file with more channels (#3749). A refusal for it doesn't +/// depend on the limit: a request asking at least as much, refused for it before, would be again. +pub(crate) const MAX_BLOCK_BYTES: usize = MAX_DECODE_BYTES; + +/// The most threads one read decompresses on (beside the caller's), and the size of a file +/// whose chunks are decompressed on the calling thread alone. +const READ_WORKERS: usize = 4; +const SMALL_FILE: u64 = 1 << 20; + +/// The size of the planes of a read at `level` of a `w` × `h` display window. +#[cfg(test)] +pub(crate) fn level_size(size: (usize, usize), level: u32) -> (usize, usize) { + seek::level_size(size, level) +} + +/// Read `req` from `src` (the file `index` describes): one plane per requested channel, in +/// request order, covering the display window at the request's level (the channel's fill value +/// where the file has no samples or the request no rows). The stats are a failed read's +/// defaults: `craft-exr` reports none for it. +pub(crate) fn read_planes(src: &mut dyn ReadSeek, index: &ExrIndex, req: &ReadRequest) -> (Result>, ReadError>, ReadStats) { + match read(src, index, req) { + Ok((planes, stats)) => (Ok(planes), stats), + Err(e) => (Err(e), ReadStats { chunks: vec![0; index.file.parts().len()], ..Default::default() }), + } +} + +fn gb(bytes: usize) -> f64 { + bytes as f64 / f64::from(1u32 << 30) +} + +fn too_large(w: usize, h: usize, need: usize, most: usize) -> ReadError { + ReadError::TooLarge(format!("its {}×{} OpenEXR channels need {:.1} GB of memory, more than the {:.1} GB one file may use", w, h, gb(need), gb(most))) +} + +/// Refuse a request whose planes together, those already in hand (held in memory or read back +/// from the disk cache) and those still to read, `planes` of a `w` × `h` display window, need +/// more memory than one file may use: the limit is for what a file's request ends with, not +/// for the part of it read just now ([`effectcraft_render::memory::decode_limit`], #3749). +pub(crate) fn check_total(w: usize, h: usize, planes: usize, max_bytes: usize) -> Result<(), ReadError> { + let need = w.saturating_mul(h).saturating_mul(planes).saturating_mul(std::mem::size_of::()); + let most = max_bytes.min(effectcraft_render::memory::decode_limit(MAX_DECODE_BYTES, need)); + if need > most { + return Err(too_large(w, h, need, most)); + } + Ok(()) +} + +fn read(src: &mut dyn ReadSeek, index: &ExrIndex, req: &ReadRequest) -> Result<(Vec>, ReadStats), ReadError> { + let (w, h) = index.size(); + let (ow, oh) = seek::level_size((w, h), req.level.min(16)); + let n = ow.checked_mul(oh).ok_or_else(|| ReadError::Unreadable("display window".into()))?; + let need = n.saturating_mul(req.channels.len()).saturating_mul(std::mem::size_of::()); + // (the limit is decided here and handed to `craft-exr` as the read's `max_bytes`: the planes + // it reserves, fallibly, follow it; one decompressed block stays at the fixed floor however + // much memory the machine has, see `MAX_BLOCK_BYTES`) + let most = req.max_bytes.min(effectcraft_render::memory::decode_limit(req.floor, need)); + if need > most { + return Err(too_large(w, h, need, most)); + } + let mut channels = Vec::with_capacity(req.channels.len()); + let mut fill = Vec::with_capacity(req.channels.len()); + for id in &req.channels { + let c = index.channels.get(*id).ok_or_else(|| ReadError::Unreadable("no such channel".into()))?; + channels.push((c.part, c.channel)); + fill.push(c.fill); + } + let mut request = seek::Request::new(&channels, most); + request.fill = &fill; + request.rows = req.rows.clone(); + request.level = req.level; + request.max_block_bytes = Some(MAX_BLOCK_BYTES); + // craft-exr decompresses on threads of its own, started for this read, beside the decode + // pool the caller runs on: a few at most, and none for a small file (its chunks are + // decompressed on the calling thread). + request.workers = Some(if index.file.file_len() < SMALL_FILE { 0 } else { rayon::current_num_threads().min(READ_WORKERS) }); + let planes = seek::read_planes(src, &index.file, &request, &filmcraft_media::cancel::cancelled).map_err(read_error)?; + let stats = ReadStats { chunks: planes.stats.chunks, bytes: planes.stats.bytes, lines: planes.stats.lines }; + Ok((planes.planes, stats)) +} diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index 7eff0e9cf..7e0c24b88 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -21,8 +21,12 @@ mod convert; pub mod downmix; mod dpx; pub mod exr_channels; +mod exr_index; +mod exr_planes; +mod exr_read; mod gif_anim; mod layered; +mod localize; mod pcraft; pub use layered::vector_doc; mod pool; @@ -38,7 +42,7 @@ pub use pool::{DEFAULT_BUDGET, MediaPool, PoolStats}; pub use probe::{DEFAULT_SEQUENCE_RATE, probe, probe_bytes, probe_model, probe_noting}; /// Errors from probing or decoding footage. -#[derive(Debug, thiserror::Error)] +#[derive(Clone, Debug, thiserror::Error)] pub enum MediaError { #[error("I/O error: {0}")] Io(String), @@ -142,6 +146,21 @@ pub(crate) fn opens_under(dir: &std::path::Path) -> usize { OPENS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).iter().filter(|p| p.starts_with(dir)).count() } +#[cfg(test)] +static STAMP_CHECKS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Count a check of a file's identity on disk (tests, #3334). +#[cfg(test)] +pub(crate) fn count_stamp(path: &std::path::Path) { + STAMP_CHECKS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(path.to_path_buf()); +} + +/// How many times the identity of files under `dir` was checked on disk so far (tests). +#[cfg(test)] +pub(crate) fn stamp_checks_under(dir: &std::path::Path) -> usize { + STAMP_CHECKS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).iter().filter(|p| p.starts_with(dir)).count() +} + pub(crate) fn ext_of(path: &std::path::Path) -> String { path.extension().and_then(std::ffi::OsStr::to_str).unwrap_or("").to_ascii_lowercase() } diff --git a/crates/media/src/localize.rs b/crates/media/src/localize.rs new file mode 100644 index 000000000..f6d969c00 --- /dev/null +++ b/crates/media/src/localize.rs @@ -0,0 +1,954 @@ +//! The background footage localizer (#3271, Settings ▸ Disk ▸ Localize Network Footage, off by +//! default): footage on a network share is copied, file by file, to a local folder while the +//! user works, so later reads come from the local disk. +//! +//! - **Network footage**: UNC paths (`\\server\share\…`) and the locations the user lists +//! (Settings ▸ Disk ▸ Network Footage Locations, such as a drive letter mapped to a share, +//! `P:\`). No system call is made to tell a mapped drive apart. +//! - **Never on the playback path.** A read asks for a copy ([`request`]) and goes on reading +//! the share; one background thread copies, one file at a time. +//! - **Used only when complete and verified.** A copy is made under a temporary name (`.part`), +//! renamed when complete, and recorded beside it (`.src`: the source's path and identity when +//! it was copied). It is read only while the source still has that identity and the copy its +//! size ([`local_copy`]); a source that changed is read from the share (and copied again). +//! - **Readers keep naming the source.** Entries made of a localized file list the share's path +//! and identity (see `ExrSource::Localized`), so caches are keyed the same either way. +//! - **Bounded, across sessions.** The copies take at most the size limit and leave the disk +//! cache's reserve free on their disk ([`effectcraft_render::disk_cache::disk_reserve`]); the +//! least recently used go first. The folder's copies are adopted when the localizer starts +//! (and stale temporaries deleted), so they count towards the limit after a restart. +//! - **Visible.** [`status`] says how many files are local, their size, what is queued, what is +//! being copied and which locations count as network. + +use std::collections::{HashMap, HashSet, VecDeque}; +use std::path::{Path, PathBuf}; +use std::sync::{Condvar, Mutex, PoisonError}; + +use effectcraft_render::reads::FileStamp; +use effectcraft_render::{LocalizeConfig, LocalizeReport}; + +/// A complete local copy. +struct Copy { + local: PathBuf, + /// The copy's size and the source's identity when it was copied. + len: u64, + source: FileStamp, + last_use: u64, +} + +#[derive(Default)] +struct State { + config: Option, + copies: HashMap, + queue: VecDeque, + queued: HashSet, + bytes: u64, + clock: u64, + /// The file being copied now and the setting ([`State::epoch`]) it is copied under: asked + /// for again meanwhile it isn't queued a second time (unless the setting changed since). + copying: Option<(PathBuf, u64)>, + skipped: HashSet, + worker: bool, + /// Bumped with each new setting: a copy started under another one is thrown away. + epoch: u64, + /// The free space seen last on the copies' disk, when (read at most every 30 s) and how many + /// bytes the copies took then: what they took more or less since is what the disk gained + /// or lost since, so the reading is not stale ([`limit`]). + space: Option<((u64, u64), std::time::Instant, u64)>, + /// The limit is held below the setting by free disk space. + reserve_limited: bool, + /// Folders being adopted now ([`configure`]): the worker starts no copy meanwhile (a copy + /// already running is left alone by the scan, see [`adopt`]). + adopting: u32, +} + +/// At most this many files wait to be copied (older requests are dropped first). +const QUEUE_LIMIT: usize = 4096; + +fn state() -> &'static (Mutex, Condvar) { + static STATE: std::sync::OnceLock<(Mutex, Condvar)> = std::sync::OnceLock::new(); + STATE.get_or_init(Default::default) +} + +fn lock() -> std::sync::MutexGuard<'static, State> { + state().0.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// The settings that decide what is copied where (the free-space reader aside). +fn same(a: Option<&LocalizeConfig>, b: Option<&LocalizeConfig>) -> bool { + match (a, b) { + (None, None) => true, + (Some(a), Some(b)) => a.folder == b.folder && a.max_bytes == b.max_bytes && a.network == b.network, + _ => false, + } +} + +/// Turn the localizer on with `config`, or off (`None`): the copies stay on disk but are no +/// longer read. A new folder's earlier copies are adopted (their records beside them), stale +/// temporaries deleted. +pub fn configure(config: Option) { + // (the file system is read and written outside the lock: reads ask the localizer for copies + // on every frame, and a slow folder must not hold them up) + let (epoch, adopt_from, space_of) = { + let mut st = lock(); + if same(st.config.as_ref(), config.as_ref()) { + if let Some(c) = config { + st.config = Some(c); + } + return; + } + st.epoch = st.epoch.wrapping_add(1); + let new_folder = st.config.as_ref().map(|c| &c.folder) != config.as_ref().map(|c| &c.folder); + st.queue.clear(); + st.queued.clear(); + st.skipped.clear(); + st.space = None; + st.config = config; + if new_folder { + st.copies.clear(); + st.bytes = 0; + } + let adopt_from = st.config.as_ref().filter(|_| new_folder).map(|c| c.folder.clone()); + if adopt_from.is_some() { + st.adopting = st.adopting.saturating_add(1); + } + // (the file being copied now keeps its files: its copy may land in this folder) + let busy = st.copying.as_ref().map(|(p, _)| local_name(p)); + (st.epoch, adopt_from.map(|f| (f, busy)), st.config.as_ref().and_then(|c| c.disk_space.clone())) + }; + // (ends the adoption also when the scan or the free-space reader panics) + let guard = adopt_from.is_some().then_some(Adopting); + #[cfg(test)] + let scanned = adopt_from.as_ref().map(|(f, _)| f.clone()); + let found = adopt_from.map(|(f, busy)| adopt(&f, busy.as_deref())).unwrap_or_default(); + let space = space_of.and_then(|read| read()); + #[cfg(test)] + { + let hook = AFTER_ADOPT.lock().unwrap_or_else(PoisonError::into_inner).clone(); + if let (Some(h), Some(f)) = (hook, scanned) { + h(&f); + } + } + let gone = { + let mut st = lock(); + // (set again meanwhile: that setting's call does the work) + if st.epoch != epoch { + return; + } + for (original, copy) in found { + // (a copy made meanwhile is the current one: never counted twice) + if st.copies.contains_key(&original) { + continue; + } + st.clock += 1; + st.bytes = st.bytes.saturating_add(copy.len); + let last_use = st.clock; + st.copies.insert(original, Copy { last_use, ..copy }); + } + if let Some(space) = space { + // (read after the scan: the adopted copies were on the disk already) + let bytes = st.bytes; + st.space = Some((space, std::time::Instant::now(), bytes)); + } + let max = limit(&mut st); + evict_to(&mut st, max, &HashSet::new()) + }; + // (released only now: until the adopted copies and the free-space reading are published, a + // copy made meanwhile would be counted into a reading taken before it, or admitted against a + // total that misses the adopted files; #3301 review. The guard wakes the worker under the + // lock, so it is dropped after the block's lock is released) + drop(guard); + delete_evicted(gone, epoch); +} + +/// The copies' record beside a copy. +fn record_path(local: &Path) -> PathBuf { + let mut p = local.as_os_str().to_owned(); + p.push(".src"); + PathBuf::from(p) +} + +/// A record's text: the source's path, size and modification time (ns, or `-`), the copy's size. +fn record(original: &Path, source: &FileStamp, len: u64) -> Option { + let FileStamp::Native { len: slen, modified } = source else { return None }; + let modified = modified.map_or("-".to_string(), |m| m.to_string()); + Some(format!("{}\n{slen}\n{modified}\n{len}\n", original.to_string_lossy())) +} + +fn parse_record(text: &str) -> Option<(PathBuf, FileStamp, u64)> { + let mut lines = text.lines(); + let original = PathBuf::from(lines.next()?); + let slen = lines.next()?.parse().ok()?; + let modified = match lines.next()? { + "-" => None, + m => Some(m.parse().ok()?), + }; + let len = lines.next()?.parse().ok()?; + Some((original, FileStamp::Native { len: slen, modified }, len)) +} + +/// Is `name` one of the localizer's own files (`<16 hex>_…`). +fn ours(name: &str) -> bool { + name.len() > 17 && name.as_bytes().get(16) == Some(&b'_') && name.get(..16).is_some_and(|h| h.bytes().all(|b| b.is_ascii_hexdigit())) +} + +/// Ends an adoption ([`State::adopting`]) when dropped. +struct Adopting; + +impl Drop for Adopting { + fn drop(&mut self) { + let mut st = lock(); + st.adopting = st.adopting.saturating_sub(1); + state().1.notify_all(); + } +} + +/// The copies `folder` holds from an earlier session, by source; temporaries, records without +/// their copy and copies without a record are deleted (a copy renamed into place whose record +/// was never written, #3301 review: nothing else would ever delete it, and the size limit +/// didn't count it). Only the localizer's own files: other files in the folder are left alone, +/// and those of `busy`, the copy being made now. Runs without the localizer's lock. +fn adopt(folder: &Path, busy: Option<&str>) -> Vec<(PathBuf, Copy)> { + #[cfg(test)] + { + let hook = BEFORE_ADOPT.lock().unwrap_or_else(PoisonError::into_inner).clone(); + if let Some(h) = hook { + h(folder); + } + } + let mut found = vec![]; + let Ok(dir) = std::fs::read_dir(folder) else { return found }; + let mut records = vec![]; + let mut copies = vec![]; + for e in dir.flatten() { + let name = e.file_name().to_string_lossy().to_string(); + if !ours(&name) || busy.is_some_and(|b| name.starts_with(b)) { + continue; + } + if name.ends_with(".part") { + let _ = std::fs::remove_file(e.path()); + } else if name.ends_with(".src") { + records.push(e.path()); + } else if e.file_type().is_ok_and(|t| t.is_file()) { + copies.push(e.path()); + } + } + let recorded: std::collections::HashSet = records.iter().map(|r| r.with_extension("")).collect(); + for copy in copies.iter().filter(|c| !recorded.contains(*c)) { + let _ = std::fs::remove_file(copy); + } + for rec in records { + let local = rec.with_extension(""); + let parsed = std::fs::read_to_string(&rec).ok().and_then(|t| parse_record(&t)); + let fine = parsed.as_ref().is_some_and(|(_, _, len)| std::fs::metadata(&local).is_ok_and(|m| m.is_file() && m.len() == *len)); + match parsed { + Some((original, source, len)) if fine => found.push((original, Copy { local, len, source, last_use: 0 })), + // (a copy that can't be deleted keeps its record, and is looked at again next time) + _ => { + remove_copy(&local); + } + } + } + found +} + +/// What the localizer is doing; `None` when it is off. +pub fn status() -> Option { + let st = lock(); + let c = st.config.as_ref()?; + Some(LocalizeReport { + files: st.copies.len(), + bytes: st.bytes, + max_bytes: c.max_bytes, + queued: st.queue.len(), + copying: st.copying.as_ref().map(|(p, _)| p.to_string_lossy().to_string()), + skipped: st.skipped.len(), + network: c.network.iter().map(|p| p.to_string_lossy().to_string()).collect(), + reserve_limited: st.reserve_limited, + }) +} + +/// Paths under these roots count as network footage (tests: a local folder standing in for a +/// share). +#[cfg(test)] +static NETWORK_ROOTS: Mutex> = Mutex::new(Vec::new()); + +#[cfg(test)] +pub(crate) fn treat_as_network(root: &Path) { + NETWORK_ROOTS.lock().unwrap_or_else(PoisonError::into_inner).push(root.to_path_buf()); +} + +/// `path` lies under `prefix` (separators and, on Windows, letter case don't matter). +fn under(path: &Path, prefix: &Path) -> bool { + let norm = |p: &Path| { + let s = p.to_string_lossy().replace('\\', "/"); + if cfg!(windows) { s.to_lowercase() } else { s } + }; + let (p, pre) = (norm(path), norm(prefix)); + let pre = pre.trim_end_matches('/'); + !pre.is_empty() && (p == pre || p.starts_with(&format!("{pre}/"))) +} + +/// Is `path` network footage: a UNC path (`\\server\share\…`, `//server/share/…`), or under one +/// of the locations the localizer is given (`P:\`). +pub(crate) fn is_network(path: &Path) -> bool { + #[cfg(test)] + if NETWORK_ROOTS.lock().unwrap_or_else(PoisonError::into_inner).iter().any(|r| path.starts_with(r)) { + return true; + } + let s = path.to_string_lossy(); + if s.starts_with("\\\\") || s.starts_with("//") { + return true; + } + lock().config.as_ref().is_some_and(|c| c.network.iter().any(|n| under(path, n))) +} + +/// Ask for a local copy of the network file `original` (nothing when the localizer is off, the +/// file is local, already copied, queued, being copied under this setting, or skipped). +/// Returns at once. +pub(crate) fn request(original: &Path) { + if !is_network(original) { + return; + } + let mut st = lock(); + let copying = st.copying.as_ref().is_some_and(|(p, epoch)| p == original && *epoch == st.epoch); + if st.config.is_none() || copying || st.copies.contains_key(original) || st.queued.contains(original) || st.skipped.contains(original) { + return; + } + if st.queue.len() >= QUEUE_LIMIT + && let Some(old) = st.queue.pop_front() + { + st.queued.remove(&old); + } + st.queue.push_back(original.to_path_buf()); + st.queued.insert(original.to_path_buf()); + start_worker(&mut st); + state().1.notify_all(); +} + +/// The complete local copy of `original` when its source still has identity `now` (its size and +/// modification time when it was copied) and the copy its size; `None` otherwise (read the +/// source). A copy whose source changed is forgotten (and copied again when asked for). +pub(crate) fn local_copy(original: &Path, now: &FileStamp) -> Option { + let (local, len, source) = { + let st = lock(); + st.config.as_ref()?; + let c = st.copies.get(original)?; + (c.local.clone(), c.len, c.source) + }; + // (the copy is looked at without the lock) + let ok = source == *now && std::fs::metadata(&local).is_ok_and(|m| m.is_file() && m.len() == len); + let mut st = lock(); + st.clock += 1; + let clock = st.clock; + // (the same copy as looked at: it may have been replaced or dropped meanwhile) + let same = st.copies.get(original).is_some_and(|c| c.local == local && c.len == len && c.source == source); + if !same { + return None; + } + if ok { + if let Some(c) = st.copies.get_mut(original) { + c.last_use = clock; + } + return Some(local); + } + let gone = st.copies.remove(original); + if let Some(g) = &gone { + st.bytes = st.bytes.saturating_sub(g.len); + } + let epoch = st.epoch; + drop(st); + if let Some(g) = gone { + delete_evicted(vec![(original.to_path_buf(), g)], epoch); + } + None +} + +/// Delete a copy's file and its record. `false` when the file could not be deleted (open +/// elsewhere, read-only): it is still on the disk, so its record stays (it is adopted again +/// later) and the caller keeps counting its bytes. +fn remove_copy(local: &Path) -> bool { + #[cfg(test)] + if FAIL_REMOVE.lock().unwrap_or_else(PoisonError::into_inner).iter().any(|p| p == local) { + return false; + } + match std::fs::remove_file(local) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return false, + } + let _ = std::fs::remove_file(record_path(local)); + true +} + +/// A copy dropped from the books and the source it was made of. +type Evicted = (PathBuf, Copy); + +/// Delete the files of evicted copies (without the lock). Those that could not be deleted are +/// still on the disk: they go back on the books (their bytes counted again, unless the setting +/// changed since `epoch`); their sources are returned. +fn delete_evicted(victims: Vec, epoch: u64) -> Vec { + let stuck: Vec = victims.into_iter().filter(|(_, c)| !remove_copy(&c.local)).collect(); + if stuck.is_empty() { + return vec![]; + } + let mut st = lock(); + let mut sources = vec![]; + for (original, copy) in stuck { + sources.push(original.clone()); + if st.epoch == epoch && !st.copies.contains_key(&original) { + st.bytes = st.bytes.saturating_add(copy.len); + st.copies.insert(original, copy); + } + } + sources +} + +#[cfg(not(target_arch = "wasm32"))] +fn start_worker(st: &mut State) { + if st.worker { + return; + } + st.worker = std::thread::Builder::new().name("ec-localize".into()).spawn(worker).is_ok(); +} + +/// (no threads in the browser: nothing is copied there) +#[cfg(target_arch = "wasm32")] +fn start_worker(_st: &mut State) {} + +/// The most the copies may take now: the setting, or less when free disk space holds them +/// below it (the disk cache's reserve stays free on their disk; free space is read at most +/// every 30 s). +fn limit(st: &mut State) -> u64 { + let Some(c) = st.config.clone() else { return 0 }; + let fresh = st.space.is_some_and(|(_, at, _)| at.elapsed() < std::time::Duration::from_secs(30)); + if !fresh && let Some(read) = &c.disk_space { + let bytes = st.bytes; + st.space = read().map(|s| (s, std::time::Instant::now(), bytes)); + } + // (free space then, less what the copies took since, plus what they took then: what the + // copies may take; a copy written meanwhile is not free room, a copy evicted is) + let cap = match st.space { + Some(((total, available), _, at_bytes)) if total > 0 => { + at_bytes.saturating_add(available).saturating_sub(effectcraft_render::disk_cache::disk_reserve(total)) + } + _ => u64::MAX, + }; + st.reserve_limited = cap < c.max_bytes; + c.max_bytes.min(cap) +} + +/// Drop the least recently used copies until they take at most `max` bytes; their files, which +/// the caller deletes once it let go of the lock ([`delete_evicted`]). Copies whose source is in +/// `skip` (their files could not be deleted just now) stay. +#[must_use] +fn evict_to(st: &mut State, max: u64, skip: &HashSet) -> Vec { + let mut gone = vec![]; + while st.bytes > max { + let Some(oldest) = st.copies.iter().filter(|(p, _)| !skip.contains(*p)).min_by_key(|(_, c)| c.last_use).map(|(p, _)| p.clone()) else { break }; + if let Some(c) = st.copies.remove(&oldest) { + st.bytes = st.bytes.saturating_sub(c.len); + gone.push((oldest, c)); + } + } + gone +} + +/// The copies' folder name of `original`: a hash of its path, then its file name. +fn local_name(original: &Path) -> String { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + original.hash(&mut h); + let name = original.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + format!("{:016x}_{name}", h.finish()) +} + +/// The copying thread: one file at a time, until the queue is empty for a while. +#[cfg(not(target_arch = "wasm32"))] +fn worker() { + let (m, cv) = state(); + loop { + let (job, config, epoch) = { + let mut st = m.lock().unwrap_or_else(PoisonError::into_inner); + loop { + if st.adopting == 0 + && let (Some(p), Some(c)) = (st.queue.front().cloned(), st.config.clone()) + { + st.queue.pop_front(); + st.queued.remove(&p); + st.copying = Some((p.clone(), st.epoch)); + break (p, c, st.epoch); + } + let (g, timeout) = match cv.wait_timeout(st, std::time::Duration::from_secs(30)) { + Ok(r) => r, + Err(p) => p.into_inner(), + }; + st = g; + if timeout.timed_out() && st.queue.is_empty() { + st.worker = false; + return; + } + } + }; + // Room is made for the incoming file before it is written: the least recently used + // copies go first, so the disk's reserve is never eaten (a file over the limit is skipped). + // A copy whose file can't be deleted stays on the books (its bytes are still on the + // disk); the file is refused when that leaves too little room. + let make_room = |incoming: u64| { + let mut stuck = HashSet::new(); + loop { + let victims = { + let mut st = m.lock().unwrap_or_else(PoisonError::into_inner); + if st.epoch != epoch { + return false; + } + let max = limit(&mut st); + if incoming > max { + return false; + } + let victims = evict_to(&mut st, max - incoming, &stuck); + if victims.is_empty() { + return st.bytes.saturating_add(incoming) <= max; + } + victims + }; + stuck.extend(delete_evicted(victims, epoch)); + } + }; + let copied = copy_file(&job, &config.folder, &make_room); + let mut st = m.lock().unwrap_or_else(PoisonError::into_inner); + st.copying = None; + let mut gone = vec![]; + let mut evicted = vec![]; + match copied { + Some((local, len, source)) if st.epoch == epoch => { + if let Some(old) = st.copies.remove(&job) { + st.bytes = st.bytes.saturating_sub(old.len); + } + st.clock += 1; + let last_use = st.clock; + st.copies.insert(job, Copy { local, len, source, last_use }); + st.bytes = st.bytes.saturating_add(len); + let max = limit(&mut st); + evicted = evict_to(&mut st, max, &HashSet::new()); + } + // (made under an earlier setting: thrown away, unless the folder's adoption took it + // as the current copy meanwhile) + Some((local, _, _)) => { + if !st.copies.get(&job).is_some_and(|c| c.local == local) { + gone.push(local); + } + } + // (only under the setting it was asked for under: a new one asks again) + None if st.epoch == epoch => { + st.skipped.insert(job); + } + None => {} + } + drop(st); + for local in gone { + remove_copy(&local); + } + delete_evicted(evicted, epoch); + } +} + +/// Copy `original` into `folder`: under a temporary name; then an earlier copy of it removed, +/// its record written beside the final name, and the temporary renamed when complete (a crash +/// in between leaves a record without its copy or a temporary, both deleted when the folder is +/// adopted; never a copy without a record, nor old bytes beside a new record); its +/// modification time set to the source's. The copy, its size and the +/// source's identity, or `None` (`make_room` refused its size, unreadable, or changed while it +/// was copied). `make_room` is asked, with the file's size, before anything is written. +#[cfg(not(target_arch = "wasm32"))] +fn copy_file(original: &Path, folder: &Path, make_room: &dyn Fn(u64) -> bool) -> Option<(PathBuf, u64, FileStamp)> { + #[cfg(test)] + { + let hook = BEFORE_COPY.lock().unwrap_or_else(PoisonError::into_inner).clone(); + if let Some(h) = hook { + h(original); + } + } + let meta = std::fs::metadata(original).ok().filter(std::fs::Metadata::is_file)?; + if !make_room(meta.len()) { + return None; + } + let before = FileStamp::of_metadata(&meta); + std::fs::create_dir_all(folder).ok()?; + let local = folder.join(local_name(original)); + let tmp = folder.join(format!("{}.part", local_name(original))); + let copied = (|| -> std::io::Result { + let mut from = std::fs::File::open(original)?; + let mut to = std::fs::File::create(&tmp)?; + let n = std::io::copy(&mut from, &mut to)?; + to.sync_all()?; + if let Ok(t) = meta.modified() { + to.set_modified(t)?; + } + Ok(n) + })(); + let after = std::fs::metadata(original).ok().map(|m| FileStamp::of_metadata(&m)); + let text = record(original, &before, meta.len()); + match (copied, text) { + (Ok(n), Some(text)) if n == meta.len() && after.as_ref() == Some(&before) => { + // An earlier copy of the source goes first (its record too): a new record must never + // sit beside old bytes. One that can't be deleted (open elsewhere) stays, with its + // own record, and this copy is given up. + if local.exists() && std::fs::remove_file(&local).is_err() { + let _ = std::fs::remove_file(&tmp); + return None; + } + let _ = std::fs::remove_file(record_path(&local)); + if std::fs::write(record_path(&local), text).is_err() || std::fs::rename(&tmp, &local).is_err() { + let _ = std::fs::remove_file(&tmp); + remove_copy(&local); + return None; + } + Some((local, n, before)) + } + _ => { + let _ = std::fs::remove_file(&tmp); + None + } + } +} + +/// Copies whose deletion fails (tests). +#[cfg(test)] +static FAIL_REMOVE: Mutex> = Mutex::new(Vec::new()); + +/// Runs before each copy, with the source's path (tests). +#[cfg(test)] +type CopyHook = std::sync::Arc; +#[cfg(test)] +static BEFORE_COPY: Mutex> = Mutex::new(None); +/// Runs before a folder is adopted, with the folder (tests). +#[cfg(test)] +static BEFORE_ADOPT: Mutex> = Mutex::new(None); + +/// Called by [`configure`] after the new folder is scanned and the free space read, before they +/// are published (tests). +#[cfg(test)] +static AFTER_ADOPT: Mutex> = Mutex::new(None); + +/// The localizer state is process-wide: tests that use it take turns. +#[cfg(test)] +pub(crate) static TEST_SERIAL: Mutex<()> = Mutex::new(()); + +#[cfg(test)] +mod tests { + use super::*; + + fn config(folder: &Path, max_bytes: u64, network: Vec) -> Option { + Some(LocalizeConfig { folder: folder.to_path_buf(), max_bytes, network, disk_space: None }) + } + + fn wait_for(f: impl Fn(&LocalizeReport) -> bool) -> LocalizeReport { + let until = std::time::Instant::now() + std::time::Duration::from_secs(10); + loop { + let s = status().unwrap_or_default(); + if f(&s) || std::time::Instant::now() > until { + return s; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + } + + /// A network file is copied in the background and read locally only while it matches its + /// source; a source that changed is read from the share again; files over the limit are not + /// copied; local files are never queued; a listed location counts as network; the folder's + /// copies are adopted after a restart (stale temporaries deleted). + #[test] + fn network_files_are_copied_and_used_only_while_they_match() { + let _serial = TEST_SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + let root = std::env::temp_dir().join(format!("ec-3271-localize-{}", std::process::id())); + let (share, local, mapped) = (root.join("share"), root.join("local"), root.join("mapped")); + std::fs::create_dir_all(&share).unwrap(); + std::fs::create_dir_all(&mapped).unwrap(); + treat_as_network(&share); + let file = share.join("plate_0001.exr"); + std::fs::write(&file, vec![7u8; 4096]).unwrap(); + let stamp = |p: &Path| FileStamp::of_metadata(&std::fs::metadata(p).unwrap()); + configure(config(&local, 1 << 20, vec![mapped.clone()])); + assert!(is_network(&mapped.join("x.exr")), "a listed location"); + assert!(local_copy(&file, &stamp(&file)).is_none(), "not copied yet"); + request(&file); + let s = wait_for(|s| s.files == 1); + assert_eq!((s.files, s.bytes, s.queued), (1, 4096, 0), "{s:?}"); + let copy = local_copy(&file, &stamp(&file)).expect("a verified copy"); + assert!(copy.starts_with(&local)); + assert_eq!(std::fs::read(©).unwrap(), vec![7u8; 4096]); + // A restart: the copy is adopted, a stale temporary deleted. + let stale = local.join("0123456789abcdef_old.exr.part"); + std::fs::write(&stale, b"x").unwrap(); + configure(None); + configure(config(&local, 1 << 20, vec![])); + assert_eq!(status().unwrap().files, 1, "adopted"); + assert!(!stale.exists(), "temporaries deleted"); + assert!(local_copy(&file, &stamp(&file)).is_some()); + // The source changes: the copy is not read any more. + std::fs::write(&file, vec![8u8; 5000]).unwrap(); + assert!(local_copy(&file, &stamp(&file)).is_none()); + // Over the limit: skipped. + let big = share.join("big.exr"); + std::fs::write(&big, vec![1u8; 4096]).unwrap(); + configure(config(&local, 1000, vec![])); + request(&big); + let s = wait_for(|s| s.skipped == 1); + assert_eq!((s.skipped, s.files), (1, 0), "{s:?}"); + // A local file is never queued. + request(&root.join("elsewhere.exr")); + assert_eq!(status().unwrap().queued, 0); + configure(None); + assert!(status().is_none()); + let _ = std::fs::remove_dir_all(&root); + } + + /// #3271 review: a file asked for again while it is being copied is not copied a second + /// time, but asked for after the setting changed it is (the copy under the old setting is + /// thrown away). + #[test] + fn a_file_being_copied_is_not_queued_again() { + let _serial = TEST_SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + // (dropped before `_serial`, also when an assertion fails) + let _hook = HookGuard; + let root = std::env::temp_dir().join(format!("ec-3271-localize-dup-{}", std::process::id())); + let (share, local) = (root.join("share"), root.join("local")); + std::fs::create_dir_all(&share).unwrap(); + treat_as_network(&share); + let file = share.join("plate_0002.exr"); + std::fs::write(&file, vec![3u8; 2048]).unwrap(); + // Each copy waits until the test lets it go on. + let copies = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let (go, wait) = std::sync::mpsc::channel::<()>(); + { + let (copies, wait) = (copies.clone(), Mutex::new(wait)); + *BEFORE_COPY.lock().unwrap() = Some(std::sync::Arc::new(move |_: &Path| { + copies.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let _ = wait.lock().unwrap().recv_timeout(std::time::Duration::from_secs(10)); + })); + } + let copies_now = || copies.load(std::sync::atomic::Ordering::SeqCst); + configure(config(&local, 1 << 20, vec![])); + request(&file); + wait_for(|s| s.copying.is_some()); + request(&file); + assert_eq!(status().unwrap().queued, 0, "not queued while it is copied"); + go.send(()).unwrap(); + wait_for(|s| s.files == 1 && s.copying.is_none()); + assert_eq!(copies_now(), 1, "copied once"); + // A new setting while a copy runs: asked for again, it is copied again. + let file2 = share.join("plate_0003.exr"); + std::fs::write(&file2, vec![4u8; 1024]).unwrap(); + request(&file2); + wait_for(|s| s.copying.is_some()); + configure(config(&local, 2 << 20, vec![])); + request(&file2); + assert_eq!(status().unwrap().queued, 1, "queued again under the new setting"); + go.send(()).unwrap(); + go.send(()).unwrap(); + let s = wait_for(|s| s.files == 2 && s.queued == 0 && s.copying.is_none()); + assert_eq!(s.files, 2, "{s:?}"); + assert_eq!(copies_now(), 3); + let _ = std::fs::remove_dir_all(&root); + } + + /// Takes the copy hook out and turns the localizer off when dropped (also when the test + /// fails), so the next test doesn't inherit a hook that holds its copies. + struct HookGuard; + + impl Drop for HookGuard { + fn drop(&mut self) { + *BEFORE_COPY.lock().unwrap_or_else(PoisonError::into_inner) = None; + *BEFORE_ADOPT.lock().unwrap_or_else(PoisonError::into_inner) = None; + *AFTER_ADOPT.lock().unwrap_or_else(PoisonError::into_inner) = None; + FAIL_REMOVE.lock().unwrap_or_else(PoisonError::into_inner).clear(); + configure(None); + } + } + + /// #3271 review: while a new folder's copies are adopted (outside the lock), the worker + /// starts no copy: the scan can't delete its temporary or count a copy it makes twice. + #[test] + fn no_copy_starts_while_a_folder_is_adopted() { + let _serial = TEST_SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + let _hooks = HookGuard; + let root = std::env::temp_dir().join(format!("ec-3271-localize-adopt-{}", std::process::id())); + let (share, first, second) = (root.join("share"), root.join("first"), root.join("second")); + std::fs::create_dir_all(&share).unwrap(); + treat_as_network(&share); + let file = share.join("plate_0004.exr"); + std::fs::write(&file, vec![5u8; 1500]).unwrap(); + configure(config(&first, 1 << 20, vec![])); + // The next folder's scan waits until the test lets it go on. + let (entered, scanning) = std::sync::mpsc::channel::<()>(); + let (go, wait) = std::sync::mpsc::channel::<()>(); + { + let (entered, wait) = (Mutex::new(entered), Mutex::new(wait)); + *BEFORE_ADOPT.lock().unwrap() = Some(std::sync::Arc::new(move |_: &Path| { + let _ = entered.lock().unwrap().send(()); + let _ = wait.lock().unwrap().recv_timeout(std::time::Duration::from_secs(10)); + })); + } + let second_cfg = config(&second, 1 << 20, vec![]); + let switching = std::thread::spawn(move || configure(second_cfg)); + scanning.recv_timeout(std::time::Duration::from_secs(10)).unwrap(); + request(&file); + std::thread::sleep(std::time::Duration::from_millis(200)); + let s = status().unwrap(); + assert!(s.copying.is_none() && s.files == 0, "no copy while adopting: {s:?}"); + go.send(()).unwrap(); + switching.join().unwrap(); + let s = wait_for(|s| s.files == 1 && s.copying.is_none()); + assert_eq!((s.files, s.bytes), (1, 1500), "copied once, counted once: {s:?}"); + let _ = std::fs::remove_dir_all(&root); + } + + /// #3301 review: the adoption ends only when the adopted copies and the free-space reading + /// are published. Between the scan and that publication no copy starts: it would be counted + /// into a reading taken before it, or admitted against a total that misses the adopted files. + #[test] + fn no_copy_starts_between_the_scan_and_its_publication() { + let _serial = TEST_SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + let _hooks = HookGuard; + let root = std::env::temp_dir().join(format!("ec-3301-publish-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let (share, first, second) = (root.join("share"), root.join("first"), root.join("second")); + std::fs::create_dir_all(&share).unwrap(); + treat_as_network(&share); + let file = share.join("plate_0007.exr"); + std::fs::write(&file, vec![5u8; 1500]).unwrap(); + configure(config(&first, 1 << 20, vec![])); + // The next folder is scanned; its copies are not published yet, until the test lets go. + let (entered, scanned) = std::sync::mpsc::channel::<()>(); + let (go, wait) = std::sync::mpsc::channel::<()>(); + { + let (entered, wait) = (Mutex::new(entered), Mutex::new(wait)); + *AFTER_ADOPT.lock().unwrap() = Some(std::sync::Arc::new(move |_: &Path| { + let _ = entered.lock().unwrap().send(()); + let _ = wait.lock().unwrap().recv_timeout(std::time::Duration::from_secs(10)); + })); + } + let second_cfg = config(&second, 1 << 20, vec![]); + let switching = std::thread::spawn(move || configure(second_cfg)); + scanned.recv_timeout(std::time::Duration::from_secs(10)).unwrap(); + request(&file); + std::thread::sleep(std::time::Duration::from_millis(200)); + let s = status().unwrap(); + assert!(s.copying.is_none() && s.files == 0, "no copy before the scan is published: {s:?}"); + go.send(()).unwrap(); + switching.join().unwrap(); + let s = wait_for(|s| s.files == 1 && s.copying.is_none()); + assert_eq!((s.files, s.bytes), (1, 1500), "copied once, after the publication: {s:?}"); + let _ = std::fs::remove_dir_all(&root); + } + + /// #3301 review: a copy renamed into place whose record was never written (a crash in + /// between) is deleted when the folder is adopted: nothing else would delete it, and the + /// size limit didn't count it. Other files in the folder and the copy being made stay. + #[test] + fn a_copy_without_its_record_is_deleted_when_adopted() { + let _serial = TEST_SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + let folder = std::env::temp_dir().join(format!("ec-3301-orphan-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + let orphan = folder.join("0123456789abcdef_plate.exr"); + let busy = folder.join("fedcba9876543210_busy.exr"); + let other = folder.join("notes.txt"); + for f in [&orphan, &busy, &other] { + std::fs::write(f, b"pixels").unwrap(); + } + // A crash between writing a copy's record and renaming its temporary into place: both go. + let mid = folder.join("abcdef0123456789_mid.exr"); + let (mid_rec, mid_part) = (record_path(&mid), folder.join("abcdef0123456789_mid.exr.part")); + std::fs::write(&mid_rec, "/share/mid.exr\n6\n-\n6\n").unwrap(); + std::fs::write(&mid_part, b"pixels").unwrap(); + assert!(adopt(&folder, Some("fedcba9876543210_busy")).is_empty()); + assert!(!mid_rec.exists() && !mid_part.exists(), "a record without its copy and a temporary go"); + assert!(!orphan.exists(), "the copy without a record went"); + assert!(busy.exists(), "the copy being made stays"); + assert!(other.exists(), "not the localizer's: left alone"); + let _ = std::fs::remove_dir_all(&folder); + } + + /// #3301 review: free space is read every 30 s, but copies are made in between. Two copies + /// inside one reading each looked at the same free space (and at room that existing copies + /// took), so together they ate the disk's reserve. Now room is made before a copy is + /// written, and what the copies took since the reading is not free. + #[test] + fn two_copies_in_one_free_space_reading_keep_the_reserve() { + let _serial = TEST_SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + let _hooks = HookGuard; + let root = std::env::temp_dir().join(format!("ec-3301-reserve-{}", std::process::id())); + let (share, local) = (root.join("share"), root.join("local")); + std::fs::create_dir_all(&share).unwrap(); + treat_as_network(&share); + let (a, b) = (share.join("a.exr"), share.join("b.exr")); + std::fs::write(&a, vec![1u8; 2000]).unwrap(); + std::fs::write(&b, vec![2u8; 2000]).unwrap(); + // The disk has 3000 bytes above its reserve and keeps saying so (a cached reading). + let total = 1u64 << 40; + let free = effectcraft_render::disk_cache::disk_reserve(total) + 3000; + let reads = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let counter = reads.clone(); + let disk_space: std::sync::Arc Option<(u64, u64)> + Send + Sync> = std::sync::Arc::new(move || { + counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Some((total, free)) + }); + configure(Some(LocalizeConfig { folder: local.clone(), max_bytes: 1 << 30, network: vec![], disk_space: Some(disk_space) })); + request(&a); + let s = wait_for(|s| s.files == 1 && s.copying.is_none()); + assert_eq!((s.files, s.bytes), (1, 2000), "{s:?}"); + request(&b); + let stamp = |p: &Path| FileStamp::of_metadata(&std::fs::metadata(p).unwrap()); + let until = std::time::Instant::now() + std::time::Duration::from_secs(10); + while local_copy(&b, &stamp(&b)).is_none() && std::time::Instant::now() < until { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + let s = wait_for(|s| s.copying.is_none() && s.queued == 0); + assert!(local_copy(&b, &stamp(&b)).is_some(), "the new copy is kept: {s:?}"); + assert!(local_copy(&a, &stamp(&a)).is_none(), "the older one made room"); + assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 1, "one reading for both copies"); + assert!(s.bytes <= 3000, "the reserve is kept: {s:?}"); + assert_eq!(s.files, 1, "the older copy made room: {s:?}"); + let tmp = std::fs::read_dir(&local).map(|d| d.flatten().filter(|e| e.file_name().to_string_lossy().ends_with(".part")).count()).unwrap_or(0); + assert_eq!(tmp, 0); + let _ = std::fs::remove_dir_all(&root); + } + + /// #3301 review: an old copy whose file can't be deleted (open elsewhere, read-only) is still + /// on the disk: it stays on the books, so the new file is refused (its room was not freed) + /// instead of the disk holding 4000 bytes while the accounting says 2000. + #[test] + fn a_copy_that_cannot_be_deleted_keeps_its_bytes_counted() { + let _serial = TEST_SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + let _hooks = HookGuard; + let root = std::env::temp_dir().join(format!("ec-3301-stuck-{}", std::process::id())); + let (share, local) = (root.join("share"), root.join("local")); + std::fs::create_dir_all(&share).unwrap(); + treat_as_network(&share); + let (a, b) = (share.join("a.exr"), share.join("b.exr")); + std::fs::write(&a, vec![1u8; 2000]).unwrap(); + std::fs::write(&b, vec![2u8; 2000]).unwrap(); + let total = 1u64 << 40; + let free = effectcraft_render::disk_cache::disk_reserve(total) + 3000; + let disk_space: std::sync::Arc Option<(u64, u64)> + Send + Sync> = std::sync::Arc::new(move || Some((total, free))); + configure(Some(LocalizeConfig { folder: local.clone(), max_bytes: 1 << 30, network: vec![], disk_space: Some(disk_space) })); + let stamp = |p: &Path| FileStamp::of_metadata(&std::fs::metadata(p).unwrap()); + request(&a); + wait_for(|s| s.files == 1 && s.copying.is_none()); + let a_copy = local_copy(&a, &stamp(&a)).expect("a's copy"); + // Its file can't be deleted. + FAIL_REMOVE.lock().unwrap().push(a_copy.clone()); + request(&b); + let s = wait_for(|s| s.copying.is_none() && s.queued == 0 && s.skipped == 1); + assert_eq!(s.skipped, 1, "the new file is refused: its room was not freed: {s:?}"); + assert_eq!((s.files, s.bytes), (1, 2000), "the old copy is still counted: {s:?}"); + assert!(a_copy.exists() && record_path(&a_copy).exists(), "its file and record are still there"); + assert!(local_copy(&b, &stamp(&b)).is_none()); + let on_disk: u64 = + std::fs::read_dir(&local).unwrap().flatten().filter(|e| e.path().extension().is_none_or(|x| x != "src")).map(|e| e.metadata().unwrap().len()).sum(); + assert_eq!(on_disk, s.bytes, "the books match the disk"); + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/crates/media/src/pool.rs b/crates/media/src/pool.rs index 90e31a0e7..f6d11ba3c 100644 --- a/crates/media/src/pool.rs +++ b/crates/media/src/pool.rs @@ -1,10 +1,12 @@ //! [`MediaPool`]: decoded footage frames for the compositor, with a memory-budgeted LRU cache. -use std::collections::{BTreeMap, HashMap, HashSet}; +use std::cell::Cell; +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, OnceLock}; use effectcraft_project::{AlphaMode, Footage, FootageKind, ItemId}; +use effectcraft_raster::channels3d::AuxNeed; use effectcraft_raster::{Image, Px}; use effectcraft_render::disk_cache::Frame8; use effectcraft_render::reads::{FileStamp, ReadFile, ReadFiles, ReadLog}; @@ -51,9 +53,12 @@ struct Key { /// A movie frame made at this size for a reduced-resolution render ((0, 0): as decoded). size: (u32, u32), /// A still at a reduced `size`: the footage's nominal size, which decides whether it is - /// resampled (see `Inner::still_at_size`); also at its own size for a placed PDF / + /// resampled (see `Inner::sized_still`); also at its own size for a placed PDF / /// Illustrator page, which is drawn to fill it ([`Footage::placed_page`]); (0, 0) otherwise. nominal: (u32, u32), + /// An OpenEXR frame of which only these rows are read (a region of interest, #3271; the other + /// rows are empty); `None`: all of it. + rows: Option<(i64, i64)>, /// Kept as 8-bit levels ([`FootageSource::frame8`]), not float. q8: bool, } @@ -66,12 +71,40 @@ enum Pixels { } impl Pixels { + /// Nobody but the cache holds the pixels: dropping the cache's references frees their memory. + /// `own` counts the cache's own references to them ([`CacheState::own_refs`]): one picture can + /// be cached under two keys, or both as a frame and as a whole still (#3750 review: a still + /// asked for reduced and then whole is one picture in both), and those are not other holders. + fn unshared(&self, own: impl FnOnce(*const ()) -> usize) -> bool { + let holders = match self { + Pixels::F32(img) => Arc::strong_count(img), + Pixels::Q8(f) => Arc::strong_count(f), + }; + holders <= 1 || holders <= own(self.addr()) + } + + /// Where the pixels are (the same for every reference to them). + fn addr(&self) -> *const () { + match self { + Pixels::F32(img) => Arc::as_ptr(img).cast(), + Pixels::Q8(f) => Arc::as_ptr(f).cast(), + } + } + fn bytes(&self) -> usize { match self { Pixels::F32(img) => img.data.len() * std::mem::size_of::(), Pixels::Q8(f) => f.rgba.len(), } } + + /// The float picture (`None` for 8-bit levels). + fn f32(self) -> Option> { + match self { + Pixels::F32(img) => Some(img), + Pixels::Q8(_) => None, + } + } } struct Entry { @@ -80,6 +113,10 @@ struct Entry { files: Arc, stamp: u64, bytes: usize, + /// When it was last used, for the memory accountant ([`effectcraft_render::memory::tick`]). + used: u64, + /// What decoding it took, in microseconds (a typical cost when not timed). + cost_us: u64, } /// Conformed audio files written by builds before this version are ignored (and written again): @@ -137,14 +174,22 @@ impl Lru { self.order.remove(&e.stamp); self.clock += 1; e.stamp = self.clock; + e.used = effectcraft_render::memory::tick(); self.order.insert(e.stamp, k.clone()); Some((e.img.clone(), e.files.clone())) } /// Stores a frame with its read files under `k` and evicts the least recently used entries until the cache fits `budget` bytes. fn insert(&mut self, k: Key, img: Pixels, files: Arc, budget: usize) { + self.insert_took(k, img, files, budget, None); + } + /// [`Lru::insert`] with what decoding the frame took in microseconds (`None`: not timed, a + /// typical cost). + fn insert_took(&mut self, k: Key, img: Pixels, files: Arc, budget: usize, took: Option) { let bytes = img.bytes() + 64; + let cost_us = took.map_or_else(|| effectcraft_render::memory::default_cost(bytes, effectcraft_render::memory::DEFAULT_FRAME_US_PER_MB), |t| t.max(1)); self.clock += 1; - if let Some(old) = self.map.insert(k.clone(), Entry { img, files, stamp: self.clock, bytes }) { + let used = effectcraft_render::memory::tick(); + if let Some(old) = self.map.insert(k.clone(), Entry { img, files, stamp: self.clock, bytes, used, cost_us }) { self.order.remove(&old.stamp); self.bytes -= old.bytes; } @@ -174,6 +219,31 @@ impl Lru { } } } + /// The least recently used frame it may drop and its last use: not the newest (it always + /// stays) and not one whose pixels someone outside the cache holds (dropping it would free + /// nothing yet). `own`: the cache's own references to pixels ([`CacheState::own_refs`]). + fn oldest(&self, own: impl Fn(*const ()) -> usize) -> Option<(&Key, u64)> { + if self.map.len() <= 1 { + return None; + } + let newest = self.order.last_key_value().map(|(s, _)| *s); + self.order.iter().filter(|(s, _)| Some(**s) != newest).find_map(|(_, k)| { + let e = self.map.get(k)?; + e.img.unshared(&own).then_some((k, e.used)) + }) + } + /// The frames holding the pixels at `addr`. + fn refs(&self, addr: *const ()) -> usize { + self.map.values().filter(|e| e.img.addr() == addr).count() + } + /// The bytes of the recycled buffers ([`Lru::spare`]). + fn spare_bytes(&self) -> usize { + self.spare.iter().map(|b| b.len().saturating_mul(std::mem::size_of::())).fold(0, usize::saturating_add) + } + /// Let one recycled buffer go; the bytes freed. + fn drop_spare(&mut self) -> usize { + self.spare.pop().map_or(0, |b| b.len().saturating_mul(std::mem::size_of::()).max(1)) + } /// A recycled buffer of exactly `len` pixels, or an empty Vec. fn take_spare(&mut self, len: usize) -> Vec { match self.spare.iter().position(|b| b.len() == len) { @@ -197,13 +267,51 @@ pub struct PoolStats { pub bytes: usize, /// Movie and audio files opened (each path once, however many callers ask for it at once). pub opened: u64, + /// Pictures decoded: a still's file (once for all the sizes asked for at the same time) or + /// a movie frame. Requests for a picture being decoded wait for it instead (#3269). + pub decodes: u64, + /// Bytes of whole stills kept beside the frame cache for other sizes of the same frame (at + /// most half the budget; not in `bytes`). + pub recent_bytes: usize, } +/// Whole stills decoded for a reduced size kept beside the frame cache ([`CacheState::recent`]): +/// at most this many bytes in all (and half the frame cache's budget)… +const RECENT_BYTES: usize = 512 << 20; +/// …and only while the frame cache has taken fewer than this many frames since. +const RECENT_AGE: u64 = 256; + +/// How long a request waits for another thread's decode of the same picture before it decodes +/// a copy itself. A safety net only: decodes run on their own threads ([`decode_threads`]), so +/// no wait depends on the waiting thread or on other requests; only a hung decode takes this long. +#[cfg(not(target_arch = "wasm32"))] +const WAIT_LIMIT: std::time::Duration = std::time::Duration::from_secs(10); + +/// How often a request asks again after the decode it waited for was called off for the +/// request that ran it (#329), before it decodes a copy itself. +const CANCELLED_RETRIES: u32 = 3; + #[derive(Default)] struct CacheState { lru: Lru, - /// Frames being decoded right now (requests for them wait instead of decoding again). - inflight: HashSet, + /// Pictures being decoded right now, by what is decoded (a still's whole picture, a movie + /// frame at its size): requests for them wait for that decode instead of decoding again. + inflight: HashMap>, + /// The last whole stills decoded for a reduced size (their keys have no size; see + /// [`RECENT_BYTES`] and [`RECENT_AGE`]). Another size of the same frame shortly after (the + /// Project panel's thumbnail of the comp at the viewer's time) is resampled from it instead of + /// decoded again (#3269), and comes out as if decoded on its own. Not in the frame cache: a + /// large plate shown reduced is not kept whole there (#1812). + recent: VecDeque, + /// Counts `forget` calls (an epoch requests and decodes start in; see [`CacheState::stale`]). + generation: u64, + /// The generation each path was last forgotten at (at most [`MAX_FORGOTTEN`] paths): a + /// request or decode of that path that started before it is stale (the file may have changed + /// meanwhile), one of another path is not. + forgotten: HashMap, u64>, + /// Requests and decodes that started before this generation are stale whatever their path + /// (set when `forgotten` is cleared to keep it bounded). + stale_before: u64, /// Last frame index requested per movie (sequential-playback detection). last: HashMap, i64>, /// Movies whose frames can't be kept as 8-bit levels (more bits, or shown turned). @@ -214,6 +322,235 @@ struct CacheState { forgets: u64, } +/// A whole still in [`CacheState::recent`]. +struct Recent { + key: Key, + img: Arc, + /// The files it was decoded from (see [`crate::reads`]). + files: Arc, + bytes: usize, + /// The frame cache's clock when it was kept. + stamp: u64, + /// When it was kept ([`effectcraft_render::memory::tick`]). + used: u64, +} + +/// At most this many forgotten paths are remembered ([`CacheState::forgotten`]); beyond that +/// everything that started before is treated as stale instead. +const MAX_FORGOTTEN: usize = 4096; + +impl CacheState { + /// Whether what was made of `path` by a request or decode that started at `generation` is + /// stale: the path was forgotten since (#3269 review: forgetting one file left every other + /// file's decodes uncached and unshared). + fn stale(&self, path: &str, generation: u64) -> bool { + generation < self.stale_before || self.forgotten.get(path).is_some_and(|&at| at > generation) + } + + /// Note that `path` was forgotten. + fn forgot(&mut self, path: &str) { + self.generation = self.generation.saturating_add(1); + if self.forgotten.len() >= MAX_FORGOTTEN { + self.forgotten.clear(); + self.stale_before = self.generation; + } + self.forgotten.insert(path.into(), self.generation); + } + + /// Note that every file was let go (Purge): whatever a request or decode that started before + /// makes is stale, and none of them is joined. + fn forgot_all(&mut self) { + self.generation = self.generation.saturating_add(1); + self.forgotten.clear(); + self.stale_before = self.generation; + } + + /// The whole still `key` decoded recently, with the files it was decoded from, if it is + /// still kept. + fn recent(&mut self, key: &Key) -> Option<(Arc, Arc)> { + let clock = self.lru.clock; + self.recent.retain(|r| clock.saturating_sub(r.stamp) <= RECENT_AGE); + self.recent.iter().find(|r| r.key == *key).map(|r| (r.img.clone(), r.files.clone())) + } + + /// Keep the whole still `img` decoded for a reduced size, dropping the oldest beyond + /// [`RECENT_BYTES`] (and half of `budget`). + fn keep_recent(&mut self, key: Key, img: Arc, files: Arc, budget: usize) { + let bytes = img.data.len().saturating_mul(std::mem::size_of::()); + self.recent.retain(|r| r.key != key); + if bytes > Self::recent_cap(budget) { + return; + } + let stamp = self.lru.clock; + self.recent.push_back(Recent { key, img, files, bytes, stamp, used: effectcraft_render::memory::tick() }); + self.trim_recent(budget); + } + + /// The most bytes of whole stills [`CacheState::recent`] holds with the frame cache's `budget`. + fn recent_cap(budget: usize) -> usize { + RECENT_BYTES.min(budget / 2) + } + + /// Drop the oldest whole stills until the rest fit [`CacheState::recent_cap`] of `budget` + /// (also when the budget shrinks). + fn trim_recent(&mut self, budget: usize) { + let cap = Self::recent_cap(budget); + while self.recent_bytes() > cap { + if self.recent.pop_front().is_none() { + break; + } + } + } + + /// The bytes the frame cache, its recycled buffers and the whole stills beside it hold (the + /// memory holder's). + fn held_bytes(&self) -> usize { + self.lru.bytes.saturating_add(self.lru.spare_bytes()).saturating_add(self.recent_bytes()) + } + + /// The oldest whole still in [`CacheState::recent`] that nobody outside the cache holds + /// (dropping one in use would free nothing yet; one also cached as a frame is the cache's). + fn oldest_recent(&self) -> Option { + self.recent.iter().position(|r| { + let holders = Arc::strong_count(&r.img); + holders <= 1 || holders <= self.own_refs(Arc::as_ptr(&r.img).cast()) + }) + } + + /// The references the cache itself holds to the pixels at `addr`: its frames and whole + /// stills holding them (#3750 review: a whole still kept for a reduced size and then asked + /// for whole is in both). + fn own_refs(&self, addr: *const ()) -> usize { + self.lru.refs(addr).saturating_add(self.recent.iter().filter(|r| Arc::as_ptr(&r.img).cast::<()>() == addr).count()) + } + + /// The least recently used frame it may drop ([`Lru::oldest`]) and its last use. + fn oldest_frame(&self) -> Option<(&Key, u64)> { + self.lru.oldest(|addr| self.own_refs(addr)) + } + + /// Drop the least recently used frame it may drop; the bytes freed. + fn drop_oldest_frame(&mut self) -> usize { + let Some(k) = self.oldest_frame().map(|(k, _)| k.clone()) else { return 0 }; + let had = self.lru.bytes; + self.lru.remove(&k); + had.saturating_sub(self.lru.bytes) + } + + /// The bytes of the whole stills [`CacheState::recent`] holds. + fn recent_bytes(&self) -> usize { + self.recent.iter().map(|r| r.bytes).sum() + } +} + +/// What a decode ended with: the picture (or why not) and the files it read (see +/// [`crate::reads`]; also on failure, so a frame that failed names the files to watch). +type Outcome = (Result, Arc); + +/// A decode in progress ([`CacheState::inflight`]): its outcome once it ends, for the requests +/// waiting on it. +#[derive(Default)] +struct Flight { + /// [`CacheState::generation`] when it started: a request made after its file was forgotten + /// (it changed on disk) doesn't join it, and decodes the file anew. + generation: u64, + outcome: Mutex>, + ready: Condvar, +} + +thread_local! { + /// Decodes running on this thread itself right now ([`Decoding`]; only where there are no + /// decode threads). Such a thread doesn't wait for another decode: a rayon worker waiting on + /// its decode's parallel work runs other jobs meanwhile, and one asking for a picture being + /// decoded could wait on a decode further down its own stack. + static OWNED: Cell = const { Cell::new(0) }; +} + +/// Marks a decode running on this thread ([`OWNED`]) until dropped (also when it panics). +struct Decoding; + +impl Decoding { + fn new() -> Self { + OWNED.with(|n| n.set(n.get().saturating_add(1))); + Decoding + } +} + +impl Drop for Decoding { + fn drop(&mut self) { + OWNED.with(|n| n.set(n.get().saturating_sub(1))); + } +} + +/// The threads footage pictures are decoded on (one per core, `ec-decode-N`), `None` where they +/// can't be started. Requests hand their decode to them and block until it is done (#3269): +/// a frame worker then never runs part of a decode (rayon would let it pick up another frame's +/// job meanwhile, which could wait on that very decode), and a thread decoding never runs a +/// frame job that waits on it. The decode's own parallel work runs on these threads, which +/// never wait for a picture. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn decode_threads() -> Option<&'static rayon::ThreadPool> { + static THREADS: OnceLock> = OnceLock::new(); + THREADS + .get_or_init(|| { + let n = std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(4, 32); + rayon::ThreadPoolBuilder::new() + .num_threads(n) + .thread_name(|i| format!("ec-decode-{i}")) + // (the request waiting for it gets an error; rayon's default aborts) + .panic_handler(|_| log::error!("media: a footage decode panicked; that frame shows nothing")) + .build() + .inspect_err(|e| log::warn!("media: no decode threads ({e}); footage decodes on the threads asking for it")) + .ok() + }) + .as_ref() +} + +/// What waiting for another thread's decode ended with ([`Inner::wait`]). +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +enum Waited { + /// Its outcome. + Got(Outcome), + /// This request was called off meanwhile (its own cancel flag, #329). + Cancelled, + /// This thread may not wait, or waited [`WAIT_LIMIT`]: it decodes a copy itself. + No, +} + +/// At most this many movie/audio files are kept open ([`Sources`]): the least recently used one +/// nobody is using is closed beyond it (it opens again when asked for; a project that cycles +/// through more files than this opens them again each time). +/// Still images and image sequences keep no file open (an OpenEXR file is opened for one decode). +const MAX_OPEN_SOURCES: usize = 256; + +/// The opened movie/audio sources by path, with when each was last asked for. +#[derive(Default)] +struct Sources { + map: HashMap, (SourceSlot, u64)>, + clock: u64, +} + +impl Sources { + /// The slot of `path` (new when there is none), as just used; the least recently used slot + /// beyond [`MAX_OPEN_SOURCES`] is dropped. + fn slot(&mut self, path: &Arc) -> SourceSlot { + self.clock = self.clock.wrapping_add(1); + let clock = self.clock; + let slot = { + let e = self.map.entry(path.clone()).or_insert_with(|| (SourceSlot::default(), clock)); + e.1 = clock; + e.0.clone() + }; + // (only a slot nobody is using or opening: an open in progress isn't started twice) + if self.map.len() > MAX_OPEN_SOURCES + && let Some(oldest) = self.map.iter().filter(|(_, (s, _))| Arc::strong_count(s) == 1).min_by_key(|(_, (_, used))| *used).map(|(p, _)| p.clone()) + { + self.map.remove(&oldest); + } + slot + } +} + /// A movie/audio source by path ([`Opened`]), opened by the first caller while the others wait /// for it (`None`: failed to open; not retried until `forget`), with the file's identity as /// opened. @@ -250,8 +587,8 @@ fn channel_order(src: &SharedSource, header: Option<&[u8]>, file: Option<&dyn fi type GifSlot = Arc, String>, ReadFile)>>; struct Inner { - /// Opened movie/audio sources by path. - sources: Mutex, SourceSlot>>, + /// Opened movie/audio sources by path, at most [`MAX_OPEN_SOURCES`]. + sources: Mutex, /// Files opened into `sources` (see [`PoolStats::opened`]). opened: AtomicU64, /// In-memory files registered with `add_bytes` (web builds, tests). @@ -263,12 +600,19 @@ struct Inner { /// `Err` is not retried until `forget`). gifs: Mutex, GifSlot>>, cache: Mutex, - done: Condvar, budget: AtomicU64, read_ahead: AtomicBool, hits: AtomicU64, misses: AtomicU64, prefetched: AtomicU64, + /// See [`PoolStats::decodes`]. + decodes: AtomicU64, + /// Requests waiting for another thread's decode right now (tests). + #[cfg(test)] + waiting: std::sync::atomic::AtomicUsize, + /// Runs before each decode; `Some` answers in its place (tests). + #[cfg(test)] + gate: Mutex>, /// Settings ▸ Disk ▸ Conformed Audio Folder: decoded audio tracks written once per file and /// rate, read back instead of decoding again (`None` = off). conform: Mutex>, @@ -287,6 +631,10 @@ struct Inner { aux_footage: Mutex, } +/// [`Inner::gate`]. +#[cfg(test)] +type Gate = Arc Option> + Send + Sync>; + /// Footage whose channels effects read ([`Inner::aux_footage`]), by [`Footage::path`]. #[derive(Default)] struct AuxFootage { @@ -295,12 +643,21 @@ struct AuxFootage { /// Read through [`FootageSource::aux`] but not given (a reader the project doesn't name, or /// a source that never gives a set). Cleared with each new set. learned: HashSet, + /// What the effects reading each footage's channels read of them + /// ([`FootageSource::set_aux_needs`], #3271); a footage read without one reads them all. + needs: HashMap, } impl AuxFootage { fn contains(&self, path: &str) -> bool { self.given.contains(path) || self.learned.contains(path) } + + /// The channels to read with the picture of footage `path`: what its effects read, all of + /// them when they didn't say, none (`None`) when no effect reads them. + fn plan(&self, path: &str) -> Option { + self.contains(path).then(|| self.needs.get(path).cloned().unwrap_or_default()) + } } /// Decodes footage for the renderer: stills, image sequences and movies (FilmCraft codecs), plus @@ -311,7 +668,9 @@ impl AuxFootage { /// - Converted frames live in an LRU cache bounded by a byte budget ([`DEFAULT_BUDGET`]). /// - Sequential playback reads one frame ahead on a worker thread (native builds), so decoding /// and conversion of the next frame overlap with the caller's use of the current one. -/// - Concurrent requests for the same frame decode it once. +/// - Concurrent requests for the same frame decode it once: the first decodes, the others wait +/// for its picture (#3269). A still asked for at several sizes is decoded once and resampled +/// to each. #[derive(Clone)] pub struct MediaPool { inner: Arc, @@ -324,6 +683,7 @@ impl Default for MediaPool { } /// Where a frame comes from. +#[derive(Clone)] struct Loc { key: Key, /// Media time for movies (`None`: an image file, `key.path`). @@ -332,16 +692,61 @@ struct Loc { float: FloatCurve, } -/// Removes an in-flight key and wakes waiters, also when decoding panics. -struct Inflight<'a> { +/// The request decoding a picture ([`CacheState::inflight`]). Dropped, it keeps the picture +/// (in the frame cache, or a reduced still's whole picture in [`CacheState::recent`]; not when +/// the file was forgotten meanwhile), ends the flight and hands its outcome to the requests +/// waiting on it: an error when the decode panicked or returned early, so none waits for a +/// picture that never comes. +struct Owner<'a> { inner: &'a Inner, + /// When the decode started ([`effectcraft_render::memory::tick`]: what it took is the frame's + /// cost to the memory accountant). + started: u64, key: Key, + flight: Arc, + /// The picture is the one asked for (else a still's whole picture, resampled for the request). + as_asked: bool, + /// [`CacheState::generation`] when the decode started. + generation: u64, + outcome: Option, } -impl Drop for Inflight<'_> { +impl Drop for Owner<'_> { fn drop(&mut self) { - lock(&self.inner.cache).inflight.remove(&self.key); - self.inner.done.notify_all(); + // (a decode that stopped early can't name the files it read) + let outcome = self.outcome.take().unwrap_or_else(|| { + let mut files = ReadFiles::default(); + files.mark_incomplete(); + (Err(MediaError::Decode(format!("{}: the decode stopped", self.key.path))), Arc::new(files)) + }); + let budget = self.inner.budget(); + let mut c = lock(&self.inner.cache); + let had = c.held_bytes(); + if let (Ok(img), files) = &outcome + && !c.stale(&self.key.path, self.generation) + { + if self.as_asked { + let took = effectcraft_render::memory::tick().saturating_sub(self.started); + let mut key = self.key.clone(); + // (asked as 8-bit levels but not 8-bit: kept as the float frame it is, which the + // renderer asks for next) + if key.q8 && matches!(img, Pixels::F32(_)) { + c.wide.insert(key.path.clone()); + key.q8 = false; + } + c.lru.insert_took(key, img.clone(), files.clone(), budget, Some(took)); + } else if let Pixels::F32(whole) = img { + c.keep_recent(self.key.clone(), whole.clone(), files.clone(), budget); + } + } + let grown = c.held_bytes().saturating_sub(had); + if c.inflight.get(&self.key).is_some_and(|f| Arc::ptr_eq(f, &self.flight)) { + c.inflight.remove(&self.key); + } + drop(c); + *lock(&self.flight.outcome) = Some(outcome); + self.flight.ready.notify_all(); + effectcraft_render::memory::Accountant::global().note_growth(grown); } } @@ -351,8 +756,16 @@ impl MediaPool { Self::with_budget(DEFAULT_BUDGET) } - /// A pool whose frame cache holds at most `bytes` of decoded frames. + /// A pool whose frame cache holds at most `bytes` of decoded frames, in the common memory + /// budget ([`effectcraft_render::memory::Accountant`]). pub fn with_budget(bytes: usize) -> Self { + let pool = Self::unregistered(bytes); + let holder: Arc = pool.inner.clone(); + effectcraft_render::memory::Accountant::global().register(&holder); + pool + } + + fn unregistered(bytes: usize) -> Self { Self { inner: Arc::new(Inner { sources: Mutex::default(), @@ -360,12 +773,16 @@ impl MediaPool { models: Mutex::default(), gifs: Mutex::default(), cache: Mutex::default(), - done: Condvar::new(), budget: AtomicU64::new(bytes as u64), read_ahead: AtomicBool::new(cfg!(not(target_arch = "wasm32"))), hits: AtomicU64::new(0), misses: AtomicU64::new(0), prefetched: AtomicU64::new(0), + decodes: AtomicU64::new(0), + #[cfg(test)] + waiting: std::sync::atomic::AtomicUsize::new(0), + #[cfg(test)] + gate: Mutex::default(), opened: AtomicU64::new(0), conform: Mutex::default(), conforming: Mutex::default(), @@ -380,10 +797,35 @@ impl MediaPool { self.inner.budget() } + /// Keep a frame of `width` by `height` as the frame of `path` (tests of the footage budget). + #[cfg(test)] + pub(crate) fn keep_test_frame(&self, path: &str, width: u32, height: u32) { + let key = Key { path: path.into(), frame: 0, interp: 0, matte: [0; 3], size: (0, 0), nominal: (0, 0), rows: None, q8: false }; + let budget = self.inner.budget(); + lock(&self.inner.cache).lru.insert(key, Pixels::F32(Arc::new(Image::new(width, height))), Arc::default(), budget); + } + + /// The paths of the frames [`MediaPool::keep_test_frame`] kept that are still cached. + #[cfg(test)] + pub(crate) fn test_frames(&self) -> Vec { + let c = lock(&self.inner.cache); + let mut v: Vec = c.lru.map.keys().map(|k| k.path.to_string()).collect(); + v.sort(); + v + } + + /// The frame cache as the memory accountant sees it (tests). + #[cfg(test)] + pub(crate) fn memory_holder(&self) -> Arc { + self.inner.clone() + } + /// Change the frame-cache budget (evicts immediately when shrinking). pub fn set_budget(&self, bytes: usize) { self.inner.budget.store(bytes as u64, Ordering::Relaxed); - lock(&self.inner.cache).lru.evict(bytes); + let mut c = lock(&self.inner.cache); + c.lru.evict(bytes); + c.trim_recent(bytes); } /// Enable or disable reading one frame ahead during sequential playback (on by default on @@ -402,6 +844,8 @@ impl MediaPool { frames: c.lru.map.len(), bytes: c.lru.bytes, opened: i.opened.load(Ordering::Relaxed), + decodes: i.decodes.load(Ordering::Relaxed), + recent_bytes: c.recent_bytes(), } } @@ -409,7 +853,10 @@ impl MediaPool { pub fn clear_frames(&self) { let mut c = lock(&self.inner.cache); c.lru = Lru::default(); + c.recent.clear(); c.last.clear(); + // (a decode in flight keeps nothing, and later requests don't join it) + c.forgot_all(); c.forgets = c.forgets.wrapping_add(1); drop(c); // Decoded GIFs sit outside the frame budget; Purge frees them too. @@ -419,7 +866,7 @@ impl MediaPool { /// Drop every cached frame and decoder. pub fn clear(&self) { self.clear_frames(); - lock(&self.inner.sources).clear(); + lock(&self.inner.sources).map.clear(); lock(&self.inner.problems).clear(); } @@ -427,7 +874,7 @@ impl MediaPool { /// failed to open). A decode of any file in flight meanwhile keeps nothing (see /// [`CacheState::forgets`]). pub fn forget(&self, path: &str) { - lock(&self.inner.sources).remove(path); + lock(&self.inner.sources).map.remove(path); lock(&self.inner.models).remove(path); lock(&self.inner.gifs).remove(path); lock(&self.inner.problems).remove(path); @@ -436,11 +883,13 @@ impl MediaPool { for k in keys { c.lru.remove(&k); } + c.recent.retain(|r| &*r.key.path != path); + c.forgot(path); c.last.remove(path); c.wide.remove(path); c.forgets = c.forgets.wrapping_add(1); drop(c); - crate::exr_channels::forget(path); + crate::exr_planes::forget(path); } /// Provide the contents of `path` from memory (used instead of the file system; web builds). @@ -463,7 +912,7 @@ impl MediaPool { if lock(&self.inner.cache).wide.contains(footage.path.as_str()) { return None; } - match Inner::frame_px(&self.inner, footage, t, true, None, float, true, None) { + match Inner::frame_px(&self.inner, footage, t, true, None, float, true, None, None) { Ok(Pixels::Q8(f)) => Some(f), _ => None, } @@ -705,6 +1154,27 @@ impl Inner { bytes } + /// Where the OpenEXR file at `path` is read from: registered bytes, else the file. + fn exr_source(&self, path: &str) -> crate::exr_read::ExrSource { + use crate::exr_read::ExrSource; + if let Some(b) = lock(&self.files).get(path) { + return ExrSource::Bytes(b.clone()); + } + let file = std::path::PathBuf::from(path); + // A network file: copied in the background when the localizer is on, and read from its + // copy once that is complete and the file unchanged (#3271). + if crate::localize::is_network(&file) && crate::localize::status().is_some() { + crate::localize::request(&file); + // (the identity as read within the last moment: one check per file and frame, #3334) + if let Ok(stamp) = crate::exr_read::recent_stamp(&file) + && let Some(copy) = crate::localize::local_copy(&file, &stamp) + { + return ExrSource::Localized { original: file, copy, stamp }; + } + } + ExrSource::File(file) + } + /// The bytes of the file at `path` and its identity as read ([`FileStamp::Missing`] when it /// can't be read), not noted. fn read_file(&self, path: &str) -> (Result>, ReadFile) { @@ -725,7 +1195,7 @@ impl Inner { /// each decoded a long FLAC in full at once (#408). /// Each call notes the file as read (see [`crate::reads`]), with its identity as opened. fn opened(&self, path: &Arc) -> Option { - let slot = lock(&self.sources).entry(path.clone()).or_default().clone(); + let slot = lock(&self.sources).slot(path); let (opened, file) = slot.get_or_init(|| self.open(path)); reads::note(file.clone()); opened.clone() @@ -822,7 +1292,7 @@ impl Inner { } << 2) | (u8::from(footage.placed_page) << 4); let matte = if footage.alpha == AlphaMode::Premultiplied { footage.premul_color.map(f32::to_bits) } else { [0; 3] }; - let key = |path: &str, frame| Key { path: path.into(), frame, interp, matte, size: (0, 0), nominal: (0, 0), q8: false }; + let key = |path: &str, frame| Key { path: path.into(), frame, interp, matte, size: (0, 0), nominal: (0, 0), rows: None, q8: false }; match footage.kind { FootageKind::Sequence if !footage.sequence.is_empty() => { let i = Self::frame_index(footage.frame_rate, t, footage.sequence_frames(), footage.loop_count); @@ -857,8 +1327,35 @@ impl Inner { /// The frame of `footage` at `t`, resampled to `size` (see [`FootageSource::frame_at_size`]): /// a movie's made at that size directly, a still's resampled once and kept at that size. + /// + /// Each picture is decoded once however many threads ask for it at the same time (#3269): + /// the first decodes it and the others wait for its picture. A still is decoded whole and + /// resampled to each size asked for, so a second size of the same frame (the Project panel's + /// thumbnail beside a reduced viewer) comes from the same decode, the frame cache's whole + /// picture or a recent one ([`CacheState::recent`]), and is the same as decoded on its own. fn frame_at(self: &Arc, footage: &Footage, t: Tick, playback: bool, size: Option<(u32, u32)>, float: FloatCurve) -> Result> { - match Self::frame_px(self, footage, t, playback, size, float, false, None)? { + self.frame_at_rows(footage, t, playback, size, float, None) + } + + /// Whether a request for some rows of `footage` at `t` reads only those: an OpenEXR frame + /// (not a movie) whose channels no effect reads. + fn reads_rows(&self, footage: &Footage, t: Tick) -> bool { + let loc = Self::locate(footage, t, FloatCurve::Srgb); + loc.media_t.is_none() && crate::exr_planes::is_exr(&loc.key.path) && lock(&self.aux_footage).plan(&footage.path).is_none() + } + + /// [`Inner::frame_at`] of only the rows `rows` of an OpenEXR frame whose channels no effect + /// reads (#3271; others are read whole). + fn frame_at_rows( + self: &Arc, + footage: &Footage, + t: Tick, + playback: bool, + size: Option<(u32, u32)>, + float: FloatCurve, + rows: Option<(i64, i64)>, + ) -> Result> { + match Self::frame_px(self, footage, t, playback, size, float, false, rows, None)? { Pixels::F32(img) => Ok(img), // (a float request's key never holds 8-bit levels) Pixels::Q8(_) => Err(MediaError::Decode(format!("{}: 8-bit frame for a float request", footage.path))), @@ -879,6 +1376,7 @@ impl Inner { size: Option<(u32, u32)>, float: FloatCurve, q8: bool, + rows: Option<(i64, i64)>, since: Option, ) -> Result { if !footage.has_video { @@ -887,6 +1385,7 @@ impl Inner { let mut loc = Self::locate(footage, t, float); loc.key.q8 = q8; let movie = loc.media_t.is_some(); + loc.key.rows = rows.filter(|_| self.reads_rows(footage, t)); // A still asked for at its own size is the unsized frame (one decode, one entry). if let Some(size) = size.filter(|s| movie || *s != (footage.width, footage.height)) { loc.key.size = size; @@ -899,13 +1398,35 @@ impl Inner { if footage.placed_page && !movie { loc.key.nominal = (footage.width, footage.height); } + // Some rows of an OpenEXR frame (a region of interest, #3271): the whole frame when the + // cache has it, else those rows read for this request alone (not kept: a frame cache + // entry of a few rows would hold a whole frame's memory). + if loc.key.rows.is_some() { + return self.frame_rows_of(&loc, footage).map(Pixels::F32); + } + // What is decoded: a movie frame at its size, a still whole (its key has no size; a + // placed page keeps the footage's size, which it is drawn to fill). + let whole_nominal = if footage.placed_page { (footage.width, footage.height) } else { (0, 0) }; + let source = Loc { + key: if movie { loc.key.clone() } else { Key { size: (0, 0), nominal: whole_nominal, ..loc.key.clone() } }, + media_t: loc.media_t, + float: loc.float, + }; + let as_asked = source.key == loc.key; + // The picture asked for, made of the decoded one. + let shape = |whole: Pixels| match whole { + Pixels::F32(img) if !movie => Pixels::F32(Self::sized_still(img, &loc, footage)), + whole => whole, + }; let mut c = lock(&self.cache); + let generation = c.generation; // sequential playback of a movie: read the next frame ahead if playback && movie { self.prefetch_next(&mut c, &loc, footage, t, size, float); } // (Each exit notes the files the frame came from, see `crate::reads`; a cached frame // notes those it was decoded from, without touching them.) + let mut retries = 0; loop { if let Some((img, files)) = c.lru.get(&loc.key) { self.hits.fetch_add(1, Ordering::Relaxed); @@ -913,44 +1434,154 @@ impl Inner { reads::note_all(&files); return Ok(img); } - if !c.inflight.contains(&loc.key) { - break; + // A still decoded already for another size: resampled from its whole picture. + if !movie { + let whole = c.lru.get(&source.key).or_else(|| c.recent(&source.key).map(|(img, files)| (Pixels::F32(img), files))); + if let Some((whole, files)) = whole { + drop(c); + self.hits.fetch_add(1, Ordering::Relaxed); + reads::note_all(&files); + return Ok(self.keep(&loc.key, shape(whole), files, generation)); + } } - // Another thread (or the read-ahead) is decoding this frame. Never block a rayon - // worker on that: while the decoder waits on its own parallel join, the worker can - // steal this very job, and waiting here would then wait on a decode further down - // its own stack (deadlock). Decode a private copy instead. - if rayon::current_thread_index().is_some() { - self.misses.fetch_add(1, Ordering::Relaxed); - drop(c); - let (img, files) = reads::captured(|| self.decode(&loc, footage)); - reads::note_all(&files); - return img; + // (one started before the file was forgotten is left to its own requests) + let Some(flight) = c.inflight.get(&source.key).filter(|f| !c.stale(&source.key.path, f.generation)).cloned() else { break }; + // Another request (or the read-ahead) is decoding this picture: wait for it. + drop(c); + self.misses.fetch_add(1, Ordering::Relaxed); + match self.wait(&flight) { + // (kept also when it is the picture decoded: a still's whole picture decoded for + // another size is not in the frame cache) + Waited::Got((Ok(whole), files)) => { + reads::note_all(&files); + return Ok(self.keep(&loc.key, shape(whole), files, generation)); + } + // The other request was called off (#329), not this one: ask again (and decode + // it here if nobody else does by now). + Waited::Got((Err(MediaError::Cancelled), _)) if retries < CANCELLED_RETRIES => retries += 1, + // Called off again and again, or this thread may not wait (or waited too long): + // decode a copy. + Waited::Got((Err(MediaError::Cancelled), _)) | Waited::No => { + let (img, files) = self.run_decode(&source, footage); + reads::note_all(&files); + return Ok(shape(img?)); + } + Waited::Got((Err(e), files)) => { + reads::note_all(&files); + return Err(e); + } + Waited::Cancelled => return Err(MediaError::Cancelled), } - c = self.done.wait(c).unwrap_or_else(std::sync::PoisonError::into_inner); + c = lock(&self.cache); } let since = since.unwrap_or(c.forgets); if c.forgets != since { return Err(MediaError::Cancelled); } self.misses.fetch_add(1, Ordering::Relaxed); - c.inflight.insert(loc.key.clone()); + let flight = Arc::new(Flight { generation, ..Flight::default() }); + c.inflight.insert(source.key.clone(), flight.clone()); drop(c); - let _guard = Inflight { inner: self, key: loc.key.clone() }; - let (img, files) = reads::captured(|| self.decode(&loc, footage)); + let mut owner = + Owner { inner: self, started: effectcraft_render::memory::tick(), key: source.key.clone(), flight, as_asked, generation, outcome: None }; + let (decoded, files) = self.run_decode(&source, footage); + let files = Arc::new(files); reads::note_all(&files); - let img = img?; + owner.outcome = Some((decoded.clone(), files.clone())); + // (keeps the picture and hands it to the waiting requests) + drop(owner); + let whole = decoded?; + Ok(if as_asked { whole } else { self.keep(&loc.key, shape(whole), files, generation) }) + } + + /// [`Inner::frame_at_rows`] of a request for rows (`loc.key.rows`): the whole frame at that + /// size or the whole still from the frame cache, else the rows decoded now. + fn frame_rows_of(self: &Arc, loc: &Loc, footage: &Footage) -> Result> { + let whole = Key { rows: None, ..loc.key.clone() }; + let still = Key { size: (0, 0), nominal: (0, 0), ..whole.clone() }; let mut c = lock(&self.cache); - if c.forgets != since { + if let Some((img, files)) = c.lru.get(&whole).and_then(|(p, f)| Some((p.f32()?, f))) { + drop(c); + self.hits.fetch_add(1, Ordering::Relaxed); + reads::note_all(&files); return Ok(img); } - if q8 && let Pixels::F32(_) = img { - // not 8-bit: kept as the float frame it is, which the renderer asks for next - c.wide.insert(loc.key.path.clone()); - loc.key.q8 = false; + if let Some((img, files)) = c.lru.get(&still).and_then(|(p, f)| Some((p.f32()?, f))).or_else(|| c.recent(&still)) { + drop(c); + self.hits.fetch_add(1, Ordering::Relaxed); + reads::note_all(&files); + return Ok(Self::sized_still(img, loc, footage)); } - c.lru.insert(loc.key, img.clone(), Arc::new(files), self.budget()); - Ok(img) + drop(c); + self.misses.fetch_add(1, Ordering::Relaxed); + let source = Loc { key: Key { size: (0, 0), nominal: (0, 0), ..loc.key.clone() }, media_t: None, float: loc.float }; + let (img, files) = self.run_decode(&source, footage); + reads::note_all(&files); + match img? { + Pixels::F32(img) => Ok(Self::sized_still(img, loc, footage)), + Pixels::Q8(_) => Err(MediaError::Decode(format!("{}: 8-bit frame for a still", loc.key.path))), + } + } + + /// Keep `img`, made of `files`, in the frame cache as `key` (unless its file was forgotten + /// since `generation`, see [`CacheState::stale`]), and return it. + fn keep(&self, key: &Key, img: Pixels, files: Arc, generation: u64) -> Pixels { + let mut c = lock(&self.cache); + let had = c.held_bytes(); + if !c.stale(&key.path, generation) { + c.lru.insert(key.clone(), img.clone(), files, self.budget()); + } + let grown = c.held_bytes().saturating_sub(had); + drop(c); + effectcraft_render::memory::Accountant::global().note_growth(grown); + img + } + + /// Wait for the outcome of another request's decode (`flight`). + /// + /// Waiting can't deadlock: decodes run on their own threads ([`decode_threads`]), which never + /// wait for a picture, so a decode doesn't depend on the requests waiting for it. Where there + /// are no decode threads, a thread running a decode itself ([`OWNED`]) doesn't wait. The time + /// limit is a safety net for a hung decode. + #[cfg(not(target_arch = "wasm32"))] + fn wait(&self, flight: &Flight) -> Waited { + if OWNED.with(Cell::get) > 0 { + log::debug!("media: a picture asked for during a decode on this thread is being decoded elsewhere; decoding a copy"); + return Waited::No; + } + let until = std::time::Instant::now() + WAIT_LIMIT; + #[cfg(test)] + self.waiting.fetch_add(1, Ordering::SeqCst); + let mut outcome = lock(&flight.outcome); + let waited = loop { + if let Some(o) = outcome.as_ref() { + break Waited::Got(o.clone()); + } + if filmcraft_media::cancel::cancelled() { + break Waited::Cancelled; + } + let left = until.saturating_duration_since(std::time::Instant::now()); + if left.is_zero() { + log::warn!("media: a picture took over {} s to decode on another thread; decoding a copy", WAIT_LIMIT.as_secs()); + break Waited::No; + } + // (in slices, to notice this request being called off) + outcome = match flight.ready.wait_timeout(outcome, left.min(std::time::Duration::from_millis(20))) { + Ok((g, _)) => g, + Err(p) => p.into_inner().0, + }; + }; + drop(outcome); + #[cfg(test)] + self.waiting.fetch_sub(1, Ordering::SeqCst); + waited + } + + /// (A wasm32 build has one thread: a picture in flight there is being decoded further down + /// this thread's own stack.) + #[cfg(target_arch = "wasm32")] + fn wait(&self, _flight: &Flight) -> Waited { + Waited::No } /// Sequential playback of a movie (`loc`, at `t`): read the frame after it ahead. @@ -961,7 +1592,7 @@ impl Inner { let mut next = Self::locate(footage, next_t, float); next.key.size = loc.key.size; next.key.q8 = loc.key.q8; - if next.key != loc.key && !c.lru.map.contains_key(&next.key) && !c.inflight.contains(&next.key) { + if next.key != loc.key && !c.lru.map.contains_key(&next.key) && !c.inflight.contains_key(&next.key) { self.prefetch(footage, next_t, size, float, loc.key.q8, c.forgets); } } @@ -971,33 +1602,86 @@ impl Inner { fn prefetch(self: &Arc, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve, q8: bool, since: u64) { let (me, f) = (self.clone(), footage.clone()); self.prefetched.fetch_add(1, Ordering::Relaxed); - // A plain thread, not a rayon job: the decode below parallelises with rayon itself. + // A plain thread, not a rayon job: it waits for the decode. std::thread::spawn(move || { - let _ = me.frame_px(&f, t, false, size, float, q8, Some(since)); + let _ = me.frame_px(&f, t, false, size, float, q8, None, Some(since)); }); } #[cfg(target_arch = "wasm32")] fn prefetch(self: &Arc, _footage: &Footage, _t: Tick, _size: Option<(u32, u32)>, _float: FloatCurve, _q8: bool, _since: u64) {} - /// A still (image file or sequence frame) at `loc.key.size` when one is set: resampled as the - /// renderer would ([`FootageSource::frame_at_size`]), so the pool keeps the reduced frame and a - /// reduced-resolution render neither decodes nor resamples a large still again for every frame - /// (#1812: 21120-px plates at Quarter). Like the renderer's `footage_buf`, an image decoded - /// larger than the footage's nominal size (a smart object's pixels) is resampled too, and one - /// decoded smaller is not (the renderer scales the layer instead). - fn still_at_size(img: Image, loc: &Loc, footage: &Footage) -> Image { + /// A still (image file or sequence frame) at `loc.key.size` when one is set, made of its + /// whole decoded picture `img`: resampled as the renderer would ([`FootageSource::frame_at_size`]), + /// so the pool keeps the reduced frame and a reduced-resolution render neither decodes nor + /// resamples a large still again for every frame (#1812: 21120-px plates at Quarter). Like the + /// renderer's `footage_buf`, an image decoded larger than the footage's nominal size (a smart + /// object's pixels) is resampled too, and one decoded smaller is not (the renderer scales the + /// layer instead). + fn sized_still(img: Arc, loc: &Loc, footage: &Footage) -> Arc { let (w, h) = loc.key.size; let smaller = img.width == 0 || footage.width as f64 / img.width as f64 > 1.0 + 1e-9; if w == 0 || h == 0 || smaller || (w, h) == (img.width, img.height) { return img; } - effectcraft_raster::resample(&img, w, h) + Arc::new(effectcraft_raster::resample(&img, w, h)) } - fn decode(&self, loc: &Loc, footage: &Footage) -> Result { + /// Decode `loc`'s picture ([`Inner::decode_source`]) on the decode threads + /// ([`decode_threads`]) and block until it is done; on this thread where there are none + /// (wasm32) or this is one of them. With the files the decode read (see [`crate::reads`]): + /// collected on the thread that decodes, not noted anywhere (the caller notes them). + fn run_decode(self: &Arc, loc: &Loc, footage: &Footage) -> (Result, ReadFiles) { + #[cfg(not(target_arch = "wasm32"))] + if let Some(threads) = decode_threads() + && threads.current_thread_index().is_none() + { + let (tx, rx) = std::sync::mpsc::sync_channel(1); + let (me, at, f) = (self.clone(), loc.clone(), footage.clone()); + // The request's cancel flag and decoding hints go with it (#329). + let hints = filmcraft_media::cancel::Context::current(); + threads.spawn(move || { + #[cfg(not(test))] + let decoded = reads::captured(|| hints.run(|| me.decode_source(&at, &f))); + // (the decodes counted on that thread are this thread's) + #[cfg(test)] + let decoded = crate::exr_channels::counting(|| reads::captured(|| hints.run(|| me.decode_source(&at, &f)))); + let _ = tx.send(decoded); + }); + // A plain block: this thread runs nothing else meanwhile. + return match rx.recv() { + #[cfg(not(test))] + Ok(decoded) => decoded, + #[cfg(test)] + Ok((decoded, counted)) => { + crate::exr_channels::add_decodes(counted); + decoded + } + // (the decode panicked: what it read is unknown) + Err(_) => { + let mut files = ReadFiles::default(); + files.mark_incomplete(); + (Err(MediaError::Decode(format!("{}: the decode stopped", loc.key.path))), files) + } + }; + } + let _decoding = Decoding::new(); + reads::captured(|| self.decode_source(loc, footage)) + } + + /// Decode the picture `loc` names: a still whole, a movie frame at its size. + fn decode_source(&self, loc: &Loc, footage: &Footage) -> Result { + self.decodes.fetch_add(1, Ordering::Relaxed); + #[cfg(test)] + { + // (not holding the lock while it runs) + let gate = lock(&self.gate).clone(); + if let Some(answer) = gate.and_then(|g| g()) { + return answer.map(|img| Pixels::F32(Arc::new(img))); + } + } match loc.media_t { - None => self.decode_still(loc, footage).map(|img| Pixels::F32(Arc::new(Self::still_at_size(img, loc, footage)))), + None => self.decode_still(loc, footage).map(|img| Pixels::F32(Arc::new(img))), Some(_) => self.decode_media(loc, footage), } } @@ -1010,8 +1694,25 @@ impl Inner { if &**path == PLACEHOLDER { return Ok(colour_bars(footage.width, footage.height)); } + // OpenEXR: the picture's channels from the plane store, read chunk by chunk (#3271), with + // the channels effects read when they read this footage's (#474). + if crate::exr_planes::is_exr(path) { + use crate::exr_planes::Picture; + let extra = lock(&self.aux_footage).plan(&footage.path); + let picture = match loc.key.rows { + Some(rows) if extra.is_none() => crate::exr_planes::picture_rows(path, &self.exr_source(path), op, rows, (footage.width, footage.height)), + _ => crate::exr_planes::picture(path, &self.exr_source(path), op, extra.as_ref()), + }; + match picture { + Picture::Done(Ok(img)) => return Ok(img), + Picture::Done(Err(why)) => return Err(MediaError::Decode(format!("{path}: {why}"))), + Picture::Cancelled => return Err(MediaError::Cancelled), + // (the `image` crate decodes the whole file) + Picture::Legacy => {} + } + } let (bytes, file) = self.read_file(path); - reads::note(file.clone()); + reads::note(file); let bytes = bytes?; if let Some(img) = crate::dpx::decode(path, &bytes)? { return Ok(dynamic_to_image(&img, op)); @@ -1026,13 +1727,10 @@ impl Inner { { return Err(MediaError::Decode(format!("{path}: {why}"))); } - // An effect reads this footage's channels: the picture is made of the same decode (#474). - let shared = lock(&self.aux_footage).contains(&footage.path); - if shared - && path.to_ascii_lowercase().ends_with(".exr") - && let Some(img) = crate::exr_channels::cached_picture(path, bytes.clone(), &file, op) - { - return Ok(img); + // A hostile OpenEXR header (a data window a billion pixels wide over one tiny chunk) made + // the decoder allocate gigabytes for a block: refused before any decoder sees it. + if crate::still_format(path, &bytes) == Some(image::ImageFormat::OpenExr) && !crate::exr_index::safe_to_decode(&bytes) { + return Err(MediaError::Decode(format!("{path}: an OpenEXR part larger than this reader takes"))); } #[cfg(test)] crate::exr_channels::count_decode(false); @@ -1040,9 +1738,11 @@ impl Inner { Ok(img) => Ok(dynamic_to_image(&img, op)), // Over the size limit: the layered fallback would allocate its planes anyway. Err(e @ image::ImageError::Limits(_)) => Err(MediaError::Decode(format!("{path}: {e}"))), - // A multi-layer OpenEXR file without an unnamed RGB layer: its colour layer. - Err(e) => crate::exr_channels::layered_picture(path, bytes, &file, op, shared) - .map_err(|why| MediaError::Decode(format!("{path}: {}", why.unwrap_or_else(|| e.to_string())))), + // An OpenEXR file the decoder refuses (no unnamed RGB): its main picture, or black. + Err(e) => match crate::exr_channels::picture_image(&bytes) { + Some(img) => Ok(dynamic_to_image(&img, op)), + None => Err(MediaError::Decode(format!("{path}: {e}"))), + }, } } @@ -1088,6 +1788,64 @@ impl Inner { } } +/// The decoded frames in the common memory budget (#3271, #3298): each frame is worth what +/// decoding it took, per byte; the whole stills kept to resample other sizes shortly after +/// ([`CacheState::recent`]) are worth nothing. +impl effectcraft_render::memory::MemoryHolder for Inner { + fn name(&self) -> &'static str { + "footage frames" + } + fn bytes(&self) -> usize { + lock(&self.cache).held_bytes() + } + /// The older of the least recently used frame and the oldest whole still kept beside the + /// frames (#3271: whichever was used last goes first); a whole still is kept for a moment + /// only, to resample other sizes, so it is offered as worth nothing. Recycled buffers of + /// frames dropped go before either, at no cost. + fn oldest(&self) -> Option { + use effectcraft_render::memory::Candidate; + let c = lock(&self.cache); + if let Some(b) = c.lru.spare.last() { + return Some(Candidate { used: 0, bytes: b.len().saturating_mul(std::mem::size_of::()).max(1), cost_us: 0, protected: false }); + } + let frame = + c.oldest_frame().and_then(|(k, _)| c.lru.map.get(k)).map(|e| Candidate { used: e.used, bytes: e.bytes, cost_us: e.cost_us, protected: false }); + let still = c.oldest_recent().and_then(|i| c.recent.get(i)).map(|r| Candidate { used: r.used, bytes: r.bytes.max(1), cost_us: 0, protected: false }); + match (frame, still) { + (Some(f), Some(s)) => Some(if s.used < f.used { s } else { f }), + (f, s) => f.or(s), + } + } + fn drop_oldest(&self) -> usize { + let mut c = lock(&self.cache); + if !c.lru.spare.is_empty() { + return c.lru.drop_spare(); + } + let frame = c.oldest_frame().map(|(_, t)| t); + let at = c.oldest_recent(); + let still = at.and_then(|i| c.recent.get(i)).map(|r| r.used); + match (frame, still, at) { + (Some(f), Some(s), Some(i)) if s < f => c.recent.remove(i).map_or(0, |r| r.bytes.max(1)), + (None, Some(_), Some(i)) => c.recent.remove(i).map_or(0, |r| r.bytes.max(1)), + _ => c.drop_oldest_frame(), + } + } +} + +impl MediaPool { + /// The OpenEXR file holding the channels of `footage` at `t` (a still or a sequence frame). + fn aux_path(&self, footage: &Footage, t: Tick) -> Option> { + if footage.missing || !footage.has_video { + return None; + } + let loc = Inner::locate(footage, t, FloatCurve::Srgb); + if loc.media_t.is_some() || !crate::exr_planes::is_exr(&loc.key.path) { + return None; + } + Some(loc.key.path) + } +} + impl FootageSource for MediaPool { fn set_conform_folder(&self, folder: Option) { MediaPool::set_conform_folder(self, folder); @@ -1098,8 +1856,12 @@ impl FootageSource for MediaPool { } self.inner.model(&footage.path) } + /// The most the footage frames, and the decoded OpenEXR planes, hold by themselves (#3298: + /// the whole common budget on the desktop, the browser's caps there; the memory accountant + /// keeps them within the budget with the other caches). fn set_cache_budget(&self, bytes: usize) { self.set_budget(bytes); + crate::exr_planes::set_budget(bytes); } fn purge(&self) { self.clear_frames(); @@ -1132,6 +1894,17 @@ impl FootageSource for MediaPool { fn frame_with(&self, item: ItemId, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve) -> Option> { self.frame_sized(item, footage, t, size, float) } + fn frame_rows(&self, _item: ItemId, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve, rows: (i64, i64)) -> Option> { + if footage.missing { + return None; + } + Inner::frame_at_rows(&self.inner, footage, t, true, size, float, Some(rows)).ok() + } + /// Only an OpenEXR frame whose channels no effect reads is read by rows (others whole, see + /// [`Inner::frame_at_rows`]). + fn reads_rows(&self, footage: &Footage, t: Tick) -> bool { + !footage.missing && self.inner.reads_rows(footage, t) + } fn frame8(&self, _item: ItemId, footage: &Footage, t: Tick, float: FloatCurve) -> Option> { self.frame8_of(footage, t, float) } @@ -1167,21 +1940,47 @@ impl FootageSource for MediaPool { let given: HashSet = paths.iter().cloned().collect(); let mut wanted = lock(&self.inner.aux_footage); if given != wanted.given || !wanted.learned.is_empty() { - crate::exr_channels::release_held(); + crate::exr_planes::release_held(); } wanted.given = given; wanted.learned.clear(); } + fn set_localizer(&self, config: Option) { + crate::localize::configure(config); + } + + fn localize_status(&self) -> Option { + crate::localize::status() + } + + fn set_disk_cache(&self, cache: Option>) { + crate::exr_planes::set_disk_cache(cache.as_ref()); + } + + fn set_aux_needs(&self, needs: &[(String, AuxNeed)]) { + let mut wanted = lock(&self.inner.aux_footage); + let needs: HashMap = needs.iter().cloned().collect(); + if needs != wanted.needs { + crate::exr_planes::release_held(); + } + wanted.needs = needs; + } + + /// Every channel, the picture's too (no render asks for that: renders ask for what their + /// effects read, [`FootageSource::aux_for`]). fn aux(&self, _item: ItemId, footage: &Footage, t: Tick) -> Option> { - if footage.missing || !footage.has_video { - return None; - } - let loc = Inner::locate(footage, t, FloatCurve::Srgb); - if loc.media_t.is_some() || !loc.key.path.to_ascii_lowercase().ends_with(".exr") { - return None; - } - let path = loc.key.path.clone(); + let path = self.aux_path(footage, t)?; + crate::exr_planes::every_channel(&path, &self.inner.exr_source(&path)) + } + + fn aux_names(&self, _item: ItemId, footage: &Footage, t: Tick) -> Option> { + let path = self.aux_path(footage, t)?; + crate::exr_planes::names(&path, &self.inner.exr_source(&path)) + } + + fn aux_for(&self, _item: ItemId, footage: &Footage, t: Tick, need: &AuxNeed) -> Option> { + let path = self.aux_path(footage, t)?; { let mut wanted = lock(&self.inner.aux_footage); if !wanted.contains(&footage.path) { @@ -1192,7 +1991,7 @@ impl FootageSource for MediaPool { wanted.learned.insert(footage.path.clone()); } } - crate::exr_channels::cached(&path, || self.inner.read(&path).ok()) + crate::exr_planes::aux(&path, &self.inner.exr_source(&path), need) } fn audio(&self, _item: ItemId, footage: &Footage, t: Tick, frames: usize, rate: u32) -> Option> { @@ -1254,7 +2053,7 @@ mod tests { let f = Footage { path: "/a.png".into(), kind: FootageKind::Still, width: 2, height: 2, has_video: true, ..Default::default() }; let queued = lock(&pool.inner.cache).forgets; pool.forget("/a.png"); - let read = Inner::frame_px(&pool.inner, &f, Tick::ZERO, false, None, FloatCurve::Srgb, false, Some(queued)); + let read = Inner::frame_px(&pool.inner, &f, Tick::ZERO, false, None, FloatCurve::Srgb, false, None, Some(queued)); assert!(matches!(read, Err(MediaError::Cancelled)), "{:?}", read.err()); assert_eq!(pool.stats().frames, 0, "the forgotten file's frame came back"); pool.frame_at(&f, Tick::ZERO).unwrap(); @@ -1404,7 +2203,7 @@ mod tests { fn lru_respects_budget_and_recycles() { let mut c = Lru::default(); let img = || Pixels::F32(Arc::new(Image::new(16, 16))); // 4 KiB + overhead - let k = |i| Key { path: "a".into(), frame: i, interp: 0, matte: [0; 3], size: (0, 0), nominal: (0, 0), q8: false }; + let k = |i| Key { path: "a".into(), frame: i, interp: 0, matte: [0; 3], size: (0, 0), nominal: (0, 0), rows: None, q8: false }; let budget = 3 * (4096 + 64); for i in 0..10 { c.insert(k(i), img(), Arc::default(), budget); @@ -1420,12 +2219,100 @@ mod tests { assert!(c.take_spare(17).is_empty()); } + /// #3301 review: the recycled buffers are in the memory budget: counted, and the first the + /// accountant lets go, at no cost, before any cached frame. + #[test] + fn recycled_buffers_are_held_bytes_and_go_first() { + let pool = MediaPool::unregistered(usize::MAX); + let holder = pool.memory_holder(); + let px = 256 * std::mem::size_of::(); + { + let mut c = lock(&pool.inner.cache); + let k = |i| Key { path: "a".into(), frame: i, interp: 0, matte: [0; 3], size: (0, 0), nominal: (0, 0), rows: None, q8: false }; + for i in 0..3 { + c.lru.insert(k(i), Pixels::F32(Arc::new(Image::new(16, 16))), Arc::default(), usize::MAX); + } + c.lru.spare.push(vec![[0.0; 4]; 256]); + c.lru.spare.push(vec![[0.0; 4]; 256]); + } + let frames = 3 * (px + 64); + assert_eq!(holder.bytes(), frames + 2 * px, "frames and recycled buffers"); + let next = holder.oldest().unwrap(); + assert_eq!((next.bytes, next.cost_us), (px, 0), "a recycled buffer first, worth nothing"); + assert_eq!(holder.drop_oldest(), px); + assert_eq!(holder.drop_oldest(), px); + assert_eq!(holder.bytes(), frames, "the frames stay until the buffers are gone"); + assert_eq!(holder.drop_oldest(), px + 64, "then the oldest frame"); + } + + /// #3750 review: a frame or whole still whose pixels someone else holds is not offered to the + /// accountant (dropping it would free nothing yet): what goes is what nobody else holds. + #[test] + fn frames_and_stills_held_elsewhere_are_not_offered() { + let pool = MediaPool::unregistered(usize::MAX); + let holder = pool.memory_holder(); + let px = 256 * std::mem::size_of::(); + let k = |i| Key { path: "a".into(), frame: i, interp: 0, matte: [0; 3], size: (0, 0), nominal: (0, 0), rows: None, q8: false }; + let held = Arc::new(Image::new(16, 16)); + let held_still = Arc::new(Image::new(8, 8)); + { + let mut c = lock(&pool.inner.cache); + c.lru.insert(k(0), Pixels::F32(held.clone()), Arc::default(), usize::MAX); + c.lru.insert(k(1), Pixels::F32(Arc::new(Image::new(16, 16))), Arc::default(), usize::MAX); + c.lru.insert(k(2), Pixels::F32(Arc::new(Image::new(16, 16))), Arc::default(), usize::MAX); + // (two whole stills, older than every frame: the held one first) + let stamp = c.lru.clock; + c.recent.push_back(Recent { key: k(8), img: held_still.clone(), files: Arc::default(), bytes: 64 * 16, stamp, used: 0 }); + c.recent.push_back(Recent { key: k(9), img: Arc::new(Image::new(4, 4)), files: Arc::default(), bytes: 16 * 16, stamp, used: 0 }); + } + assert_eq!(holder.drop_oldest(), 16 * 16, "the still nobody holds"); + assert_eq!(holder.drop_oldest(), px + 64, "the oldest frame nobody holds"); + assert!(holder.oldest().is_none(), "the rest is held elsewhere, or the newest frame"); + let c = lock(&pool.inner.cache); + assert!(c.lru.map.contains_key(&k(0)) && c.recent.iter().any(|r| Arc::ptr_eq(&r.img, &held_still))); + drop(c); + drop((held, held_still)); + } + + /// #3750 review: a still asked for reduced and then whole is one picture both kept as a whole + /// still and cached as a frame; once nobody else holds it, those two references are the + /// cache's own, and the accountant can let it go. + #[test] + fn a_still_cached_both_as_frame_and_whole_still_is_offered() { + let pool = MediaPool::unregistered(usize::MAX); + let holder = pool.memory_holder(); + let f = plate(&pool, "/both.exr"); + Inner::frame_at(&pool.inner, &f, Tick::ZERO, true, Some((8, 4)), FloatCurve::Srgb).unwrap(); + let whole = Inner::frame_at(&pool.inner, &f, Tick::ZERO, true, None, FloatCurve::Srgb).unwrap(); + { + let c = lock(&pool.inner.cache); + assert!(c.recent.iter().any(|r| Arc::ptr_eq(&r.img, &whole)), "kept as a whole still"); + assert!(c.lru.map.values().any(|e| matches!(&e.img, Pixels::F32(i) if Arc::ptr_eq(i, &whole))), "and cached as a frame"); + } + assert!(holder.oldest().is_some()); + // Held by the caller: the whole still is not offered (only the reduced frame is). + assert_eq!(holder.drop_oldest(), 8 * 4 * std::mem::size_of::() + 64, "the reduced frame"); + assert!(holder.oldest().is_none(), "the picture the caller holds stays"); + let gone = Arc::downgrade(&whole); + drop(whole); + // (another still becomes the newest frame, which always stays) + let other = plate(&pool, "/other.exr"); + drop(Inner::frame_at(&pool.inner, &other, Tick::ZERO, true, None, FloatCurve::Srgb).unwrap()); + for _ in 0..8 { + if holder.drop_oldest() == 0 { + break; + } + } + assert!(gone.upgrade().is_none(), "nobody else holds it: both of the cache's references went, and its memory with them"); + assert!(lock(&pool.inner.cache).recent.is_empty()); + } + /// A frame kept as 8-bit levels is its own entry beside the float one, counted at 4 bytes /// a pixel. #[test] fn lru_keeps_8_bit_frames_apart_at_a_quarter_of_the_bytes() { let mut c = Lru::default(); - let k = |q8| Key { path: "a".into(), frame: 0, interp: 0, matte: [0; 3], size: (0, 0), nominal: (0, 0), q8 }; + let k = |q8| Key { path: "a".into(), frame: 0, interp: 0, matte: [0; 3], size: (0, 0), nominal: (0, 0), rows: None, q8 }; c.insert(k(false), Pixels::F32(Arc::new(Image::new(16, 16))), Arc::default(), usize::MAX); c.insert(k(true), Pixels::Q8(Arc::new(Frame8 { width: 16, height: 16, rgba: vec![0; 16 * 16 * 4] })), Arc::default(), usize::MAX); assert!(matches!(c.get(&k(false)), Some((Pixels::F32(_), _))) && matches!(c.get(&k(true)), Some((Pixels::Q8(_), _)))); @@ -1536,4 +2423,428 @@ mod tests { assert!(red("slashes.obj", &format!("/{}", dir.join("red.mtl").display()))); let _ = std::fs::remove_dir_all(&dir); } + + /// A 16 × 8 OpenEXR still with a different value in every pixel, registered with `pool` at + /// `path`. + fn plate(pool: &MediaPool, path: &str) -> Footage { + use exr::prelude::*; + let (w, h) = (16usize, 8usize); + let ch = |n: &str, k: f32| AnyChannel::new(n, FlatSamples::F32((0..w * h).map(|i| (i as f32 * k).sin().abs()).collect())); + let channels = AnyChannels::sort(vec![ch("R", 0.37), ch("G", 0.11), ch("B", 0.73), AnyChannel::new("A", FlatSamples::F32(vec![1.0; w * h]))].into()); + let image = exr::image::Image::from_layer(Layer::new((w, h), LayerAttributes::default(), Encoding::FAST_LOSSLESS, channels)); + let mut bytes = std::io::Cursor::new(Vec::new()); + image.write().to_buffered(&mut bytes).unwrap(); + let b: Arc<[u8]> = bytes.into_inner().into(); + pool.add_bytes(path, b.clone()); + crate::probe_bytes(path, b).unwrap() + } + + /// Hold `pool`'s decodes until `n` requests wait for one (at most 10 s), then answer with + /// `then` (`None`: decode the file). + fn gate(pool: &MediaPool, n: usize, then: impl Fn() -> Option> + Send + Sync + 'static) { + let inner = Arc::downgrade(&pool.inner); + *lock(&pool.inner.gate) = Some(Arc::new(move || { + let until = std::time::Instant::now() + std::time::Duration::from_secs(10); + while inner.upgrade().is_some_and(|i| i.waiting.load(Ordering::SeqCst) < n) && std::time::Instant::now() < until { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + then() + })); + } + + type Job = Box T + Send>; + + /// Run `jobs` at once, each on a rayon worker of its own (as the viewer's frame workers ask + /// for frames), and collect what they return; a job that panics returns nothing, and one + /// that hangs fails the test (20 s) instead of hanging it. + fn on_workers(jobs: Vec>) -> Vec { + let n = jobs.len(); + let workers = rayon::ThreadPoolBuilder::new().num_threads(n).panic_handler(|_| {}).build().unwrap(); + let start = Arc::new(std::sync::Barrier::new(n)); + let (tx, rx) = std::sync::mpsc::channel(); + for job in jobs { + let (tx, start) = (tx.clone(), start.clone()); + workers.spawn(move || { + // (each worker holds one job until all have started) + start.wait(); + let _ = tx.send(job()); + }); + } + drop(tx); + (0..n).map_while(|_| rx.recv_timeout(std::time::Duration::from_secs(20)).ok()).collect() + } + + /// Requests for the frame of `f` on `pool`, one at each of `sizes`, as [`on_workers`] jobs. + fn requests(pool: &MediaPool, f: &Footage, sizes: &[Option<(u32, u32)>]) -> Vec, Result>)>> { + sizes + .iter() + .map(|&size| { + let (pool, f) = (pool.clone(), f.clone()); + Box::new(move || (size, Inner::frame_at(&pool.inner, &f, Tick::ZERO, true, size, FloatCurve::Srgb))) as Job<_> + }) + .collect() + } + + /// #3269: requests for a frame being decoded wait for that decode and take its picture, also + /// on rayon workers (the viewer's frame workers), which each decoded a private copy before. + #[test] + fn concurrent_requests_for_a_frame_decode_it_once() { + let pool = MediaPool::new(); + let f = plate(&pool, "/plate.exr"); + const N: usize = 8; + gate(&pool, N - 1, || None); + let got = on_workers(requests(&pool, &f, &[None; N])); + assert_eq!(got.len(), N, "every request came back"); + let first = got[0].1.as_ref().unwrap().clone(); + for (_, img) in &got { + assert!(Arc::ptr_eq(img.as_ref().unwrap(), &first), "the same picture"); + } + assert_eq!(pool.stats().decodes, 1, "one decode for {N} requests"); + assert!(lock(&pool.inner.cache).inflight.is_empty(), "the flight ended"); + } + + /// #3269: a still asked for at several sizes at once (a reduced viewer, the Project panel's + /// thumbnail of its comp) is decoded once, and each size is what decoding it alone gives. + #[test] + fn sizes_of_a_still_asked_for_at_once_share_one_decode() { + let whole = { + let alone = MediaPool::new(); + let f = plate(&alone, "/plate.exr"); + alone.frame_at(&f, Tick::ZERO).unwrap() + }; + let pool = MediaPool::new(); + let f = plate(&pool, "/plate.exr"); + let sizes = [Some((8, 4)), Some((4, 2)), None]; + gate(&pool, sizes.len() - 1, || None); + let got = on_workers(requests(&pool, &f, &sizes)); + assert_eq!(got.len(), sizes.len(), "every request came back"); + assert_eq!(pool.stats().decodes, 1, "one decode for all sizes"); + for (size, img) in got { + let img = img.unwrap(); + match size { + None => assert_eq!(img.data, whole.data), + Some((w, h)) => { + assert_eq!((img.width, img.height), (w, h)); + assert_eq!(img.data, effectcraft_raster::resample(&whole, w, h).data, "{w}×{h} as decoded alone"); + } + } + } + } + + /// #3269: a second size of a still shown reduced (the thumbnail after the viewer) is + /// resampled from the first request's decode, not decoded again, and the whole picture is + /// not kept in the frame cache (#1812). + #[test] + fn a_second_size_of_a_still_is_resampled_from_the_first_decode() { + let whole = { + let alone = MediaPool::new(); + let f = plate(&alone, "/plate.exr"); + alone.frame_at(&f, Tick::ZERO).unwrap() + }; + let pool = MediaPool::new(); + let f = plate(&pool, "/plate.exr"); + let at = |size| Inner::frame_at(&pool.inner, &f, Tick::ZERO, true, Some(size), FloatCurve::Srgb).unwrap(); + let viewer = at((8, 4)); + let thumb = at((4, 2)); + assert_eq!(pool.stats().decodes, 1, "the thumbnail did not decode the file again"); + assert_eq!(viewer.data, effectcraft_raster::resample(&whole, 8, 4).data); + assert_eq!(thumb.data, effectcraft_raster::resample(&whole, 4, 2).data, "as decoded alone"); + assert!(lock(&pool.inner.cache).lru.map.keys().all(|k| k.size != (0, 0)), "the whole picture is not in the frame cache"); + // Forgetting the file forgets its whole picture too. + pool.forget("/plate.exr"); + at((2, 1)); + assert_eq!(pool.stats().decodes, 2); + } + + /// #3269: when the decode others wait for fails, or panics, every waiting request gets an + /// error and none hangs; the next request decodes again. + #[test] + fn a_failed_decode_fails_every_waiting_request() { + for panics in [false, true] { + let pool = MediaPool::new(); + let f = plate(&pool, "/broken.exr"); + const N: usize = 6; + gate(&pool, N - 1, move || if panics { panic!("a decoder bug") } else { Some(Err(MediaError::Decode("/broken.exr: a bad block".into()))) }); + let got = on_workers(requests(&pool, &f, &[None; N])); + let errors: Vec = got.iter().map(|(_, r)| r.as_ref().err().map(ToString::to_string).unwrap_or_default()).collect(); + assert_eq!(got.len(), N, "panics: {panics}, {errors:?}"); + let why = if panics { "the decode stopped" } else { "a bad block" }; + assert!(errors.iter().all(|e| e.contains(why)), "panics: {panics}, {errors:?}"); + assert_eq!(pool.stats().decodes, 1, "the waiting requests did not decode"); + assert!(lock(&pool.inner.cache).inflight.is_empty(), "the flight ended"); + *lock(&pool.inner.gate) = None; + assert!(pool.frame_at(&f, Tick::ZERO).is_ok(), "decodes again"); + } + } + + /// #3269: a decode runs on the decode threads, not on the frame worker asking for it: a frame + /// worker that ran part of it (rayon lets a worker waiting in a parallel loop take another + /// job) could take a request waiting for that very decode, which then never finished. Here + /// the decode works in parallel while a request for the same picture comes to the frame + /// workers: none of its work runs there, and both requests are answered at once. + #[test] + fn a_decode_runs_off_the_frame_workers() { + use rayon::prelude::*; + let pool = MediaPool::new(); + let f = plate(&pool, "/plate.exr"); + let workers = Arc::new(rayon::ThreadPoolBuilder::new().num_threads(2).build().unwrap()); + let on_frame_workers = Arc::new(AtomicU64::new(0)); + let (tx, rx) = std::sync::mpsc::channel(); + { + let (workers, seen, asker, f, tx) = (workers.clone(), on_frame_workers.clone(), pool.clone(), f.clone(), tx.clone()); + let inner = Arc::downgrade(&pool.inner); + *lock(&pool.inner.gate) = Some(Arc::new(move || { + let (asker, f, tx) = (asker.clone(), f.clone(), tx.clone()); + workers.spawn(move || { + let _ = tx.send(asker.frame_at(&f, Tick::ZERO)); + }); + (0..64).into_par_iter().for_each(|_| { + if workers.current_thread_index().is_some() { + seen.fetch_add(1, Ordering::SeqCst); + } + std::thread::sleep(std::time::Duration::from_millis(1)); + }); + let until = std::time::Instant::now() + std::time::Duration::from_secs(5); + while inner.upgrade().is_some_and(|i| i.waiting.load(Ordering::SeqCst) < 1) && std::time::Instant::now() < until { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + None + })); + } + let started = std::time::Instant::now(); + { + let (pool, f, tx) = (pool.clone(), f.clone(), tx.clone()); + workers.spawn(move || { + let _ = tx.send(pool.frame_at(&f, Tick::ZERO)); + }); + } + drop(tx); + let got: Vec<_> = (0..2).map_while(|_| rx.recv_timeout(std::time::Duration::from_secs(20)).ok()).collect(); + // (the gate holds a pool: let it go) + *lock(&pool.inner.gate) = None; + assert_eq!(got.len(), 2, "both requests were answered"); + assert!(got.iter().all(Result::is_ok)); + assert!(started.elapsed() < WAIT_LIMIT, "nobody waited out the time limit: {:?}", started.elapsed()); + assert_eq!(on_frame_workers.load(Ordering::SeqCst), 0, "no part of the decode ran on a frame worker"); + assert_eq!(pool.stats().decodes, 1); + } + + /// Where a thread decodes a picture itself (no decode threads), a request that comes to it + /// meanwhile (a rayon worker runs other jobs while its decode waits on its parallel work) + /// doesn't wait for a picture being decoded: that could be its own decode further down the + /// stack. It decodes a copy instead. + #[test] + fn a_thread_decoding_a_picture_does_not_wait_for_one() { + let pool = MediaPool::new(); + let f = plate(&pool, "/plate.exr"); + let flight = current_flight(&pool); + lock(&pool.inner.cache).inflight.insert(Key { size: (0, 0), nominal: (0, 0), ..Inner::locate(&f, Tick::ZERO, FloatCurve::Srgb).key }, flight); + let decoding = Decoding::new(); + let started = std::time::Instant::now(); + assert!(pool.frame_at(&f, Tick::ZERO).is_ok()); + assert!(started.elapsed() < WAIT_LIMIT, "did not wait for the flight"); + drop(decoding); + assert_eq!(OWNED.with(Cell::get), 0); + } + + /// #329: a request waiting for another's decode gives up once it is called off itself. + #[test] + fn a_waiting_request_called_off_stops_waiting() { + let pool = MediaPool::new(); + let f = plate(&pool, "/plate.exr"); + let flight = current_flight(&pool); + lock(&pool.inner.cache).inflight.insert(Key { size: (0, 0), nominal: (0, 0), ..Inner::locate(&f, Tick::ZERO, FloatCurve::Srgb).key }, flight); + let cancel = Arc::new(AtomicBool::new(false)); + let started = std::time::Instant::now(); + std::thread::scope(|s| { + s.spawn(|| { + std::thread::sleep(std::time::Duration::from_millis(50)); + cancel.store(true, Ordering::Relaxed); + }); + let got = filmcraft_media::cancel::with_cancel(&cancel, || pool.frame_at(&f, Tick::ZERO)); + assert!(matches!(got, Err(MediaError::Cancelled)), "{:?}", got.err()); + }); + assert!(started.elapsed() < WAIT_LIMIT); + } + + /// #3269: a whole still kept for a second size is kept within its own cap, and not after + /// the frame cache has moved on. + #[test] + fn recent_whole_stills_are_capped_and_expire() { + let key = |i| Key { path: "/s.exr".into(), frame: i, interp: 0, matte: [0; 3], size: (0, 0), nominal: (0, 0), rows: None, q8: false }; + let mut c = CacheState::default(); + // 64 KiB each (64 × 64 pixels of 16 bytes), a budget of 512 KiB: room for 4. + for i in 0..6 { + c.keep_recent(key(i), Arc::new(Image::new(64, 64)), Arc::default(), 512 << 10); + } + assert!(c.recent(&key(1)).is_none() && c.recent(&key(2)).is_some() && c.recent(&key(5)).is_some()); + // Larger than the cap: not kept. + c.keep_recent(key(9), Arc::new(Image::new(512, 512)), Arc::default(), 512 << 10); + assert!(c.recent(&key(9)).is_none()); + c.lru.clock += RECENT_AGE + 1; + assert!(c.recent(&key(5)).is_none(), "expired"); + } + + /// #3270 review: lowering the budget drops whole stills beyond the new cap at once (they + /// were kept until the next one was), and the stats count them. + #[test] + fn a_lower_budget_trims_recent_whole_stills() { + let pool = MediaPool::new(); + let f = plate(&pool, "/plate.exr"); + Inner::frame_at(&pool.inner, &f, Tick::ZERO, true, Some((8, 4)), FloatCurve::Srgb).unwrap(); + let whole = 16 * 8 * std::mem::size_of::(); + assert_eq!(pool.stats().recent_bytes, whole); + pool.set_budget(whole); + assert_eq!(pool.stats().recent_bytes, 0, "half the new budget holds no whole still"); + assert!(lock(&pool.inner.cache).recent.is_empty()); + } + + /// A flight of `pool`'s current generation (one requests join). + fn current_flight(pool: &MediaPool) -> Arc { + Arc::new(Flight { generation: lock(&pool.inner.cache).generation, ..Flight::default() }) + } + + /// #3270 review: a request made after a file was forgotten (it changed on disk) while its + /// decode was in flight doesn't join that decode: it got the old pixels, and kept them as + /// the new file's. + #[test] + fn a_request_after_forget_does_not_join_the_old_decode() { + let pool = MediaPool::new(); + let f = plate(&pool, "/plate.exr"); + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + { + let (calls, inner) = (calls.clone(), Arc::downgrade(&pool.inner)); + // The first decode (of the old file) waits for a request to join it (2 s at most) + // and answers with a black picture; later ones decode the file. + *lock(&pool.inner.gate) = Some(Arc::new(move || { + if calls.fetch_add(1, Ordering::SeqCst) > 0 { + return None; + } + let until = std::time::Instant::now() + std::time::Duration::from_secs(2); + while inner.upgrade().is_some_and(|i| i.waiting.load(Ordering::SeqCst) < 1) && std::time::Instant::now() < until { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + Some(Ok(Image::new(16, 8))) + })); + } + std::thread::scope(|s| { + let old = s.spawn(|| pool.frame_at(&f, Tick::ZERO)); + while calls.load(Ordering::SeqCst) == 0 { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + pool.forget("/plate.exr"); + let new = pool.frame_at(&f, Tick::ZERO).unwrap(); + assert!(new.data.iter().any(|p| p[0] > 0.0), "the file's pixels, not the old decode's"); + assert!(old.join().unwrap().is_ok()); + }); + *lock(&pool.inner.gate) = None; + let again = pool.frame_at(&f, Tick::ZERO).unwrap(); + assert!(again.data.iter().any(|p| p[0] > 0.0), "the old decode's pixels were not kept"); + } + + /// #3270 review: forgetting one file (a file watcher's change, `add_bytes`) leaves another + /// file's decode in flight joinable and cached: a global count made every other decode + /// stale, so requests decoded those files again and nothing was kept. + #[test] + fn forgetting_one_file_keeps_another_files_decode() { + let pool = MediaPool::new(); + let f = plate(&pool, "/a.exr"); + let other = plate(&pool, "/b.exr"); + let (pool_a, f_a) = (pool.clone(), f.clone()); + let started = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let started_a = started.clone(); + // The decode waits (2 s at most) for a request to join it, then decodes the file. + *lock(&pool.inner.gate) = { + let inner = Arc::downgrade(&pool.inner); + Some(Arc::new(move || { + started_a.store(true, Ordering::SeqCst); + let until = std::time::Instant::now() + std::time::Duration::from_secs(2); + while inner.upgrade().is_some_and(|i| i.waiting.load(Ordering::SeqCst) < 1) && std::time::Instant::now() < until { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + None + })) + }; + std::thread::scope(|s| { + let first = s.spawn(move || pool_a.frame_at(&f_a, Tick::ZERO)); + while !started.load(Ordering::SeqCst) { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + pool.forget(&other.path); + let joined = pool.frame_at(&f, Tick::ZERO).unwrap(); + let first = first.join().unwrap().unwrap(); + assert!(Arc::ptr_eq(&joined, &first), "the request joined the decode in flight"); + }); + assert_eq!(pool.stats().decodes, 1, "one decode"); + pool.frame_at(&f, Tick::ZERO).unwrap(); + assert_eq!(pool.stats().decodes, 1, "and its picture was kept"); + *lock(&pool.inner.gate) = None; + } + + /// #3750 review: a decode running when the frames are cleared (Purge) keeps nothing: its + /// frame doesn't come back into the cache after Purge emptied it. + #[test] + fn a_decode_running_across_purge_keeps_nothing() { + let pool = MediaPool::new(); + let f = plate(&pool, "/purge.exr"); + let started = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let go = Arc::new(std::sync::atomic::AtomicBool::new(false)); + { + let (started, go) = (started.clone(), go.clone()); + // The decode waits (2 s at most) until the frames were cleared, then decodes the file. + *lock(&pool.inner.gate) = Some(Arc::new(move || { + started.store(true, Ordering::SeqCst); + let until = std::time::Instant::now() + std::time::Duration::from_secs(2); + while !go.load(Ordering::SeqCst) && std::time::Instant::now() < until { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + None + })); + } + std::thread::scope(|s| { + let decoding = s.spawn(|| pool.frame_at(&f, Tick::ZERO)); + while !started.load(Ordering::SeqCst) { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + pool.clear_frames(); + go.store(true, Ordering::SeqCst); + assert!(decoding.join().unwrap().is_ok(), "the request still gets its picture"); + }); + *lock(&pool.inner.gate) = None; + assert_eq!(pool.stats().frames, 0, "nothing kept after Purge"); + } + + /// Forgotten paths are remembered per path and boundedly: past [`MAX_FORGOTTEN`], everything + /// that started before counts as stale. + #[test] + fn forgotten_paths_stay_bounded() { + let mut c = CacheState::default(); + let at = c.generation; + c.forgot("/a.exr"); + assert!(c.stale("/a.exr", at) && !c.stale("/b.exr", at) && !c.stale("/a.exr", c.generation)); + for i in 0..MAX_FORGOTTEN + 10 { + c.forgot(&format!("/{i}.exr")); + } + assert!(c.forgotten.len() <= MAX_FORGOTTEN); + assert!(c.stale("/b.exr", at), "older than the remembered paths: stale"); + assert!(!c.stale("/b.exr", c.generation)); + } + + /// #3301: open movie/audio files are capped: beyond [`MAX_OPEN_SOURCES`] the least recently + /// asked for is closed (a project of thousands of clips kept every one open). + #[test] + fn open_sources_are_capped_least_recently_used_first() { + let mut s = Sources::default(); + let path = |i: usize| -> Arc { format!("/clips/{i}.mov").into() }; + let first = s.slot(&path(0)); + for i in 1..MAX_OPEN_SOURCES + 40 { + s.slot(&path(i)); + // (the first clip is asked for again and again: it stays) + s.slot(&path(0)); + } + assert_eq!(s.map.len(), MAX_OPEN_SOURCES); + assert!(s.map.contains_key(&path(0)), "used lately: kept"); + assert!(!s.map.contains_key(&path(1)), "the least recently used went"); + assert!(Arc::ptr_eq(&first, &s.slot(&path(0))), "a kept slot is the same slot"); + } } diff --git a/crates/media/src/probe.rs b/crates/media/src/probe.rs index 194eebc47..cf62eb910 100644 --- a/crates/media/src/probe.rs +++ b/crates/media/src/probe.rs @@ -280,6 +280,9 @@ fn probe_still_bytes(path: &str, bytes: &[u8], fmt: image::ImageFormat) -> Resul { return Err(MediaError::Decode(format!("{path}: {why}"))); } + if fmt == image::ImageFormat::OpenExr && !crate::exr_index::safe_to_decode(bytes) { + return Err(MediaError::Decode(format!("{path}: an OpenEXR part larger than this reader takes"))); + } let reader = image::ImageReader::with_format(std::io::Cursor::new(bytes), fmt); let (w, h, has_alpha) = match reader.into_decoder() { Ok(mut dec) => { @@ -289,10 +292,16 @@ fn probe_still_bytes(path: &str, bytes: &[u8], fmt: image::ImageFormat) -> Resul (w, h, dec.color_type().has_alpha()) } Err(e) => { - // A multi-layer OpenEXR file without an unnamed RGB layer. - let img = (fmt == image::ImageFormat::OpenExr).then(|| crate::exr_channels::layered_image(bytes)).flatten(); - let img = img.ok_or_else(|| MediaError::Decode(format!("{path}: {e}")))?; - (img.width(), img.height(), img.color().has_alpha()) + // An OpenEXR file without an unnamed RGB part (a `Y` picture, or named layers only, + // shown black): its picture's size and alpha from the headers alone (#3271), no + // pixels decoded. + let size = (fmt == image::ImageFormat::OpenExr).then(|| crate::exr_channels::picture_size(bytes)).flatten(); + let (w, h, alpha) = size.ok_or_else(|| MediaError::Decode(format!("{path}: {e}")))?; + // (as every still: no larger than the renderer can hold as floats) + if u64::from(w) * u64::from(h) > MAX_STILL_PIXELS { + return Err(MediaError::Decode(format!("{path}: a {w}×{h} OpenEXR picture is larger than a still may be"))); + } + (w, h, alpha) } }; Ok(still_footage(path, w, h, fmt, has_alpha)) diff --git a/crates/media/tests/it/exr_golden.rs b/crates/media/tests/it/exr_golden.rs index f760ed7c2..ff860c326 100644 --- a/crates/media/tests/it/exr_golden.rs +++ b/crates/media/tests/it/exr_golden.rs @@ -248,8 +248,9 @@ fn files() -> Vec<(&'static str, Vec, bool)> { true, ), ( - // The image crate shows the part "depth" (the first with R, G and B), whose planes are - // filled with the background depth outside its data window: decoded by the image crate. + // The picture is the part "depth" (the first with R, G and B), 0 outside its data window + // as the image crate shows it, while its planes keep the background depth there for + // effects (the part's name reads as depth). "multipart_depth_named_rgb_zip16", write( vec![ @@ -336,7 +337,9 @@ fn hashes(name: &str, bytes: &[u8], aux_first: bool) -> Vec<(String, u64, bool)> out } -/// Hashes taken on main before #474's shared decode (`EXR_GOLDEN_PRINT=1`). +/// Hashes taken on main before #474's shared decode (`EXR_GOLDEN_PRINT=1`). The pictures of +/// the files of named layers only (`layered_*`, `multipart_blender5_rle`) were re-pinned when the +/// picture became After Effects' main picture (black for those files, their channels unchanged). const PINNED: &[(&str, &str, u64)] = &[ ("rgba_half_zip16", "probe", 0x0a32e074a28c1f66), ("rgba_half_zip16", "probed/linear", 0xa84600283dce98f6), @@ -352,12 +355,12 @@ const PINNED: &[(&str, &str, u64)] = &[ ("rgb_float_piz", "ignore/linear", 0xa6e8fbbad371a2ae), ("rgb_float_piz", "preserve_rgb", 0xa6e8fbbad371a2ae), ("rgb_float_piz", "aux", 0x554623d237c2e5ef), - ("layered_rle", "probe", 0x0a32e074a28c1f66), - ("layered_rle", "probed/linear", 0xa84600283dce98f6), - ("layered_rle", "straight/linear", 0xf028e1367a2fbb30), - ("layered_rle", "premul/linear", 0xa84600283dce98f6), - ("layered_rle", "ignore/linear", 0xa90a57f9a67f7468), - ("layered_rle", "preserve_rgb", 0xc8e0050f5efe75b7), + ("layered_rle", "probe", 0x6a38346c4c5662d5), + ("layered_rle", "probed/linear", 0x63d9c6245f75ef06), + ("layered_rle", "straight/linear", 0x63d9c6245f75ef06), + ("layered_rle", "premul/linear", 0x63d9c6245f75ef06), + ("layered_rle", "ignore/linear", 0x63d9c6245f75ef06), + ("layered_rle", "preserve_rgb", 0x63d9c6245f75ef06), ("layered_rle", "aux", 0xa6b9bd9f02c192ad), ("unnamed_rgb_plus_layers_zip1", "probe", 0x0a32e074a28c1f66), ("unnamed_rgb_plus_layers_zip1", "probed/linear", 0xa84600283dce98f6), @@ -380,12 +383,12 @@ const PINNED: &[(&str, &str, u64)] = &[ ("multipart_diffuse_then_beauty_zip1", "ignore/linear", 0xa90a57f9a67f7468), ("multipart_diffuse_then_beauty_zip1", "preserve_rgb", 0xa90a57f9a67f7468), ("multipart_diffuse_then_beauty_zip1", "aux", 0x6724d6dfd56a04cb), - ("multipart_blender5_rle", "probe", 0x0a32e074a28c1f66), - ("multipart_blender5_rle", "probed/linear", 0xa84600283dce98f6), - ("multipart_blender5_rle", "straight/linear", 0xf028e1367a2fbb30), - ("multipart_blender5_rle", "premul/linear", 0xa84600283dce98f6), - ("multipart_blender5_rle", "ignore/linear", 0xa90a57f9a67f7468), - ("multipart_blender5_rle", "preserve_rgb", 0xc8e0050f5efe75b7), + ("multipart_blender5_rle", "probe", 0x6a38346c4c5662d5), + ("multipart_blender5_rle", "probed/linear", 0x63d9c6245f75ef06), + ("multipart_blender5_rle", "straight/linear", 0x63d9c6245f75ef06), + ("multipart_blender5_rle", "premul/linear", 0x63d9c6245f75ef06), + ("multipart_blender5_rle", "ignore/linear", 0x63d9c6245f75ef06), + ("multipart_blender5_rle", "preserve_rgb", 0x63d9c6245f75ef06), ("multipart_blender5_rle", "aux", 0x522ae4819dd92e89), ("unnamed_rgb_window_smaller_zip16", "probe", 0x0a32e074a28c1f66), ("unnamed_rgb_window_smaller_zip16", "probed/linear", 0x19eb3b1a88d108a7), @@ -401,19 +404,19 @@ const PINNED: &[(&str, &str, u64)] = &[ ("rgb_float_window_larger_piz", "ignore/linear", 0x8e3847d48f9967a6), ("rgb_float_window_larger_piz", "preserve_rgb", 0x8e3847d48f9967a6), ("rgb_float_window_larger_piz", "aux", 0x7ccc9f86e6ff6140), - ("layered_window_smaller_zip16", "probe", 0x0a32e074a28c1f66), - ("layered_window_smaller_zip16", "probed/linear", 0x19eb3b1a88d108a7), - ("layered_window_smaller_zip16", "straight/linear", 0x2c73f9acaa936420), - ("layered_window_smaller_zip16", "premul/linear", 0x19eb3b1a88d108a7), - ("layered_window_smaller_zip16", "ignore/linear", 0x3b86057d18a16bf0), - ("layered_window_smaller_zip16", "preserve_rgb", 0x5b999014e4a64bb2), + ("layered_window_smaller_zip16", "probe", 0x6a38346c4c5662d5), + ("layered_window_smaller_zip16", "probed/linear", 0x63d9c6245f75ef06), + ("layered_window_smaller_zip16", "straight/linear", 0x63d9c6245f75ef06), + ("layered_window_smaller_zip16", "premul/linear", 0x63d9c6245f75ef06), + ("layered_window_smaller_zip16", "ignore/linear", 0x63d9c6245f75ef06), + ("layered_window_smaller_zip16", "preserve_rgb", 0x63d9c6245f75ef06), ("layered_window_smaller_zip16", "aux", 0x443480a1d789e63c), - ("layered_window_larger_piz", "probe", 0x0a32e074a28c1f66), - ("layered_window_larger_piz", "probed/linear", 0x443afe4029748836), - ("layered_window_larger_piz", "straight/linear", 0xb32b44880f746826), - ("layered_window_larger_piz", "premul/linear", 0x443afe4029748836), - ("layered_window_larger_piz", "ignore/linear", 0xaa01706accce2cc4), - ("layered_window_larger_piz", "preserve_rgb", 0xb2cbb40b10bc56b4), + ("layered_window_larger_piz", "probe", 0x6a38346c4c5662d5), + ("layered_window_larger_piz", "probed/linear", 0x63d9c6245f75ef06), + ("layered_window_larger_piz", "straight/linear", 0x63d9c6245f75ef06), + ("layered_window_larger_piz", "premul/linear", 0x63d9c6245f75ef06), + ("layered_window_larger_piz", "ignore/linear", 0x63d9c6245f75ef06), + ("layered_window_larger_piz", "preserve_rgb", 0x63d9c6245f75ef06), ("layered_window_larger_piz", "aux", 0xb7d91c8eea56a772), ("unnamed_rgb_plus_layers_tiled_zip16", "probe", 0x0a32e074a28c1f66), ("unnamed_rgb_plus_layers_tiled_zip16", "probed/linear", 0x7612f20634fe957e), @@ -422,12 +425,12 @@ const PINNED: &[(&str, &str, u64)] = &[ ("unnamed_rgb_plus_layers_tiled_zip16", "ignore/linear", 0xbbf236635dcaac90), ("unnamed_rgb_plus_layers_tiled_zip16", "preserve_rgb", 0x15b555a243d79613), ("unnamed_rgb_plus_layers_tiled_zip16", "aux", 0x3d1439eed2202e41), - ("layered_tiled_rle", "probe", 0x0a32e074a28c1f66), - ("layered_tiled_rle", "probed/linear", 0xa84600283dce98f6), - ("layered_tiled_rle", "straight/linear", 0xf028e1367a2fbb30), - ("layered_tiled_rle", "premul/linear", 0xa84600283dce98f6), - ("layered_tiled_rle", "ignore/linear", 0xa90a57f9a67f7468), - ("layered_tiled_rle", "preserve_rgb", 0xc8e0050f5efe75b7), + ("layered_tiled_rle", "probe", 0x6a38346c4c5662d5), + ("layered_tiled_rle", "probed/linear", 0x63d9c6245f75ef06), + ("layered_tiled_rle", "straight/linear", 0x63d9c6245f75ef06), + ("layered_tiled_rle", "premul/linear", 0x63d9c6245f75ef06), + ("layered_tiled_rle", "ignore/linear", 0x63d9c6245f75ef06), + ("layered_tiled_rle", "preserve_rgb", 0x63d9c6245f75ef06), ("layered_tiled_rle", "aux", 0xa6b9bd9f02c192ad), ("unnamed_rgb_plus_layers_mipmapped_zip16", "probe", 0x0a32e074a28c1f66), ("unnamed_rgb_plus_layers_mipmapped_zip16", "probed/linear", 0xa84600283dce98f6), @@ -436,12 +439,12 @@ const PINNED: &[(&str, &str, u64)] = &[ ("unnamed_rgb_plus_layers_mipmapped_zip16", "ignore/linear", 0xa90a57f9a67f7468), ("unnamed_rgb_plus_layers_mipmapped_zip16", "preserve_rgb", 0xc8e0050f5efe75b7), ("unnamed_rgb_plus_layers_mipmapped_zip16", "aux", 0x27cc9b53d0862db1), - ("layered_mipmapped_piz", "probe", 0x0a32e074a28c1f66), - ("layered_mipmapped_piz", "probed/linear", 0xa84600283dce98f6), - ("layered_mipmapped_piz", "straight/linear", 0xf028e1367a2fbb30), - ("layered_mipmapped_piz", "premul/linear", 0xa84600283dce98f6), - ("layered_mipmapped_piz", "ignore/linear", 0xa90a57f9a67f7468), - ("layered_mipmapped_piz", "preserve_rgb", 0xc8e0050f5efe75b7), + ("layered_mipmapped_piz", "probe", 0x6a38346c4c5662d5), + ("layered_mipmapped_piz", "probed/linear", 0x63d9c6245f75ef06), + ("layered_mipmapped_piz", "straight/linear", 0x63d9c6245f75ef06), + ("layered_mipmapped_piz", "premul/linear", 0x63d9c6245f75ef06), + ("layered_mipmapped_piz", "ignore/linear", 0x63d9c6245f75ef06), + ("layered_mipmapped_piz", "preserve_rgb", 0x63d9c6245f75ef06), ("layered_mipmapped_piz", "aux", 0xa6b9bd9f02c192ad), ("unnamed_rgb_plus_layers_decreasing_zip1", "probe", 0x0a32e074a28c1f66), ("unnamed_rgb_plus_layers_decreasing_zip1", "probed/linear", 0x19eb3b1a88d108a7), @@ -450,12 +453,12 @@ const PINNED: &[(&str, &str, u64)] = &[ ("unnamed_rgb_plus_layers_decreasing_zip1", "ignore/linear", 0x3b86057d18a16bf0), ("unnamed_rgb_plus_layers_decreasing_zip1", "preserve_rgb", 0x5b999014e4a64bb2), ("unnamed_rgb_plus_layers_decreasing_zip1", "aux", 0x8f78d3233450acf3), - ("layered_decreasing_rle", "probe", 0x0a32e074a28c1f66), - ("layered_decreasing_rle", "probed/linear", 0xa84600283dce98f6), - ("layered_decreasing_rle", "straight/linear", 0xf028e1367a2fbb30), - ("layered_decreasing_rle", "premul/linear", 0xa84600283dce98f6), - ("layered_decreasing_rle", "ignore/linear", 0xa90a57f9a67f7468), - ("layered_decreasing_rle", "preserve_rgb", 0xc8e0050f5efe75b7), + ("layered_decreasing_rle", "probe", 0x6a38346c4c5662d5), + ("layered_decreasing_rle", "probed/linear", 0x63d9c6245f75ef06), + ("layered_decreasing_rle", "straight/linear", 0x63d9c6245f75ef06), + ("layered_decreasing_rle", "premul/linear", 0x63d9c6245f75ef06), + ("layered_decreasing_rle", "ignore/linear", 0x63d9c6245f75ef06), + ("layered_decreasing_rle", "preserve_rgb", 0x63d9c6245f75ef06), ("layered_decreasing_rle", "aux", 0xa6b9bd9f02c192ad), ("unnamed_rgb_plus_layers_uncompressed", "probe", 0x0a32e074a28c1f66), ("unnamed_rgb_plus_layers_uncompressed", "probed/linear", 0xa27668bf31d9426b), @@ -464,12 +467,12 @@ const PINNED: &[(&str, &str, u64)] = &[ ("unnamed_rgb_plus_layers_uncompressed", "ignore/linear", 0xb3276cc5126776d4), ("unnamed_rgb_plus_layers_uncompressed", "preserve_rgb", 0xdee1105fa6e6822a), ("unnamed_rgb_plus_layers_uncompressed", "aux", 0x854a5e84e7aaa5c2), - ("layered_uncompressed", "probe", 0x0a32e074a28c1f66), - ("layered_uncompressed", "probed/linear", 0xa84600283dce98f6), - ("layered_uncompressed", "straight/linear", 0xf028e1367a2fbb30), - ("layered_uncompressed", "premul/linear", 0xa84600283dce98f6), - ("layered_uncompressed", "ignore/linear", 0xa90a57f9a67f7468), - ("layered_uncompressed", "preserve_rgb", 0xc8e0050f5efe75b7), + ("layered_uncompressed", "probe", 0x6a38346c4c5662d5), + ("layered_uncompressed", "probed/linear", 0x63d9c6245f75ef06), + ("layered_uncompressed", "straight/linear", 0x63d9c6245f75ef06), + ("layered_uncompressed", "premul/linear", 0x63d9c6245f75ef06), + ("layered_uncompressed", "ignore/linear", 0x63d9c6245f75ef06), + ("layered_uncompressed", "preserve_rgb", 0x63d9c6245f75ef06), ("layered_uncompressed", "aux", 0xa6b9bd9f02c192ad), ("uint_rgb_zip16", "probe", 0x0a32e074a28c1f66), ("uint_rgb_zip16", "probed/linear", 0xed89310ef0cdb9fd), diff --git a/crates/project/src/layer.rs b/crates/project/src/layer.rs index b13c1d980..fd1f0c347 100644 --- a/crates/project/src/layer.rs +++ b/crates/project/src/layer.rs @@ -222,6 +222,102 @@ const READS_OTHER_FRAMES: &[&str] = &[ "ec.paint.paint", ]; +/// Does the effect group `g` read its own parameters at times its frame doesn't show, past the +/// comp's shutter (`EffectHost::params_at`, `param_at`)? Write-on lays a dab at every Brush +/// Spacing from the layer's start with the Brush Position of its time, Radio Waves keeps the +/// parameters each wave was born with for its lifespan, and Transform samples past the comp's +/// shutter with its own Shutter Angle (up to 720°) or on a stretched layer (`unit_stretch` +/// false: it samples in layer time). A key change of theirs then reaches frames far from the key. The time effects and simulations ([`reads_other_frames`]) +/// read them too, and reach every frame anyway. +// ponytail: hand-kept list of the effects that call `params_at`/`param_at` beyond the comp's +// shutter; a new one must be added here. +fn reads_own_params_elsewhen(g: &PropGroup, unit_stretch: bool) -> bool { + let GroupKind::Effect { effect } = &g.kind else { return false }; + match effect.as_str() { + "ec.generate.writeon" | "ec.generate.radiowaves" => true, + // (the comp's shutter at 100% stretch is within `Comp::shutter_margin`) + "ec.distort.transform" => !unit_stretch || !g.get("useCompositionShutterAngle").is_some_and(|p| p.keys.is_empty() && p.value.as_bool()), + _ => false, + } +} + +/// `a` and `b` have the same header: every field but the children. +fn same_head(a: &PropGroup, b: &PropGroup) -> bool { + // Every field (no `..`: a new field must be considered here). + let PropGroup { uid, match_id, name, kind, enabled, label, children: _ } = a; + *uid == b.uid && *match_id == b.match_id && *name == b.name && *kind == b.kind && *enabled == b.enabled && *label == b.label +} + +/// Groups nested deeper than this in a layer's property tree count as changed everywhere. +const MAX_PROP_DEPTH: usize = 64; + +/// Where a group sits in a layer's property tree, for its audio-only children ([`audio_only`]). +#[derive(Clone, Copy, PartialEq)] +enum Level { + Root, + /// The root's Effects group. + Effects, + Inner, +} + +/// The pairs of properties that differ between `a` and `b` (groups at `level` of two layers' +/// trees, `depth` deep), when all else is the same: the same headers, children and kinds, and +/// every difference a property whose value at a time reaches only the frames around that time. +/// `None` for any other difference: one in a header, a group added, removed or reordered, or a +/// property that is read at other times (inside an effect that reads its own parameters +/// elsewhen, [`reads_own_params_elsewhen`]; in the Essential Properties; in the audio something +/// draws). Audio-only nodes count only when `heard`, as in [`same_picture_props`]. `unit_stretch`: +/// the layer plays at 100%, so layer time and comp time advance alike. +fn changed_props<'a>( + a: &'a PropGroup, + b: &'a PropGroup, + level: Level, + heard: bool, + unit_stretch: bool, + depth: usize, + out: &mut Vec<(&'a Property, &'a Property)>, +) -> Option<()> { + if depth > MAX_PROP_DEPTH || !same_head(a, b) { + return None; + } + let audio = |n: &Node| match level { + Level::Root => audio_only(n, true), + Level::Effects => audio_only(n, false), + Level::Inner => false, + }; + let mut x = a.children.iter().filter(|n| heard || !audio(n)); + let mut y = b.children.iter().filter(|n| heard || !audio(n)); + loop { + let (m, n) = match (x.next(), y.next()) { + (None, None) => return Some(()), + (Some(m), Some(n)) => (m, n), + _ => return None, + }; + if m == n { + continue; + } + // Waveform and spectrum effects draw a stretch of the audio they hear; audio effects + // (delay, reverb) carry it on. + if audio(m) || audio(n) { + return None; + } + match (m, n) { + (Node::Group(g), Node::Group(h)) => { + // (the Essential Properties override the nested comp's controls, which reach its + // layers by paths this walk doesn't follow: time effects and motion blur there, + // mirrored masters; conservatively, their whole span) + if matches!(g.kind, GroupKind::Essential { .. }) || reads_own_params_elsewhen(g, unit_stretch) || reads_own_params_elsewhen(h, unit_stretch) { + return None; + } + let level = if level == Level::Root && g.match_id == "effects" { Level::Effects } else { Level::Inner }; + changed_props(g, h, level, heard, unit_stretch, depth.saturating_add(1), out)?; + } + (Node::Prop(p), Node::Prop(q)) => out.push((p, q)), + _ => return None, + } + } +} + impl Switches { /// These switches with Audio, Lock and Shy at their defaults. pub fn pixels(&self) -> Switches { @@ -246,11 +342,6 @@ fn audio_only(n: &Node, root: bool) -> bool { /// `a` and `b` are equal but for their audio-only nodes ([`audio_only`]: the root's Audio group, /// the effects in its Effects group that are audio effects). fn same_picture_props(a: &PropGroup, b: &PropGroup) -> bool { - fn head(a: &PropGroup, b: &PropGroup) -> bool { - // Every field (no `..`: a new field must be considered here). - let PropGroup { uid, match_id, name, kind, enabled, label, children: _ } = a; - *uid == b.uid && *match_id == b.match_id && *name == b.name && *kind == b.kind && *enabled == b.enabled && *label == b.label - } fn children(a: &PropGroup, b: &PropGroup, root: bool) -> bool { let mut x = a.children.iter().filter(|n| !audio_only(n, root)); let mut y = b.children.iter().filter(|n| !audio_only(n, root)); @@ -258,7 +349,7 @@ fn same_picture_props(a: &PropGroup, b: &PropGroup) -> bool { match (x.next(), y.next()) { (None, None) => return true, (Some(Node::Group(g)), Some(Node::Group(h))) if root && g.match_id == "effects" && h.match_id == "effects" => { - if !(head(g, h) && children(g, h, false)) { + if !(same_head(g, h) && children(g, h, false)) { return false; } } @@ -267,7 +358,7 @@ fn same_picture_props(a: &PropGroup, b: &PropGroup) -> bool { } } } - head(a, b) && children(a, b, true) + same_head(a, b) && children(a, b, true) } /// `g` (a layer's property tree) without its audio-only nodes ([`same_picture_props`]). @@ -343,16 +434,20 @@ impl Layer { } /// The comp-time spans where `self` draws differently than `o` when the two differ only in - /// the keyframes of Transform properties (a key's value, ease or interpolation moved in the - /// Timeline or Graph Editor): from two keys before the first changed key to two after the - /// last (auto-Bezier and continuous tangents reach the neighbouring segments), to the - /// layer's in or out point past the first or last key (values hold there). `None` for any - /// other difference, a static value, an expression on the layer (it can read the keyed - /// property at other times), roving or muted keys, a time remap or a time effect (it reads other - /// times): those reach the layer's whole span. + /// the keyframes of their properties (a key's value, ease or interpolation moved in the + /// Timeline or Graph Editor), anywhere in the property tree: Transform, effects, masks, shape + /// contents, text animators, layer styles… Per changed property, from two keys before the + /// first changed key to two after the last (auto-Bezier and continuous tangents reach the + /// neighbouring segments), to the layer's in or out point past the first or last key (values + /// hold there). A keyed value at a time comes from the keys around it, whatever its kind (a + /// path, a gradient, Source Text's hold keys, an orientation). `None` for any other + /// difference: the tree's structure (a group or effect added, removed or reordered, a + /// group's header), a static value, an expression on the layer (it can read the keyed + /// property at other times), roving or muted keys, a time remap or a time effect (it reads + /// other times), a property read at other times (an effect reading its own parameters + /// elsewhen, the Essential Properties, audio something draws, see [`changed_props`]; Position + /// under Auto-Orient Along Path; a model's animation clip): those reach the layer's whole span. pub fn keyframe_spans(&self, o: &Layer, with_markers: bool, heard: bool) -> Option> { - let transform = |l: &Layer| l.props.group("transform").cloned(); - let (t1, t0) = (transform(self)?, transform(o)?); let reads_time = |l: &Layer| { l.props.get("timeRemap").is_some() || l.props.group("effects").is_some_and(|e| { @@ -367,22 +462,35 @@ impl Layer { if reads_time(self) || reads_time(o) || has_expr(self) || has_expr(o) { return None; } - // Everything but the Transform group draws the same. - let rest = |l: &Layer| { + // Everything but the property tree's contents draws the same. + let shell = |l: &Layer| { let mut l = l.clone(); - l.props.children.retain(|n| !matches!(n, Node::Group(g) if g.match_id == "transform")); + l.props.children.clear(); l }; - let head = |g: &PropGroup| PropGroup { children: vec![], ..g.clone() }; - if !rest(self).same_pixels_with(&rest(o), with_markers, heard) || head(&t1) != head(&t0) || t1.children.len() != t0.children.len() { + if !shell(self).same_pixels_with(&shell(o), with_markers, heard) { return None; } + // Properties read at other times by the renderer: Position under Auto-Orient Along Path + // (where the layer holds still it keeps the direction of the last motion, any distance + // back) and a model's animation clip (it plays from the key that chose it). + fn at<'a>(l: &'a Layer, group: &str, m: &str) -> Option<&'a Property> { + l.props.sub(group).and_then(|g| g.get(m)) + } + let along = self.auto_orient == AutoOrient::AlongPath || o.auto_orient == AutoOrient::AlongPath; + if (along && ["position", "positionX", "positionY", "positionZ"].iter().any(|m| at(self, "transform", m) != at(o, "transform", m))) + || at(self, "geometryOptions", "animation") != at(o, "geometryOptions", "animation") + { + return None; + } + let unit_stretch = (self.effective_stretch() - 100.0).abs() < 1e-9; + let mut pairs = Vec::new(); + changed_props(&self.props, &o.props, Level::Root, heard, unit_stretch, 0, &mut pairs)?; + // (a reversed layer plays its first keys last) + let reversed = self.effective_stretch() < 0.0; + let (early, late) = if reversed { (self.out_point, self.in_point) } else { (self.in_point, self.out_point) }; let mut spans = Vec::new(); - for (n1, n0) in t1.children.iter().zip(&t0.children) { - if n1 == n0 { - continue; - } - let (Node::Prop(p1), Node::Prop(p0)) = (n1, n0) else { return None }; + for (p1, p0) in pairs { let bare = |p: &Property| Property { keys: vec![], value: Value::Scalar(0.0), ..p.clone() }; // (muted keys are skipped: the keys around an edit that play can be any distance away) if bare(p1) != bare(p0) || p1.keys.is_empty() || p0.keys.is_empty() || p1.keys.iter().chain(&p0.keys).any(|k| k.roving || k.muted) { @@ -405,7 +513,7 @@ impl Layer { let ahead = if upto >= keys.len() { None } else { keys.get(upto.saturating_add(1).min(keys.len().saturating_sub(1))) }; hi = hi.zip(ahead).map(|(a, k)| a.max(k.time)); } - let (x, y) = (lo.map_or(self.in_point, |t| self.comp_time(t)), hi.map_or(self.out_point, |t| self.comp_time(t))); + let (x, y) = (lo.map_or(early, |t| self.comp_time(t)), hi.map_or(late, |t| self.comp_time(t))); let (x, y) = (x.min(y).max(self.in_point), x.max(y).min(self.out_point)); if x <= y { spans.push((x, y)); diff --git a/crates/project/src/tests.rs b/crates/project/src/tests.rs index 80ba3c771..83bac7f7f 100644 --- a/crates/project/src/tests.rs +++ b/crates/project/src/tests.rs @@ -535,3 +535,275 @@ fn an_item_inside_a_non_folder_moves_to_the_top_level_when_a_project_is_opened() // Nothing to repair in a sound project. assert!(Project::from_json_repaired(&q.to_json()).expect("opens").1.is_empty()); } + +/// #3324: a layer of [`project_with_layer`] with `add` applied and three keys (at 1, 2 and 3 s) +/// with `values` on the property at `path`, and that layer with the middle key's value `mid`. +fn middle_key_edit(add: impl FnOnce(&mut Ids, &mut crate::Layer), path: &str, values: [Value; 3], mid: Value) -> (crate::Layer, crate::Layer) { + let (mut p, cid) = project_with_layer(); + let mut l = p.comp(cid).unwrap().layers[0].clone(); + add(&mut Ids(&mut p.next_id), &mut l); + l.props.prop_mut(path).unwrap_or_else(|| panic!("{path}")).keys = + values.into_iter().zip([1.0, 2.0, 3.0]).map(|(v, s)| Keyframe::new(Tick::from_seconds_f64(s), v)).collect(); + let mut edited = l.clone(); + edited.props.prop_mut(path).unwrap().keys[1].value = mid; + (l, edited) +} + +/// The span of a middle-key edit: from the first key to the last (1 to 3 s). +fn first_to_last_key() -> Option> { + Some(vec![(Tick::from_seconds_f64(1.0), Tick::from_seconds_f64(3.0))]) +} + +/// An effect instance as `effects::instantiate` builds it: `params` under its group, or under a +/// `master` group (Exposure's `master/exposure`). +fn effect(ids: &mut Ids, id: &str, params: Vec) -> crate::PropGroup { + let mut fx = ids.group(id, id); + fx.kind = crate::GroupKind::Effect { effect: id.into() }; + for p in params { + fx.children.push(p.into()); + } + fx +} + +fn exposure(ids: &mut Ids) -> crate::PropGroup { + let master = ids.group("master", "Master").with(ids.prop("exposure", "Exposure", Value::Scalar(0.0))); + let mut fx = effect(ids, "ec.color.exposure", vec![]); + fx.children.push(master.into()); + fx +} + +fn add_effect(l: &mut crate::Layer, fx: crate::PropGroup) { + l.props.sub_mut("effects").unwrap().children.push(fx.into()); +} + +fn scalars(v: [f64; 3]) -> [Value; 3] { + v.map(Value::Scalar) +} + +/// A key edit on an effect parameter (inside the effect's Master group) keeps the frames +/// outside its keys, as a Transform key edit does (#3324). +#[test] +fn an_effect_key_edit_reaches_only_its_keys() { + let (a, b) = middle_key_edit(|ids, l| add_effect(l, exposure(ids)), "effects/#1/master/exposure", scalars([0.0, 1.0, 0.0]), Value::Scalar(2.0)); + assert_eq!(b.keyframe_spans(&a, true, false), first_to_last_key()); + assert_eq!(a.keyframe_spans(&b, true, false), first_to_last_key()); +} + +/// A key edit on a mask's path (a shape value) keeps the frames outside its keys (#3324). +#[test] +fn a_mask_path_key_edit_reaches_only_its_keys() { + let path = |w: f64| Value::Path(ShapePath::rect([0.0, 0.0], w, 10.0)); + let (a, b) = middle_key_edit( + |ids, l| { + let m = build::mask(ids, "Mask 1", ShapePath::rect([0.0, 0.0], 10.0, 10.0), MaskMode::Add, [255, 0, 0]); + l.props.sub_mut("masks").unwrap().children.push(m.into()); + }, + "masks/mask#1/path", + [path(10.0), path(20.0), path(10.0)], + path(40.0), + ); + assert_eq!(b.keyframe_spans(&a, true, false), first_to_last_key()); +} + +/// A key edit on a shape's path inside a shape group keeps the frames outside its keys (#3324). +#[test] +fn a_shape_path_key_edit_reaches_only_its_keys() { + let path = |w: f64| Value::Path(ShapePath::ellipse([0.0, 0.0], w, 10.0)); + let (a, b) = middle_key_edit( + |ids, l| { + let shape = build::shape_path(ids, ShapePath::ellipse([0.0, 0.0], 10.0, 10.0)); + let fill = build::shape_fill(ids, [1.0, 0.0, 0.0, 1.0]); + let group = build::shape_group(ids, "Group 1", vec![shape, fill]); + l.props.children.push(build::contents(ids).with(group).into()); + }, + "contents/group#1/contents/path#1/path", + [path(10.0), path(20.0), path(10.0)], + path(40.0), + ); + assert_eq!(b.keyframe_spans(&a, true, false), first_to_last_key()); +} + +/// A key edit on a text animator's property keeps the frames outside its keys, and so does one +/// on Source Text (hold keys) (#3324). +#[test] +fn text_key_edits_reach_only_their_keys() { + let text = |ids: &mut Ids, l: &mut crate::Layer| { + let mut t = build::text(ids, effectcraft_keyframe::TextDoc::plain("Hello")); + let opacity = build::text_anim_prop(ids, "opacity").unwrap(); + let animator = build::text_animator(ids, "Animator 1", vec![opacity]); + t.sub_mut("animators").unwrap().children.push(animator.into()); + l.props.children.push(t.into()); + }; + let (a, b) = middle_key_edit(text, "text/animators/animator#1/properties/opacity", scalars([100.0, 0.0, 100.0]), Value::Scalar(50.0)); + assert_eq!(b.keyframe_spans(&a, true, false), first_to_last_key()); + let doc = |s: &str| Value::Text(Box::new(effectcraft_keyframe::TextDoc::plain(s))); + let (a, b) = middle_key_edit(text, "text/sourceText", [doc("a"), doc("b"), doc("c")], doc("B")); + assert_eq!(b.keyframe_spans(&a, true, false), first_to_last_key()); +} + +/// An expression anywhere on the layer can read the keyed property at other times: an effect key +/// edit then reaches the layer's whole span (#3324). +#[test] +fn an_expression_elsewhere_on_the_layer_keeps_the_whole_span() { + let (a, b) = middle_key_edit( + |ids, l| { + add_effect(l, exposure(ids)); + l.props.prop_mut("transform/rotation").unwrap().expr = Some(crate::Expression { text: "time * 10".into(), enabled: true }); + }, + "effects/#1/master/exposure", + scalars([0.0, 1.0, 0.0]), + Value::Scalar(2.0), + ); + assert_eq!(b.keyframe_spans(&a, true, false), None); +} + +/// A change of the tree's structure reaches the layer's whole span: an effect added (even beside +/// a key edit), and a group header (an effect switched off) (#3324). +#[test] +fn an_effect_added_or_switched_off_keeps_the_whole_span() { + let (a, b) = middle_key_edit(|ids, l| add_effect(l, exposure(ids)), "effects/#1/master/exposure", scalars([0.0, 1.0, 0.0]), Value::Scalar(2.0)); + let mut added = a.clone(); + add_effect(&mut added, effect(&mut Ids(&mut 10_000), "ec.channel.invert", vec![])); + assert_eq!(added.keyframe_spans(&a, true, false), None); + let mut both = b.clone(); + add_effect(&mut both, effect(&mut Ids(&mut 10_000), "ec.channel.invert", vec![])); + assert_eq!(both.keyframe_spans(&a, true, false), None); + let mut off = b.clone(); + off.props.group_mut("effects/#1").unwrap().enabled = false; + assert_eq!(off.keyframe_spans(&a, true, false), None); +} + +/// Effects that read their own parameters at other times (Write-on's dabs since the layer's +/// start, Radio Waves' birth values, Transform's own shutter) reach the layer's whole span with a +/// key edit of theirs, not with one of another effect on the layer (#3324). +#[test] +fn effects_reading_their_parameters_elsewhen_keep_the_whole_span() { + let v2 = |x: f64| Value::Vec2([x, 0.0]); + let write_on = |ids: &mut Ids| { + let p = ids.prop("brushPosition", "Brush Position", v2(0.0)); + effect(ids, "ec.generate.writeon", vec![p]) + }; + let (a, b) = middle_key_edit(|ids, l| add_effect(l, write_on(ids)), "effects/#1/brushPosition", [v2(0.0), v2(5.0), v2(0.0)], v2(9.0)); + assert_eq!(b.keyframe_spans(&a, true, false), None); + let radio = |ids: &mut Ids| { + let p = ids.prop("producePoint", "Producer Point", v2(0.0)); + effect(ids, "ec.generate.radiowaves", vec![p]) + }; + let (a, b) = middle_key_edit(|ids, l| add_effect(l, radio(ids)), "effects/#1/producePoint", [v2(0.0), v2(5.0), v2(0.0)], v2(9.0)); + assert_eq!(b.keyframe_spans(&a, true, false), None); + // Transform: its own Shutter Angle reaches past the comp's shutter, the comp's doesn't unless + // the layer is stretched (Transform samples its shutter in layer time). + for (comp_shutter, stretch, want) in [(false, 100.0, None), (true, 100.0, first_to_last_key()), (true, 200.0, None)] { + let transform = |ids: &mut Ids, l: &mut crate::Layer| { + let shutter = ids.prop("useCompositionShutterAngle", "Use Composition's Shutter Angle", Value::Bool(comp_shutter)); + let rotation = ids.prop("rotation", "Rotation", Value::Scalar(0.0)); + add_effect(l, effect(ids, "ec.distort.transform", vec![shutter, rotation])); + l.stretch = stretch; + }; + let (a, b) = middle_key_edit(transform, "effects/#1/rotation", scalars([0.0, 10.0, 0.0]), Value::Scalar(20.0)); + let want = want.map(|_| vec![(a.comp_time(Tick::from_seconds_f64(1.0)), a.comp_time(Tick::from_seconds_f64(3.0)))]); + assert_eq!(b.keyframe_spans(&a, true, false), want, "comp shutter {comp_shutter}, stretch {stretch}"); + } + // Another effect's key edit beside a Write-on. + let (a, b) = middle_key_edit( + |ids, l| { + add_effect(l, write_on(ids)); + add_effect(l, exposure(ids)); + }, + "effects/#2/master/exposure", + scalars([0.0, 1.0, 0.0]), + Value::Scalar(2.0), + ); + assert_eq!(b.keyframe_spans(&a, true, false), first_to_last_key()); +} + +/// The Essential Properties feed a nested comp, and audio something draws (a waveform reads a +/// stretch of it): a key edit there reaches the layer's whole span. Audio nothing draws doesn't +/// count at all (#3324). +#[test] +fn essential_properties_and_heard_audio_keep_the_whole_span() { + let (a, b) = middle_key_edit( + |ids, l| { + let mut g = ids.group("essentialProperties", "Essential Properties").with(ids.prop("control1", "Size", Value::Scalar(0.0))); + g.kind = crate::GroupKind::Essential { overridden: vec![] }; + l.props.children.push(g.into()); + }, + "essentialProperties/control1", + scalars([0.0, 1.0, 0.0]), + Value::Scalar(2.0), + ); + assert_eq!(b.keyframe_spans(&a, true, false), None); + let (a, b) = middle_key_edit( + |ids, l| l.props.children.push(build::audio(ids).into()), + "audio/levels", + [Value::Vec2([0.0; 2]), Value::Vec2([-6.0; 2]), Value::Vec2([0.0; 2])], + Value::Vec2([-12.0; 2]), + ); + assert_eq!(b.keyframe_spans(&a, true, true), None, "heard"); + assert_eq!(b.keyframe_spans(&a, true, false), Some(vec![]), "not heard: the picture is the same"); +} + +/// A property tree nested deeper than the walk goes counts as changed everywhere (#3324). +#[test] +fn a_deeply_nested_key_edit_keeps_the_whole_span() { + // 100 groups around a property keyed at 1, 2 and 3 s with `mid` in the middle (the same uids + // each time). + let deep = |mid: f64| { + let mut n = 50_000; + let ids = &mut Ids(&mut n); + let mut x = ids.prop("x", "X", Value::Scalar(0.0)); + x.keys = [0.0, mid, 0.0].into_iter().zip([1.0, 2.0, 3.0]).map(|(v, s)| Keyframe::new(Tick::from_seconds_f64(s), Value::Scalar(v))).collect(); + let mut g = ids.group("g", "G").with(x); + for _ in 0..100 { + g = ids.group("g", "G").with(g); + } + g + }; + let (p, cid) = project_with_layer(); + let (mut a, mut b) = (p.comp(cid).unwrap().layers[0].clone(), p.comp(cid).unwrap().layers[0].clone()); + a.props.children.push(deep(1.0).into()); + b.props.children.push(deep(2.0).into()); + assert_eq!(b.keyframe_spans(&a, true, false), None); + // (a Transform key edit beside the same deep tree keeps its span) + let (a, b) = middle_key_edit(|_, l| l.props.children.push(deep(1.0).into()), "transform/opacity", scalars([100.0, 0.0, 100.0]), Value::Scalar(50.0)); + assert_eq!(b.keyframe_spans(&a, true, false), first_to_last_key()); +} + +/// On a reversed layer (negative stretch) the first keys play last: an edit of the first key +/// reaches from the next keys' time to the out point, not from the in point (#3324). +#[test] +fn a_first_key_edit_on_a_reversed_layer_reaches_the_out_point() { + // (a layer from 0 to 10 s reversed: start 10 s, so layer time t shows at 10 - t) + let reversed = |_: &mut Ids, l: &mut crate::Layer| (l.stretch, l.start_time) = (-100.0, Tick::from_seconds_f64(10.0)); + let (a, _) = middle_key_edit(reversed, "transform/opacity", scalars([100.0, 0.0, 100.0]), Value::Scalar(0.0)); + let mut b = a.clone(); + b.props.prop_mut("transform/opacity").unwrap().keys[0].value = Value::Scalar(50.0); + let spans = b.keyframe_spans(&a, true, false).unwrap(); + let (s, e) = spans[0]; + assert_eq!(spans.len(), 1); + // Keys at layer 1, 2, 3 s show at 9, 8, 7 s; the first key's edit reaches 7 s (its second key + // after) through the out point. + assert_eq!((s, e), (Tick::from_seconds_f64(7.0), a.out_point), "{spans:?}"); +} + +/// The renderer reads some properties at other times: Position under Auto-Orient Along Path (a +/// still layer keeps its last direction of travel) and a model's animation clip (it plays from the +/// key that chose it). Their key edits reach the layer's whole span (#3324). +#[test] +fn properties_the_renderer_reads_elsewhen_keep_the_whole_span() { + let v3 = |x: f64| Value::Vec3([x, 0.0, 0.0]); + let (a, b) = middle_key_edit(|_, l| l.auto_orient = crate::AutoOrient::AlongPath, "transform/position", [v3(0.0), v3(5.0), v3(9.0)], v3(2.0)); + assert_eq!(b.keyframe_spans(&a, true, false), None); + let (a, b) = middle_key_edit(|_, _| {}, "transform/position", [v3(0.0), v3(5.0), v3(9.0)], v3(2.0)); + assert_eq!(b.keyframe_spans(&a, true, false), first_to_last_key(), "without Auto-Orient"); + let (a, b) = middle_key_edit( + |ids, l| { + let g = ids.group("geometryOptions", "Geometry Options").with(ids.prop("animation", "Animation", Value::Enum(0))); + l.props.children.push(g.into()); + }, + "geometryOptions/animation", + [Value::Enum(0), Value::Enum(1), Value::Enum(1)], + Value::Enum(0), + ); + assert_eq!(b.keyframe_spans(&a, true, false), None); +} diff --git a/crates/psd/src/descriptor.rs b/crates/psd/src/descriptor.rs index 37e7cb94b..63efce100 100644 --- a/crates/psd/src/descriptor.rs +++ b/crates/psd/src/descriptor.rs @@ -127,7 +127,7 @@ pub fn read_descriptor(r: &mut Reader) -> Result { Ok(from_craft_descriptor(d)) } -fn desc_err(e: craft_psd::PsdError) -> Error { +pub(crate) fn desc_err(e: craft_psd::PsdError) -> Error { match e { craft_psd::PsdError::UnexpectedEof { .. } => Error::Truncated, craft_psd::PsdError::Unsupported(s) => Error::Unsupported(s), @@ -143,7 +143,7 @@ fn unit_str(u: &[u8; 4]) -> String { String::from_utf8_lossy(u).into_owned() } -fn from_craft_descriptor(d: craft_psd::descriptor::Descriptor) -> Descriptor { +pub(crate) fn from_craft_descriptor(d: craft_psd::descriptor::Descriptor) -> Descriptor { Descriptor { class_name: d.name.to_string_lossy(), class_id: id_str(&d.class_id), diff --git a/crates/psd/src/parse.rs b/crates/psd/src/parse.rs index 3ba26e9fc..2f1ccd2b3 100644 --- a/crates/psd/src/parse.rs +++ b/crates/psd/src/parse.rs @@ -1,6 +1,6 @@ use super::limits::{Error, Result}; use super::model::{Adjustment, ChannelInfo, ColorMode, Layer, LayerMask, LinkedFile, MAX_GROUP_DEPTH, Node, Rect, Section, SubPath, TextInfo, VectorMask}; -use super::{Psd, Reader, descriptor, engine_data, placed}; +use super::{Psd, descriptor, engine_data, placed}; use std::sync::Arc; /// Whether `bytes` start like a Photoshop document. @@ -114,7 +114,7 @@ impl Psd { // A malformed optional block only loses that block's information. // Unsupported modern placement geometry must not silently become an // unwarped layer or fall back to a less expressive PlLd in either order. - match self.layer_block(&mut l, &b.key, &b.data) { + match self.layer_block(&mut l, b) { Err(e @ Error::Unsupported(_)) if matches!(&b.key, b"SoLd" | b"SoLE") => return Err(e), _ => {} } @@ -140,8 +140,9 @@ impl Psd { } } - fn layer_block(&self, l: &mut Layer, key: &[u8; 4], b: &[u8]) -> Result<()> { - let mut r = Reader::new(b); + fn layer_block(&self, l: &mut Layer, block: &craft_psd::tagged::TaggedBlock) -> Result<()> { + let key = &block.key; + let b = block.data.as_slice(); match key { b"luni" => { // Shared framing rejects truncated counts/payloads before allocation. Only @@ -155,32 +156,37 @@ impl Psd { l.name = name; } } - b"lyid" => l.id = Some(r.u32()?), - b"iOpa" => l.fill_opacity = r.u8()?, + b"lyid" | b"iOpa" => { + use craft_psd::tagged::BlockData; + // Borrow the original block; short fields keep the previous value, + // while complete prefixes retain the shared parser's trailing-byte policy. + match block.parsed().transpose().map_err(|e| error(&e))? { + Some(BlockData::LayerId(id)) => l.id = Some(id), + Some(BlockData::FillOpacity(opacity)) => l.fill_opacity = opacity, + _ => {} + } + } b"lsct" | b"lsdk" => { - l.section = match r.u32()? { - 1 => Section::OpenFolder, - 2 => Section::ClosedFolder, - 3 => Section::Divider, + use craft_psd::tagged::{SectionDivider, SectionType}; + let divider = SectionDivider::from_bytes_recovering_blend(b).map_err(|e| error(&e))?; + l.section = match divider.kind { + SectionType::OpenFolder => Section::OpenFolder, + SectionType::ClosedFolder => Section::ClosedFolder, + SectionType::BoundingDivider => Section::Divider, _ => Section::Layer, }; - if b.len() >= 12 && &b[4..8] == b"8BIM" { - l.blend.copy_from_slice(&b[8..12]); + if let Some(blend) = divider.blend_mode { + l.blend = blend.key(); } } b"TySh" => { - let _ver = r.u16()?; - let mut t = [0.0; 6]; - for v in &mut t { - *v = r.f64()?; - } + let prefix = craft_psd::text::TypeLayerPrefix::from_bytes_with_limits(b, descriptor::PARSE_LIMITS).map_err(descriptor::desc_err)?; + let mut t = prefix.transform; // A transform with NaN/inf is unusable: fall back to the identity. if t.iter().any(|v| !v.is_finite()) { t = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; } - let _text_ver = r.u16()?; - let _desc_ver = r.u32()?; - let d = descriptor::read_descriptor(&mut r)?; + let d = descriptor::from_craft_descriptor(prefix.descriptor); let text = d.text("Txt ").unwrap_or_default().replace("\r\n", "\n").replace('\r', "\n"); let text = text.strip_suffix('\n').map(str::to_string).unwrap_or(text); let style = d.raw("EngineData").map(|e| engine_data::text_style(&engine_data::parse_lossy(e))).unwrap_or_default(); @@ -188,15 +194,21 @@ impl Psd { d.obj("bounds").or_else(|| d.obj("boundingBox")).and_then(|o| Some([o.num("Left")?, o.num("Top ")?, o.num("Rght")?, o.num("Btom")?])); l.text = Some(TextInfo { text, transform: t, style, bounds }); } - b"lfx2" => { - let _ver = r.u32()?; - let _dver = r.u32()?; - l.effects = Some(descriptor::read_descriptor(&mut r)?); - } - b"SoCo" => { - let _ver = r.u32()?; - let d = descriptor::read_descriptor(&mut r)?; - l.fill = d.color("Clr "); + b"lfx2" | b"SoCo" | b"CgEd" => { + if let Some(parsed) = block.descriptor_prefix_recovering_versions_with_limits(descriptor::PARSE_LIMITS) { + let d = descriptor::from_craft_descriptor(parsed.map_err(descriptor::desc_err)?); + match key { + b"lfx2" => l.effects = Some(d), + b"SoCo" => l.fill = d.color("Clr "), + _ => { + l.adjustment = Some(Adjustment::BrightnessContrast { + brightness: d.num("Brgh").unwrap_or(0.0), + contrast: d.num("Cntr").unwrap_or(0.0), + legacy: d.bool("useLegacy").unwrap_or(false), + }); + } + } + } } b"nvrt" => l.adjustment = Some(Adjustment::Invert), b"brit" | b"hue2" | b"hue " | b"levl" | b"expA" => { @@ -209,15 +221,6 @@ impl Psd { } } } - b"CgEd" => { - let _ver = r.u32()?; - let d = descriptor::read_descriptor(&mut r)?; - l.adjustment = Some(Adjustment::BrightnessContrast { - brightness: d.num("Brgh").unwrap_or(0.0), - contrast: d.num("Cntr").unwrap_or(0.0), - legacy: d.bool("useLegacy").unwrap_or(false), - }); - } b"curv" | b"blnc" | b"post" | b"thrs" | b"selc" | b"mixr" | b"phfl" | b"vibA" | b"blwh" | b"grdm" | b"clrL" if l.adjustment.is_none() => { l.adjustment = Some(Adjustment::Other(String::from_utf8_lossy(key).into_owned())); } @@ -230,45 +233,37 @@ impl Psd { l.smart_object = Some(placed::from_craft_smart(craft_psd::smart::SmartObject::from_placed_layer(b).map_err(|e| error(&e))?)); } b"vmsk" | b"vsms" => { - let _ver = r.u32()?; - let flags = r.u32()?; - l.vector_mask = Some(self.vector_paths(&mut r, flags)?); + let block = craft_psd::path::VectorMaskBlock::from_bytes(b).map_err(|e| error(&e))?; + l.vector_mask = Some(self.vector_paths(&block)); } _ => {} } Ok(()) } - fn vector_paths(&self, r: &mut Reader, flags: u32) -> Result { + fn vector_paths(&self, block: &craft_psd::path::VectorMaskBlock) -> VectorMask { + use craft_psd::path::{VectorMaskBlock, selector}; let (w, h) = (self.width as f64, self.height as f64); - let mut vm = VectorMask { inverted: flags & 1 != 0, disabled: flags & 4 != 0, subpaths: vec![] }; - let fixed = |r: &mut Reader| -> Result { Ok(r.i32()? as f64 / (1 << 24) as f64) }; - while r.remaining() >= 26 { - let sel = r.u16()?; - match sel { - 0 | 3 => { - let _n = r.u16()?; - r.skip(22)?; - vm.subpaths.push(SubPath { closed: sel == 0, knots: vec![] }); - } - 1 | 2 | 4 | 5 => { - let mut pts = [[0.0; 2]; 3]; - for p in &mut pts { - let y = fixed(r)?; - let x = fixed(r)?; - *p = [x * w, y * h]; - } - if let Some(sp) = vm.subpaths.last_mut() { - sp.knots.push(pts); - } - } - _ => r.skip(24)?, + let mut vm = VectorMask { + inverted: block.flags & VectorMaskBlock::FLAG_INVERT != 0, + disabled: block.flags & VectorMaskBlock::FLAG_DISABLED != 0, + subpaths: vec![], + }; + // Keep Effect's recovery policy: ignore declared counts and orphan knots, and + // keep mixed open/closed knot selectors in the last declared subpath. + // PathData::subpaths deliberately has a different, more permissive policy. + for record in &block.path.records { + if record.is_length() { + vm.subpaths.push(SubPath { closed: record.selector == selector::CLOSED_LENGTH, knots: vec![] }); + } else if let Some(knot) = record.knot() + && let Some(sp) = vm.subpaths.last_mut() + { + sp.knots.push([knot.pre, knot.anchor, knot.post].map(|(x, y)| [x * w, y * h])); } } vm.subpaths.retain(|s| !s.knots.is_empty()); - Ok(vm) + vm } - /// The layer tree, top of the stack first. Groups nest at most [`MAX_GROUP_DEPTH`] deep (see /// [`Psd::tree_report`]). pub fn tree(&self) -> Vec { diff --git a/crates/psd/src/tests.rs b/crates/psd/src/tests.rs index 2935841dd..227dda1b9 100644 --- a/crates/psd/src/tests.rs +++ b/crates/psd/src/tests.rs @@ -3,10 +3,16 @@ use super::*; use crate::pixels::srgb_encode; mod fixed_adjustments; +mod fixed_writers; mod integration; mod opt; +mod scalar_blocks; +mod section_divider; mod shared_corpus; +mod tagged_descriptors; +mod tysh_prefix; mod unicode_name; +mod vector_records; fn gradient(w: u32, h: u32) -> Vec<[f32; 4]> { (0..w * h).map(|i| [(i % w) as f32 / (w - 1).max(1) as f32, (i / w) as f32 / (h - 1).max(1) as f32, 0.25, 1.0]).collect() diff --git a/crates/psd/src/tests/fixed_writers.rs b/crates/psd/src/tests/fixed_writers.rs new file mode 100644 index 000000000..4aac3c9c2 --- /dev/null +++ b/crates/psd/src/tests/fixed_writers.rs @@ -0,0 +1,70 @@ +use super::*; + +#[test] +fn fixed_adjustment_writers_keep_exact_bytes_through_full_psd() { + let cases = [ + (brightness_block(i16::MIN, i16::MAX), *b"brit", vec![0x80, 0, 0x7f, 0xff, 0, 0x7f, 0]), + (brightness_block(-1, 0), *b"brit", vec![0xff, 0xff, 0, 0, 0, 0x7f, 0]), + (exposure_block(0.0, -0.0, f32::INFINITY), *b"expA", vec![0, 1, 0, 0, 0, 0, 0x80, 0, 0, 0, 0x7f, 0x80, 0, 0]), + ( + exposure_block(f32::NEG_INFINITY, f32::from_bits(0x7fc1_2345), f32::from_bits(0xffc5_4321)), + *b"expA", + vec![0, 1, 0xff, 0x80, 0, 0, 0x7f, 0xc1, 0x23, 0x45, 0xff, 0xc5, 0x43, 0x21], + ), + (exposure_block(1.0, -2.5, 0.125), *b"expA", vec![0, 1, 0x3f, 0x80, 0, 0, 0xc0, 0x20, 0, 0, 0x3e, 0, 0, 0]), + ]; + for (block, key, expected) in cases { + assert_eq!(block.0, key); + assert_eq!(block.1, expected); + let mut doc = WDoc::new(1, 1); + doc.layers = vec![WLayer::empty("raw adjustment", vec![block])]; + let bytes = write(&doc); + let file = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let emitted = file.layer_info.as_ref().unwrap().layers[0].block(&key).unwrap(); + assert_eq!(emitted.data, expected); + } +} + +fn assert_written_payload(block: ([u8; 4], Vec), key: [u8; 4], expected: Vec) { + assert_eq!(block.0, key); + assert_eq!(block.1, expected); + let mut doc = WDoc::new(1, 1); + doc.layers = vec![WLayer::empty("raw adjustment", vec![block])]; + let bytes = write(&doc); + let file = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); + assert_eq!(file.layer_info.as_ref().unwrap().layers[0].block(&key).unwrap().data, expected); +} + +#[test] +fn hue_writer_keeps_all_six_unused_ranges_and_signed_master_values() { + let mut expected = vec![0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0x80, 0, 0x7f, 0xff, 0xff, 0xff]; + expected.extend([0; 144]); + assert_written_payload(hue_sat_block(i16::MIN, i16::MAX, -1), *b"hue2", expected); + let mut expected = vec![0; 160]; + expected[1] = 2; + assert_written_payload(hue_sat_block(0, 0, 0), *b"hue2", expected); +} + +#[test] +fn levels_writer_preserves_gamma_conversion_and_all_default_records() { + // Expected bytes are constants, not another execution of the conversion. + for (gamma, gamma_bytes) in [ + (0.125, [0, 13]), + (-0.125, [255, 243]), + (0.0, [0, 0]), + (-0.0, [0, 0]), + (f64::NAN, [0, 0]), + (f64::INFINITY, [127, 255]), + (f64::NEG_INFINITY, [128, 0]), + (f64::MAX, [127, 255]), + (-f64::MAX, [128, 0]), + (400.0, [127, 255]), + (-400.0, [128, 0]), + (1.0, [0, 100]), + ] { + let mut expected = vec![0, 2, 0x80, 0, 0x7f, 0xff, 0xff, 0xff, 0, 0]; + expected.extend(gamma_bytes); + expected.extend([0, 0, 0, 255, 0, 0, 0, 255, 0, 100].repeat(28)); + assert_written_payload(levels_block(i16::MIN, i16::MAX, -1, 0, gamma), *b"levl", expected); + } +} diff --git a/crates/psd/src/tests/scalar_blocks.rs b/crates/psd/src/tests/scalar_blocks.rs new file mode 100644 index 000000000..d8dff9a1a --- /dev/null +++ b/crates/psd/src/tests/scalar_blocks.rs @@ -0,0 +1,40 @@ +use super::*; + +fn scalars(blocks: Vec<([u8; 4], Vec)>) -> (Option, u8, u8) { + let mut doc = WDoc::new(1, 1); + doc.layers = vec![WLayer::empty("Scalars", blocks).with_opacity(37)]; + let layer = Psd::parse(write(&doc)).unwrap().layers.remove(0); + (layer.id, layer.fill_opacity, layer.opacity) +} + +#[test] +fn scalar_prefixes_keep_defaults_and_ignore_trailing_bytes() { + assert_eq!(scalars(vec![]), (None, 255, 37)); + let bytes = [0x89, 0xab, 0xcd, 0xef, 255, 0, 23]; + for end in 0..=bytes.len() { + assert_eq!(scalars(vec![(*b"lyid", bytes[..end].to_vec())]), (if end < 4 { None } else { Some(0x89ab_cdef) }, 255, 37), "lyid prefix {end}"); + assert_eq!(scalars(vec![(*b"iOpa", bytes[..end].to_vec())]), (None, if end == 0 { 255 } else { 0x89 }, 37), "iOpa prefix {end}"); + } + for id in [0u32, 1, 0x8000_0000, u32::MAX] { + for opacity in [0, 1, 254, 255] { + assert_eq!(scalars(vec![(*b"lyid", id.to_be_bytes().to_vec()), (*b"iOpa", vec![opacity])]), (Some(id), opacity, 37)); + } + } +} + +#[test] +fn repeated_scalar_blocks_preserve_prior_values_on_short_fields_in_both_orders() { + for reverse in [false, true] { + for short in 0..4 { + let mut initial = vec![(*b"lyid", vec![0, 0, 0, 42]), (*b"iOpa", vec![99])]; + if reverse { + initial.reverse(); + } + let mut blocks = initial.clone(); + blocks.extend([(*b"lyid", vec![255; short]), (*b"iOpa", vec![]), (*b"zzzz", vec![0; 4])]); + assert_eq!(scalars(blocks.clone()), (Some(42), 99, 37)); + blocks.extend([(*b"iOpa", vec![0, 77]), (*b"lyid", vec![0, 0, 0, 7, 255])]); + assert_eq!(scalars(blocks), (Some(7), 0, 37)); + } + } +} diff --git a/crates/psd/src/tests/section_divider.rs b/crates/psd/src/tests/section_divider.rs new file mode 100644 index 000000000..ec208383b --- /dev/null +++ b/crates/psd/src/tests/section_divider.rs @@ -0,0 +1,53 @@ +use super::*; + +fn parse_section_blocks(blocks: Vec<([u8; 4], Vec)>) -> (Section, [u8; 4]) { + let mut doc = WDoc::new(1, 1); + doc.layers = vec![WLayer::empty("Section", blocks).with_blend(b"mul ")]; + let layer = Psd::parse(write(&doc)).unwrap().layers.remove(0); + (layer.section, layer.blend) +} + +#[test] +fn section_prefixes_and_invalid_optional_signatures_preserve_prior_state() { + let full = [0, 0, 0, 2, b'8', b'B', b'I', b'M', b'z', b'z', b'z', b'z', 0, 0, 0, 7, 255]; + for key in [*b"lsct", *b"lsdk"] { + for len in 0..=17 { + let data = full[..len].to_vec(); + assert_eq!( + parse_section_blocks(vec![(key, data.clone())]), + (if len < 4 { Section::Layer } else { Section::ClosedFolder }, if len < 12 { *b"mul " } else { *b"zzzz" }), + "{key:?} length {len}" + ); + let previous = vec![0, 0, 0, 1, b'8', b'B', b'I', b'M', b's', b'c', b'r', b'n']; + let other = if key == *b"lsct" { *b"lsdk" } else { *b"lsct" }; + assert_eq!( + parse_section_blocks(vec![(other, previous), (key, data.clone())]), + (if len < 4 { Section::OpenFolder } else { Section::ClosedFolder }, if len < 12 { *b"scrn" } else { *b"zzzz" }), + ); + if len >= 12 { + let mut bad = data; + bad[4..8].copy_from_slice(b"nope"); + assert_eq!(parse_section_blocks(vec![(key, bad)]), (Section::ClosedFolder, *b"mul ")); + } + } + } +} + +#[test] +fn section_unknown_kinds_and_sequential_keys_keep_blend_until_replaced() { + for kind in [0u32, 1, 2, 3, 99, u32::MAX] { + let expected = match kind { + 1 => Section::OpenFolder, + 2 => Section::ClosedFolder, + 3 => Section::Divider, + _ => Section::Layer, + }; + for keys in [[*b"lsct", *b"lsdk"], [*b"lsdk", *b"lsct"]] { + let previous = vec![0, 0, 0, 1, b'8', b'B', b'I', b'M', b'z', b'z', b'z', b'z']; + let mut bad = kind.to_be_bytes().to_vec(); + bad.extend_from_slice(b"nopepass"); + bad.extend_from_slice(&7u32.to_be_bytes()); + assert_eq!(parse_section_blocks(vec![(keys[0], previous), (keys[1], bad)]), (expected, *b"zzzz")); + } + } +} diff --git a/crates/psd/src/tests/tagged_descriptors.rs b/crates/psd/src/tests/tagged_descriptors.rs new file mode 100644 index 000000000..28e0e3fc6 --- /dev/null +++ b/crates/psd/src/tests/tagged_descriptors.rs @@ -0,0 +1,92 @@ +use super::*; +use craft_psd::descriptor::{Descriptor as Shared, UnicodeString, Value}; + +fn bytes(key: [u8; 4], d: Shared, version: u32) -> Vec { + let mut b = version.to_be_bytes().repeat(if key == *b"lfx2" { 2 } else { 1 }); + b.extend(d.to_bytes()); + b +} + +fn state(blocks: Vec<([u8; 4], Vec)>) -> (Option, Option<[f64; 3]>, Option) { + let mut doc = WDoc::new(1, 1); + doc.layers = vec![WLayer::empty("Descriptor", blocks)]; + let layer = Psd::parse(write(&doc)).unwrap().layers.remove(0); + (layer.effects, layer.fill, layer.adjustment) +} + +fn value(key: [u8; 4]) -> Shared { + match &key { + b"lfx2" => Shared::new("null").with("name", Value::Text(UnicodeString::new("effect"))), + b"SoCo" => Shared::new("null").with( + "Clr ", + Value::Descriptor(Shared::new("RGBC").with("Rd ", Value::Double(255.0)).with("Grn ", Value::Double(127.5)).with("Bl ", Value::Double(0.0))), + ), + _ => Shared::new("null").with("Brgh", Value::Double(12.0)).with("Cntr", Value::Double(-4.0)).with("useLegacy", Value::Boolean(true)), + } +} + +#[test] +fn tagged_descriptor_headers_ignore_versions_and_tails_and_preserve_short_block_state() { + for key in [*b"lfx2", *b"SoCo", *b"CgEd"] { + let good = bytes(key, value(key), 16); + let expected = state(vec![(key, good.clone())]); + match &key { + b"lfx2" => assert_eq!(expected.0.as_ref().unwrap().text("name"), Some("effect")), + b"SoCo" => assert_eq!(expected.1, Some([1.0, 0.5, 0.0])), + _ => assert_eq!(expected.2, Some(Adjustment::BrightnessContrast { brightness: 12.0, contrast: -4.0, legacy: true })), + } + for cut in 0..good.len() { + assert_eq!(state(vec![(key, good[..cut].to_vec())]), (None, None, None), "{key:?} cut {cut}"); + assert_eq!(state(vec![(key, good.clone()), (key, good[..cut].to_vec())]), expected); + } + for version in [0, 99, u32::MAX] { + for tail in [vec![], vec![255], vec![1, 2, 3, 4, 5]] { + let mut b = bytes(key, value(key), version); + b.extend(tail); + assert_eq!(state(vec![(key, b)]), expected); + } + } + let empty = bytes(key, Shared::new("null"), 0); + let replaced = state(vec![(key, good), (key, empty)]); + match &key { + b"lfx2" => assert!(replaced.0.unwrap().items.is_empty()), + b"SoCo" => assert_eq!(replaced.1, None), + _ => assert_eq!(replaced.2, Some(Adjustment::BrightnessContrast { brightness: 0.0, contrast: 0.0, legacy: false })), + } + } +} + +#[test] +fn tagged_descriptors_keep_normalization_and_adjustment_precedence() { + let d = Shared::new("null").with("Brgh", Value::Double(f64::NAN)).with("Cntr", Value::UnitFloat { unit: *b"#Prc", value: f64::INFINITY }); + let cged = bytes(*b"CgEd", d, 99); + let expected = Some(Adjustment::BrightnessContrast { brightness: 0.0, contrast: 0.0, legacy: false }); + assert_eq!(state(vec![(*b"nvrt", vec![]), (*b"CgEd", cged.clone())]).2, expected); + assert_eq!(state(vec![(*b"CgEd", cged.clone()), (*b"brit", vec![0, 42, 0, 7])]).2, expected); + assert_eq!(state(vec![(*b"CgEd", cged), (*b"nvrt", vec![])]).2, Some(Adjustment::Invert)); + let color = Shared::new("RGBC").with("Rd ", Value::Double(f64::NEG_INFINITY)).with("Grn ", Value::Double(255.0)).with("Bl ", Value::Double(0.0)); + assert_eq!(state(vec![(*b"SoCo", bytes(*b"SoCo", Shared::new("null").with("Clr ", Value::Descriptor(color)), 0))]).1, Some([0.0, 1.0, 0.0])); +} + +#[test] +fn tagged_descriptor_raw_fixture_and_limits_do_not_depend_on_shared_writer() { + for key in [*b"lfx2", *b"SoCo", *b"CgEd"] { + let mut raw = vec![255; if key == *b"lfx2" { 8 } else { 4 }]; + raw.extend([0; 8]); + raw.extend(b"null"); + raw.extend(0u32.to_be_bytes()); + let result = state(vec![(key, raw.clone())]); + if key == *b"lfx2" { + assert!(result.0.is_some()); + } + if key == *b"CgEd" { + assert!(result.2.is_some()); + } + let end = raw.len(); + raw[end - 4..].copy_from_slice(&100_001u32.to_be_bytes()); + let block = craft_psd::tagged::TaggedBlock::new(key, raw.clone()); + assert!(matches!(block.descriptor_prefix_recovering_versions_with_limits(descriptor::PARSE_LIMITS), Some(Err(craft_psd::PsdError::LimitExceeded(_))))); + let good = bytes(key, value(key), 16); + assert_eq!(state(vec![(key, good.clone()), (key, raw)]), state(vec![(key, good)])); + } +} diff --git a/crates/psd/src/tests/tysh_prefix.rs b/crates/psd/src/tests/tysh_prefix.rs new file mode 100644 index 000000000..027a21cbb --- /dev/null +++ b/crates/psd/src/tests/tysh_prefix.rs @@ -0,0 +1,115 @@ +use super::*; +use craft_psd::descriptor::{Class, Descriptor as SharedDescriptor, Id, ReferenceItem, UnicodeString, Value}; + +fn block(transform: [f64; 6], descriptor: SharedDescriptor) -> Vec { + let mut b = 999u16.to_be_bytes().to_vec(); + b.extend(transform.into_iter().flat_map(f64::to_be_bytes)); + b.extend(999u16.to_be_bytes()); + b.extend(999u32.to_be_bytes()); + b.extend(descriptor.to_bytes()); + b +} + +fn text_descriptor(text: &str) -> SharedDescriptor { + SharedDescriptor::new("TxLr").with("Txt ", Value::Text(UnicodeString::new(text))) +} + +fn parse_text(blocks: Vec>) -> Option { + let mut doc = WDoc::new(1, 1); + doc.layers = vec![WLayer::empty("Text", blocks.into_iter().map(|b| (*b"TySh", b)).collect())]; + Psd::parse(write(&doc)).unwrap().layers.remove(0).text +} + +#[test] +fn text_prefix_recovers_suffixes_and_repeated_blocks_without_changing_text_policy() { + let transform = [2.0, 0.0, 0.0, 3.0, 4.0, 5.0]; + let data = block(transform, text_descriptor("a\r\nb\rc\n\n")); + let expected = TextInfo { text: "a\nb\nc\n".into(), transform, ..Default::default() }; + for suffix in [vec![], vec![255], vec![0; 6], vec![255; 40]] { + let mut b = data.clone(); + b.extend(suffix); + assert_eq!(parse_text(vec![b]), Some(expected.clone())); + } + for cut in 0..data.len() { + assert_eq!(parse_text(vec![data[..cut].to_vec()]), None, "cut {cut}"); + assert_eq!(parse_text(vec![data.clone(), data[..cut].to_vec()]), Some(expected.clone())); + } + let last = block(transform, text_descriptor("last")); + assert_eq!(parse_text(vec![data, last]).unwrap().text, "last"); + for index in 0..6 { + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let mut t = transform; + t[index] = bad; + assert_eq!(parse_text(vec![block(t, text_descriptor("x"))]).unwrap().transform, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + } + } +} + +#[test] +fn text_prefix_preserves_descriptor_normalization_and_bounds_precedence() { + let bounds = SharedDescriptor::new("bounds") + .with("Left", Value::Double(f64::NAN)) + .with("Top ", Value::UnitFloat { unit: *b"#Pnt", value: f64::INFINITY }) + .with("Rght", Value::Double(20.0)) + .with("Btom", Value::Double(10.0)); + let d = text_descriptor("x").with("bounds", Value::Descriptor(bounds.clone())); + assert_eq!(parse_text(vec![block([1.0; 6], d)]).unwrap().bounds, Some([0.0, 0.0, 20.0, 10.0])); + let d = text_descriptor("x") + .with("bounds", Value::Descriptor(SharedDescriptor::new("bounds").with("Left", Value::Double(1.0)))) + .with("boundingBox", Value::Descriptor(bounds.clone())); + assert_eq!(parse_text(vec![block([1.0; 6], d)]).unwrap().bounds, None); + let d = text_descriptor("x").with("boundingBox", Value::Descriptor(bounds)); + assert_eq!(parse_text(vec![block([1.0; 6], d)]).unwrap().bounds, Some([0.0, 0.0, 20.0, 10.0])); + + let class = Class { name: UnicodeString::new("named"), class_id: Id::Str(b"abcd".to_vec()) }; + let d = text_descriptor("x") + .with("ref ", Value::Reference(vec![ReferenceItem::Identifier { class: class.clone(), id: 7 }])) + .with("cls ", Value::Class(class.clone())) + .with("nums", Value::UnitFloats { unit: *b"#Pxl", values: vec![f64::NEG_INFINITY, 2.0] }); + let raw = craft_psd::text::TypeLayerPrefix::from_bytes_with_limits(&block([1.0; 6], d), descriptor::PARSE_LIMITS).unwrap(); + let converted = descriptor::from_craft_descriptor(raw.descriptor); + assert_eq!(converted.class_id, "TxLr"); + assert_eq!(converted.items[1].1, descriptor::DValue::Reference(vec![descriptor::RefItem::IdentifierWithClass(class, 7)])); + assert_eq!(converted.items[2].1, descriptor::DValue::Class("named".into(), "abcd".into())); + assert_eq!(converted.items[3].1, descriptor::DValue::UnitFloats("#Pxl".into(), vec![0.0, 2.0])); +} + +#[test] +fn text_prefix_enforces_effect_descriptor_count_limit_before_reading_items() { + let mut data = block([1.0; 6], SharedDescriptor::new("TxLr")); + let end = data.len(); + data[end - 4..].copy_from_slice(&100_001u32.to_be_bytes()); + let err = craft_psd::text::TypeLayerPrefix::from_bytes_with_limits(&data, descriptor::PARSE_LIMITS).unwrap_err(); + assert!(matches!(descriptor::desc_err(err), Error::Invalid(_) | Error::Unsupported(_))); + assert_eq!(parse_text(vec![data]), None); +} + +#[test] +fn text_prefix_reads_independent_raw_header_and_text_descriptor() { + let mut data = vec![0, 9]; + for value in [1.0f64, 0.0, 0.0, 1.0, 12.0, -3.0] { + data.extend(value.to_be_bytes()); + } + // Ignored text/descriptor versions; empty class name, code class, one text item. + data.extend([0, 8, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0]); + data.extend(b"TxLr"); + data.extend(1u32.to_be_bytes()); + data.extend(0u32.to_be_bytes()); + data.extend(b"Txt TEXT"); + data.extend(4u32.to_be_bytes()); + data.extend([0, 65, 0, 13, 0, 10, 0, 66]); + let t = parse_text(vec![data]).unwrap(); + assert_eq!(t.text, "A\nB"); + assert_eq!(t.transform, [1.0, 0.0, 0.0, 1.0, 12.0, -3.0]); +} + +#[test] +fn text_prefix_keeps_first_engine_style() { + let engine = craft_psd::engine_data::minimal("x", "Courier", 24.0, [0.2, 0.4, 0.6], 1); + let d = text_descriptor("x").with("EngineData", Value::RawData(engine)); + let style = parse_text(vec![block([1.0; 6], d)]).unwrap().style; + assert_eq!(style.font.as_deref(), Some("Courier")); + assert_eq!(style.size, Some(24.0)); + assert_eq!(style.color, Some([0.2, 0.4, 0.6])); + assert_eq!(style.justification, Some(1)); +} diff --git a/crates/psd/src/tests/vector_records.rs b/crates/psd/src/tests/vector_records.rs new file mode 100644 index 000000000..531650835 --- /dev/null +++ b/crates/psd/src/tests/vector_records.rs @@ -0,0 +1,85 @@ +use super::*; + +// Independent wire fixtures: do not use the shared path encoder to test its decoder. +fn record(selector: u16, data: [u8; 24]) -> Vec { + let mut out = selector.to_be_bytes().to_vec(); + out.extend_from_slice(&data); + out +} + +fn length(selector: u16, count: u16) -> Vec { + let mut data = [0; 24]; + data[..2].copy_from_slice(&count.to_be_bytes()); + record(selector, data) +} + +fn knot(selector: u16) -> Vec { + let mut data = [0; 24]; + // Stored y then x, including negative and outside-document coordinates. + for (chunk, value) in data.as_chunks_mut::<4>().0.iter_mut().zip([-(1i32 << 23), 1 << 22, 1 << 24, -(1 << 24), 1 << 23, 1 << 25]) { + chunk.copy_from_slice(&value.to_be_bytes()); + } + record(selector, data) +} + +fn parse_mask(key: [u8; 4], bytes: Vec) -> Option { + let mut doc = WDoc::new(64, 32); + doc.layers = vec![WLayer::empty("mask", vec![(key, bytes)])]; + Psd::parse(write(&doc)).unwrap().layers.remove(0).vector_mask +} + +fn header(version: u32, flags: u32) -> Vec { + [version.to_be_bytes(), flags.to_be_bytes()].concat() +} + +#[test] +fn vector_masks_preserve_record_recovery_and_dimension_mapping() { + for key in [*b"vmsk", *b"vsms"] { + for version in [3, 99] { + for tail in 0..26 { + let mut bytes = header(version, 1 | 2 | 4 | 0x80); + bytes.extend(knot(1)); // Orphan knots are ignored, not made into a path. + bytes.extend(length(0, u16::MAX)); // Empty subpath is removed. + bytes.extend(length(3, 0)); // Counts do not control app grouping. + for selector in [1, 2, 4, 5] { + bytes.extend(knot(selector)); // Keep mixed selectors in the open path. + } + bytes.extend(record(0xffff, [0xff; 24])); + bytes.extend(length(0, 1)); + bytes.extend(knot(4)); + bytes.extend(knot(2)); // More knots than declared still belong to this path. + bytes.extend(length(3, 1)); // Empty final path is removed too. + bytes.extend(std::iter::repeat_n(0xff, tail)); + let mask = parse_mask(key, bytes).unwrap(); + assert!(mask.inverted && mask.disabled); + assert_eq!(mask.subpaths.len(), 2); + assert!(!mask.subpaths[0].closed); + assert!(mask.subpaths[1].closed); + assert_eq!(mask.subpaths[0].knots.len(), 4); + assert_eq!(mask.subpaths[1].knots.len(), 2); + for path in mask.subpaths { + for points in path.knots { + assert_eq!(points, [[16.0, -16.0], [-64.0, 32.0], [128.0, 16.0]]); + } + } + } + } + } +} + +#[test] +fn vector_masks_preserve_short_header_and_empty_path_recovery() { + for key in [*b"vmsk", *b"vsms"] { + let bytes = header(3, 0); + for len in 0..8 { + assert!(parse_mask(key, bytes[..len].to_vec()).is_none()); + } + for records in [vec![], knot(5), length(3, u16::MAX), record(8, [0xff; 24])] { + let mut bytes = header(3, 2 | 0x80); + bytes.extend(records); + let mask = parse_mask(key, bytes).unwrap(); + assert!(!mask.inverted && !mask.disabled); + assert!(mask.subpaths.is_empty()); + } + } +} diff --git a/crates/psd/src/write.rs b/crates/psd/src/write.rs index e5ec285b8..1004e28b5 100644 --- a/crates/psd/src/write.rs +++ b/crates/psd/src/write.rs @@ -434,30 +434,14 @@ pub fn solid_color_block(rgb: [f64; 3]) -> ([u8; 4], Vec) { /// `hue2`: Hue/Saturation (master). pub fn hue_sat_block(hue: i16, sat: i16, light: i16) -> ([u8; 4], Vec) { - let mut d = vec![]; - put_u16(&mut d, 2); - d.extend_from_slice(&[0, 0]); - for v in [0i16, 0, 0, hue, sat, light] { - d.extend_from_slice(&v.to_be_bytes()); - } - // Six colour ranges (unused). - d.resize(d.len() + 6 * 24, 0); - (*b"hue2", d) + let block = craft_psd::adjust::hue_saturation_block(hue, sat, light); + (block.key, block.data) } /// `levl`: Levels (composite record). pub fn levels_block(in_black: i16, in_white: i16, out_black: i16, out_white: i16, gamma: f64) -> ([u8; 4], Vec) { - let mut d = vec![]; - put_u16(&mut d, 2); - for v in [in_black, in_white, out_black, out_white, (gamma * 100.0).round() as i16] { - d.extend_from_slice(&v.to_be_bytes()); - } - for _ in 0..28 { - for v in [0i16, 255, 0, 255, 100] { - d.extend_from_slice(&v.to_be_bytes()); - } - } - (*b"levl", d) + let block = craft_psd::adjust::levels_block(in_black, in_white, out_black, out_white, (gamma * 100.0).round() as i16); + (block.key, block.data) } pub fn invert_block() -> ([u8; 4], Vec) { @@ -465,21 +449,13 @@ pub fn invert_block() -> ([u8; 4], Vec) { } pub fn brightness_block(brightness: i16, contrast: i16) -> ([u8; 4], Vec) { - let mut d = vec![]; - for v in [brightness, contrast, 127] { - d.extend_from_slice(&v.to_be_bytes()); - } - d.push(0); - (*b"brit", d) + let block = craft_psd::adjust::brightness_contrast_block(brightness, contrast); + (block.key, block.data) } pub fn exposure_block(exposure: f32, offset: f32, gamma: f32) -> ([u8; 4], Vec) { - let mut d = vec![]; - put_u16(&mut d, 1); - for v in [exposure, offset, gamma] { - d.extend_from_slice(&v.to_be_bytes()); - } - (*b"expA", d) + let block = craft_psd::adjust::exposure_block(exposure, offset, gamma); + (block.key, block.data) } /// `vmsk`: a vector mask from closed polygons/curves given as (in, anchor, out) knots in pixels. diff --git a/crates/raster/src/channels3d.rs b/crates/raster/src/channels3d.rs index 05473ca80..7dc7e44bd 100644 --- a/crates/raster/src/channels3d.rs +++ b/crates/raster/src/channels3d.rs @@ -20,6 +20,15 @@ /// Depth written where nothing was rendered. pub const BACKGROUND_DEPTH: f32 = 1.0e10; +/// The names [`AuxChannels::depth`] looks for, in order (also as `*.name` suffixes). +pub const DEPTH_NAMES: [&str; 5] = ["Z", "depth", "Depth", "zDepth", "Z-Depth"]; +/// The names [`AuxChannels::object_id`] looks for. +pub const OBJECT_ID_NAMES: [&str; 4] = ["ObjectID", "object_id", "objectId", "id"]; +/// The names [`AuxChannels::material_id`] looks for. +pub const MATERIAL_ID_NAMES: [&str; 3] = ["MaterialID", "material_id", "materialId"]; +/// The names [`AuxChannels::coverage`] looks for. +pub const COVERAGE_NAMES: [&str; 2] = ["Coverage", "coverage"]; + #[derive(Clone, Debug, Default, PartialEq)] pub struct AuxChannels { pub width: u32, @@ -30,39 +39,147 @@ pub struct AuxChannels { pub channels: Vec<(String, Vec)>, /// Cryptomatte manifests: (layer name, [(object name, hash)]). pub manifests: Vec<(String, Vec<(String, u32)>)>, + /// Channels of a multi-part OpenEXR file whose stored name is itself a `layer.channel` name + /// but doesn't start with its part's name (`Crypto_Material00.R` in part `Crypto_Material`): + /// (the name as stored, the plane's full name `Crypto_Material.Crypto_Material00.R`). + /// Lookups by the stored name find the plane; the full name is what is shown (#3271). + pub aliases: Vec<(String, String)>, + /// Every channel name of the source in order, when `channels` holds only some of them (the + /// channels a layer's effects read, #3271); empty when `channels` holds them all. Lists + /// that depend on every channel (the Cryptomatte layers) read it. + pub listed: Vec, +} + +/// What an effect reads of its layer's auxiliary channels, declared before the render +/// ([`AuxNeed`]): each lookup is resolved against the source's channel names exactly as the +/// effect resolves it on the planes, so the planes read are the ones it looks up (#3271). +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum AuxLookup { + /// [`AuxChannels::get`] of this name. + Name(String), + /// [`AuxChannels::find`] of these names. + Find(Vec), + /// The rank planes of the Cryptomatte layer the effect reads: Layer Name `name`, else the + /// layer of the Layer popup's stored value `index` ([`crypto_layer_named`]). + Crypto { name: String, index: usize }, +} + +impl AuxLookup { + /// [`AuxLookup::Find`] of `names`. + pub fn find(names: &[&str]) -> AuxLookup { + AuxLookup::Find(names.iter().map(|n| n.to_string()).collect()) + } +} + +/// The auxiliary channels a layer's effects read (#3271): all of them (an effect that doesn't +/// declare, or parameters that change over time), or what its lookups find. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub enum AuxNeed { + #[default] + All, + Lookups(Vec), +} + +impl AuxNeed { + /// What both need. + pub fn union(self, other: AuxNeed) -> AuxNeed { + match (self, other) { + (AuxNeed::Lookups(mut a), AuxNeed::Lookups(b)) => { + for l in b { + if !a.contains(&l) { + a.push(l); + } + } + AuxNeed::Lookups(a) + } + _ => AuxNeed::All, + } + } + + /// The channel names of `names` (a source's channels; planes not needed) these lookups + /// find, in channel order, once each. `None`: all of them. + pub fn resolve(&self, names: &AuxChannels) -> Option> { + let AuxNeed::Lookups(lookups) = self else { return None }; + let mut picked = vec![false; names.channels.len()]; + let mut mark = |i: Option| { + if let Some(slot) = i.and_then(|i| picked.get_mut(i)) { + *slot = true; + } + }; + for l in lookups { + match l { + AuxLookup::Name(n) => mark(names.get_index(n.trim())), + AuxLookup::Find(list) => { + let list: Vec<&str> = list.iter().map(String::as_str).collect(); + mark(names.find_index(&list)); + } + AuxLookup::Crypto { name, index } => { + if let Some(layer) = crypto_layer_named(names, name, *index) { + for (id, cov) in names.crypto_rank_indices(&layer) { + mark(Some(id)); + mark(Some(cov)); + } + } + } + } + } + Some(names.channels.iter().zip(picked).filter(|(_, p)| *p).map(|((n, _), _)| n.clone()).collect()) + } } impl AuxChannels { pub fn new(width: u32, height: u32, scale: f64) -> AuxChannels { - AuxChannels { width, height, scale, channels: vec![], manifests: vec![] } + AuxChannels { width, height, scale, channels: vec![], manifests: vec![], aliases: vec![], listed: vec![] } } - /// A channel by exact name (case-insensitive). + /// The position in [`AuxChannels::channels`] of a channel by exact name (case-insensitive), + /// or by the name a multi-part file stores it under ([`AuxChannels::aliases`]). + pub fn get_index(&self, name: &str) -> Option { + if let Some(i) = self.channels.iter().position(|(n, _)| n.eq_ignore_ascii_case(name)) { + return Some(i); + } + let full = self.aliases.iter().find(|(stored, _)| stored.eq_ignore_ascii_case(name)).map(|(_, full)| full)?; + self.channels.iter().position(|(n, _)| n == full) + } + + /// A channel by exact name (case-insensitive), or by the name a multi-part file stores it + /// under (`Crypto_Material00.R` for `Crypto_Material.Crypto_Material00.R`). pub fn get(&self, name: &str) -> Option<&[f32]> { - self.channels.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_slice()) + self.get_index(name).and_then(|i| self.channels.get(i)).map(|(_, v)| v.as_slice()) } - /// The first channel present among `names` (also matching `*.name` suffixes, so `Z` finds - /// `depth.Z`). - pub fn find(&self, names: &[&str]) -> Option<&[f32]> { + /// The position of the first channel present among `names` ([`AuxChannels::find`]). + pub fn find_index(&self, names: &[&str]) -> Option { for n in names { - if let Some(v) = self.get(n) { - return Some(v); + if let Some(i) = self.get_index(n) { + return Some(i); } } for n in names { let suffix = format!(".{}", n.to_ascii_lowercase()); - if let Some((_, v)) = self.channels.iter().find(|(c, _)| c.to_ascii_lowercase().ends_with(&suffix)) { - return Some(v); + if let Some(i) = self.channels.iter().position(|(c, _)| c.to_ascii_lowercase().ends_with(&suffix)) { + return Some(i); } } None } + /// The first channel present among `names` (also matching `*.name` suffixes, so `Z` finds + /// `depth.Z`). + pub fn find(&self, names: &[&str]) -> Option<&[f32]> { + self.find_index(names).and_then(|i| self.channels.get(i)).map(|(_, v)| v.as_slice()) + } + pub fn names(&self) -> Vec<&str> { self.channels.iter().map(|(n, _)| n.as_str()).collect() } + /// Every channel name of the source: [`AuxChannels::listed`] when `channels` holds only + /// some, else the channels'. + fn all_names(&self) -> Vec<&str> { + if self.listed.is_empty() { self.names() } else { self.listed.iter().map(String::as_str).collect() } + } + /// The layers of the channels (OpenEXR layers: the name before the last `.`; `""` for the /// unnamed layer), in channel order. pub fn layers(&self) -> Vec<&str> { @@ -80,34 +197,38 @@ impl AuxChannels { pub use craft_exr::channels::split_channel; +/// The Cryptomatte layer a channel name's first rank `R` belongs to (`CryptoObject00.R` → +/// `CryptoObject`), any case of the component letter. +fn crypto_layer_of(name: &str) -> Option<&str> { + name.strip_suffix("00.R").or_else(|| name.strip_suffix("00.r")) +} + impl AuxChannels { pub fn depth(&self) -> Option<&[f32]> { - self.find(&["Z", "depth", "Depth", "zDepth", "Z-Depth"]) + self.find(&DEPTH_NAMES) } pub fn object_id(&self) -> Option<&[f32]> { - self.find(&["ObjectID", "object_id", "objectId", "id"]) + self.find(&OBJECT_ID_NAMES) } pub fn material_id(&self) -> Option<&[f32]> { - self.find(&["MaterialID", "material_id", "materialId"]) + self.find(&MATERIAL_ID_NAMES) } pub fn coverage(&self) -> Option<&[f32]> { - self.find(&["Coverage", "coverage"]) + self.find(&COVERAGE_NAMES) } - /// Cryptomatte layer names present (prefixes with a `00.R` channel). + /// Cryptomatte layer names present (prefixes with a `00.R` channel), of every channel of the + /// source ([`AuxChannels::listed`]). pub fn crypto_layers(&self) -> Vec { - let mut v: Vec = - self.channels.iter().filter_map(|(n, _)| n.strip_suffix("00.R").or_else(|| n.strip_suffix("00.r")).map(str::to_string)).collect(); + let mut v: Vec = self.all_names().into_iter().filter_map(crypto_layer_of).map(str::to_string).collect(); v.sort(); v.dedup(); v } - /// The rank planes of Cryptomatte layer `layer`, in rank order: (ID plane, coverage plane) - /// for `layer00.R/G`, `layer00.B/A`, `layer01.R/G`, ... Resolve them once per evaluation and - /// index them per pixel; looking the channels up by name for every pixel is what made the - /// effect slow. - pub fn crypto_rank_planes(&self, layer: &str) -> Vec<(&[f32], &[f32])> { + /// The positions in [`AuxChannels::channels`] of the rank planes of Cryptomatte layer + /// `layer`, paired as [`AuxChannels::crypto_rank_planes`] pairs them. + pub fn crypto_rank_indices(&self, layer: &str) -> Vec<(usize, usize)> { let mut out = vec![]; for k in 0.. { let (r, g, b, a) = (self.rank(layer, k, 'R'), self.rank(layer, k, 'G'), self.rank(layer, k, 'B'), self.rank(layer, k, 'A')); @@ -120,17 +241,32 @@ impl AuxChannels { out } - /// The plane `{layer}{k:02}.{comp}`: the layer name matches case-sensitively (layers - /// `Crypto_A` and `crypto_a` are different layers), the component letter either case. - fn rank(&self, layer: &str, k: usize, comp: char) -> Option<&[f32]> { + /// The rank planes of Cryptomatte layer `layer`, in rank order: (ID plane, coverage plane) + /// for `layer00.R/G`, `layer00.B/A`, `layer01.R/G`, ... Resolve them once per evaluation and + /// index them per pixel; looking the channels up by name for every pixel is what made the + /// effect slow. + pub fn crypto_rank_planes(&self, layer: &str) -> Vec<(&[f32], &[f32])> { + let plane = |i: usize| self.channels.get(i).map(|(_, v)| v.as_slice()); + self.crypto_rank_indices(layer).into_iter().filter_map(|(id, cov)| Some((plane(id)?, plane(cov)?))).collect() + } + + /// The position of plane `{layer}{k:02}.{comp}`: the layer name matches case-sensitively + /// (layers `Crypto_A` and `crypto_a` are different layers), the component letter either + /// case; also by the name a multi-part file stores it under ([`AuxChannels::aliases`]). + fn rank(&self, layer: &str, k: usize, comp: char) -> Option { let tail = format!("{k:02}.{comp}"); - self.channels.iter().find(|(n, _)| n.strip_prefix(layer).is_some_and(|rest| rest.eq_ignore_ascii_case(&tail))).map(|(_, v)| v.as_slice()) + let is_rank = |n: &str| n.strip_prefix(layer).is_some_and(|rest| rest.eq_ignore_ascii_case(&tail)); + if let Some(i) = self.channels.iter().position(|(n, _)| is_rank(n)) { + return Some(i); + } + let full = self.aliases.iter().find(|(stored, _)| is_rank(stored)).map(|(_, full)| full)?; + self.channels.iter().position(|(n, _)| n == full) } /// Rank pairs (id, coverage) of Cryptomatte layer `layer` at aux pixel index `i`. For a /// loop over pixels, use [`AuxChannels::crypto_rank_planes`] once instead. pub fn crypto_ranks(&self, layer: &str, i: usize) -> Vec<(f32, f32)> { - self.crypto_rank_planes(layer).iter().map(|(id, c)| (id[i], c[i])).collect() + self.crypto_rank_planes(layer).iter().filter_map(|(id, c)| Some((*id.get(i)?, *c.get(i)?))).collect() } /// The Cryptomatte layer an effect asking for `want` (`CryptoObject`, …) reads: an exact @@ -144,6 +280,8 @@ impl AuxChannels { /// exactly `name` when it is not empty and the footage has it (`Crypto_Material`, a name an /// imported After Effects project carries), else the layer for `want`. /// The name as given is tried first (EXR channel names may carry spaces), then trimmed. + /// A multi-part file's layer is also found by the name its part stores it under + /// (`Crypto_Material` for `Crypto_Material.Crypto_Material`, [`AuxChannels::aliases`]). pub fn resolve_crypto_layer_named(&self, name: &str, want: &str) -> Option { let layers = self.crypto_layers(); for name in [name, name.trim()] { @@ -151,9 +289,29 @@ impl AuxChannels { return Some(name.to_string()); } } + for name in [name, name.trim()] { + if name.is_empty() { + continue; + } + let full = self.aliases.iter().filter(|(stored, _)| crypto_layer_of(stored) == Some(name)).find_map(|(_, full)| crypto_layer_of(full)); + if let Some(full) = full.filter(|f| layers.iter().any(|l| l == f)) { + return Some(full.to_string()); + } + } self.resolve_crypto_layer(want) } + /// The manifest of Cryptomatte layer `layer`: the one named as the layer, else the one named + /// as a multi-part file's part stores the layer (the manifest `Crypto_Material` for the layer + /// `Crypto_Material.Crypto_Material`). + pub fn manifest(&self, layer: &str) -> Option<&[(String, u32)]> { + if let Some((_, m)) = self.manifests.iter().find(|(l, _)| l == layer) { + return Some(m.as_slice()); + } + let stored = self.aliases.iter().filter(|(_, full)| crypto_layer_of(full) == Some(layer)).find_map(|(stored, _)| crypto_layer_of(stored))?; + self.manifests.iter().find(|(l, _)| l == stored).map(|(_, m)| m.as_slice()) + } + /// The ID (its hash, `f32::to_bits`) with the most coverage at aux pixel `i` of Cryptomatte /// layer `layer`, summed over the ranks it appears in. Ties go to the lower rank; IDs with /// no positive coverage don't count. `None` when nothing covers the pixel. @@ -185,10 +343,72 @@ impl AuxChannels { /// Manifest entry name for a hash in Cryptomatte layer `layer`. pub fn manifest_name(&self, layer: &str, hash: u32) -> Option<&str> { - self.manifests.iter().find(|(l, _)| l == layer)?.1.iter().find(|(_, h)| *h == hash).map(|(n, _)| n.as_str()) + self.manifest(layer)?.iter().find(|(_, h)| *h == hash).map(|(n, _)| n.as_str()) } } +/// The Cryptomatte layers every renderer names, and the Layer popup's options when the footage +/// has no Cryptomatte metadata. The stored Layer value is an index: 0-2 are these (an exact +/// match or a suffix such as `ViewLayer.CryptoObject`), 3 and up are the file's other Cryptomatte +/// layers in name order, so a project saved before the popup followed the footage loads unchanged. +pub const CRYPTO_LAYERS: [&str; 3] = ["CryptoObject", "CryptoMaterial", "CryptoAsset"]; + +/// The Layer popup's entries for Cryptomatte `layers` (sorted, as [`AuxChannels::crypto_layers`] +/// returns them): the stored value and the layer's name, in value order. Of several layers +/// that fit one standard slot (`A.CryptoObject`, `B.CryptoObject`) the first one keeps the standard +/// slot, so existing projects load unchanged, and the others get the next custom slots. +fn crypto_layer_slots(layers: &[String]) -> Vec<(usize, &str)> { + let mut out: Vec<(usize, &str)> = vec![]; + let mut custom = CRYPTO_LAYERS.len(); + for l in layers { + match CRYPTO_LAYERS.iter().position(|w| l == w || l.ends_with(w)) { + Some(i) if !out.iter().any(|(j, _)| *j == i) => out.push((i, l)), + _ => { + out.push((custom, l)); + custom += 1; + } + } + } + out.sort_by_key(|(i, _)| *i); + out +} + +/// What the Layer popup lists for the footage `aux`: the Cryptomatte layers the file has, as +/// (stored value, name), or the three standard ones when there is none (no footage, not an +/// OpenEXR, no Cryptomatte channels). +pub fn crypto_layer_choices(aux: Option<&AuxChannels>) -> Vec<(usize, String)> { + crypto_layer_menu(aux, 0).0 +} + +/// The Layer popup for the stored value `index`: [`crypto_layer_choices`], and the name of the +/// entry the effect reads (the first when `index` names none, as the effect does). +pub fn crypto_layer_menu(aux: Option<&AuxChannels>, index: usize) -> (Vec<(usize, String)>, Option) { + let layers = aux.map(AuxChannels::crypto_layers).unwrap_or_default(); + if layers.is_empty() { + let all: Vec<(usize, String)> = CRYPTO_LAYERS.iter().enumerate().map(|(i, n)| (i, n.to_string())).collect(); + let shown = all.iter().find(|c| c.0 == index).or(all.first()).map(|c| c.1.clone()); + return (all, shown); + } + let slots = crypto_layer_slots(&layers); + let shown = slots.iter().find(|(i, _)| *i == index).map(|(_, n)| n.to_string()).or_else(|| layers.first().cloned()); + (slots.into_iter().map(|(i, n)| (i, n.to_string())).collect(), shown) +} + +/// The Cryptomatte layer the effect reads: the one called `name` when the footage has it (Layer +/// Name, the layer an imported After Effects project names), else [`crypto_layer_name`]'s. +pub fn crypto_layer_named(aux: &AuxChannels, name: &str, index: usize) -> Option { + aux.resolve_crypto_layer_named(name, &crypto_layer_name(aux, index)?) +} + +/// The Cryptomatte layer of `aux` that the stored Layer value `index` reads: its slot's layer, else +/// the first layer (what a file without that layer has always shown). `None` without any. +pub fn crypto_layer_name(aux: &AuxChannels, index: usize) -> Option { + if aux.crypto_layers().is_empty() { + return None; + } + crypto_layer_menu(Some(aux), index).1 +} + pub use craft_exr::cryptomatte::{hash as crypto_hash, murmur3_32}; /// The ID float stored in Cryptomatte channels for a hash. @@ -316,4 +536,65 @@ mod tests { assert_eq!(a.crypto_id_at("Crypto_A", 0), Some(crypto_hash("upper"))); assert!(a.crypto_rank_planes("CRYPTO_A").is_empty()); } + + /// A names-only set of channels (planes of one sample) named `names`. + fn named(names: &[&str]) -> AuxChannels { + let mut a = AuxChannels::new(1, 1, 1.0); + a.channels = names.iter().map(|n| (n.to_string(), vec![0.0])).collect(); + a + } + + /// #3271: a multi-part file stores `Crypto_Material00.R` in part `Crypto_Material`; the plane + /// is shown as `Crypto_Material.Crypto_Material00.R` (as today) and found by its stored name, + /// its layer by the part's name, and the manifest named after the part. Bare stored names + /// (`R` of part `Image`) don't stand for the part's channel. + #[test] + fn multipart_channels_are_found_by_their_stored_names() { + let mut a = named(&["Crypto_Material.Crypto_Material00.R", "Crypto_Material.Crypto_Material00.G", "Image.R"]); + for c in ["R", "G"] { + a.aliases.push((format!("Crypto_Material00.{c}"), format!("Crypto_Material.Crypto_Material00.{c}"))); + } + a.manifests = vec![("Crypto_Material".into(), vec![("bunny".into(), 7)])]; + assert_eq!(a.get_index("Crypto_Material00.R"), Some(0)); + assert_eq!(a.get_index("crypto_material00.g"), Some(1), "any case, as full names"); + assert!(a.get("R").is_none(), "a bare name is not an alias"); + assert_eq!(a.crypto_layers(), ["Crypto_Material.Crypto_Material"], "the shown name is unchanged"); + let layer = a.resolve_crypto_layer_named("Crypto_Material", "CryptoObject"); + assert_eq!(layer.as_deref(), Some("Crypto_Material.Crypto_Material")); + assert_eq!(a.crypto_rank_indices("Crypto_Material.Crypto_Material"), [(0, 1)]); + assert_eq!(a.crypto_rank_indices("Crypto_Material"), [(0, 1)], "by the stored layer name too"); + assert_eq!(a.manifest_name("Crypto_Material.Crypto_Material", 7), Some("bunny")); + assert_eq!(crypto_layer_named(&a, "Crypto_Material", 0).as_deref(), Some("Crypto_Material.Crypto_Material")); + } + + /// #3271: declared lookups resolve against the channel names as the effects resolve them on + /// the planes; a set holding only some channels keeps listing every Cryptomatte layer. + #[test] + fn needs_resolve_as_the_effects_look_up() { + let all = named(&[ + "A.CryptoAsset00.R", + "A.CryptoAsset00.G", + "B.CryptoObject00.R", + "B.CryptoObject00.G", + "Image.R", + "depth.Z", + "zz.Custom00.R", + "zz.Custom00.G", + ]); + let need = AuxNeed::Lookups(vec![ + AuxLookup::Name(" image.r ".into()), + AuxLookup::find(&DEPTH_NAMES), + AuxLookup::Crypto { name: String::new(), index: 3 }, + AuxLookup::Name("missing".into()), + ]); + assert_eq!(need.resolve(&all).unwrap(), ["Image.R", "depth.Z", "zz.Custom00.R", "zz.Custom00.G"]); + assert_eq!(AuxNeed::All.resolve(&all), None); + assert_eq!(AuxNeed::All.union(need.clone()), AuxNeed::All); + assert_eq!(need.clone().union(need.clone()), need, "once each"); + // The planes read, with every name listed: the custom slot still names the same layer. + let mut some = named(&["zz.Custom00.R", "zz.Custom00.G"]); + some.listed = all.names().iter().map(|n| n.to_string()).collect(); + assert_eq!(some.crypto_layers(), all.crypto_layers()); + assert_eq!(crypto_layer_name(&some, 3), crypto_layer_name(&all, 3)); + } } diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index cd67e846a..e3d8d8a9e 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -16,6 +16,7 @@ effectcraft-color = { workspace = true } effectcraft-keyframe = { workspace = true } effectcraft-project = { workspace = true } effectcraft-raster = { workspace = true } +half = { workspace = true } effectcraft-path = { workspace = true } effectcraft-text = { workspace = true } effectcraft-effects = { workspace = true } diff --git a/crates/render/src/accel.rs b/crates/render/src/accel.rs index 21f609574..6fe259fb4 100644 --- a/crates/render/src/accel.rs +++ b/crates/render/src/accel.rs @@ -245,11 +245,18 @@ impl<'a> Renderer<'a> { /// OpenEXR footage's at the layer's source time (Time Remap included), or a precomp's /// generated 3D channels at its nested time. `None` for other layers. pub fn layer_aux(&self, ctx: &EvalCtx, layer: &Layer) -> Option> { + self.layer_aux_with(ctx, layer, &self.layer_aux_need(ctx, layer)) + } + + /// [`Renderer::layer_aux`] of what `need` reads (a footage layer's channels; a precomp's + /// generated channels are all made anyway). + pub fn layer_aux_with(&self, ctx: &EvalCtx, layer: &Layer, need: &effectcraft_raster::channels3d::AuxNeed) -> Option> { match &layer.source { LayerSource::Footage { item } => { let item = ctx.media_item(layer, *item); let ItemKind::Footage(f) = &self.project.item(item)?.kind else { return None }; - let a = self.read(|| self.footage.aux(item, f, ctx.source_time(layer)))?; + // Only what the layer's effects read (#3271). + let a = self.read(|| self.footage.aux_for(item, f, ctx.source_time(layer), need))?; // Aux pixels per layer pixel (the layer is the footage at its nominal size). The // planes are only copied when that changes the scale. let scale = a.width as f64 / f.width as f64; @@ -270,6 +277,27 @@ impl<'a> Renderer<'a> { } } + /// What the enabled effects of `layer` read of its auxiliary channels at the context time + /// ([`effectcraft_effects::aux_needs`], #3271): the union of their lookups (none when no + /// effect reads them). + pub fn layer_aux_need(&self, ctx: &EvalCtx, layer: &Layer) -> effectcraft_raster::channels3d::AuxNeed { + use effectcraft_raster::channels3d::AuxNeed; + let mut need: Option = None; + for g in layer.effects().into_iter().flat_map(|fx| fx.groups()).filter(|g| g.enabled) { + let effectcraft_project::GroupKind::Effect { effect } = &g.kind else { continue }; + if !effectcraft_effects::reads_aux(effect) { + continue; + } + let params = effectcraft_effects::flatten_params(g, &mut |pr| ctx.value(layer, pr)); + let one = effectcraft_effects::aux_need(effect, ¶ms); + need = Some(match need { + Some(n) => n.union(one), + None => one, + }); + } + need.unwrap_or(AuxNeed::Lookups(vec![])) + } + /// Evaluation context of comp `comp_id` at comp time `t`. pub fn eval_ctx(&self, comp_id: ItemId, t: Tick) -> Option> { Some(self.ctx(comp_id, self.project.comp(comp_id)?, t)) @@ -374,6 +402,8 @@ impl<'a> Renderer<'a> { pub fn adjustment_footprint(&self, ctx: &EvalCtx, layer: &Layer) -> Option> { // Cached, so an accelerator sees the same buffer (and uploads it once) every frame. let key = self.cache.and_then(|_| cache::footprint_key(ctx, layer, self.raster_scale(ctx, layer), self.opts.draft, self.mb_on(ctx, layer))); + // (a footage layer read in part is never kept under a whole layer's key, #3271) + let key = key.filter(|_| !self.reads_footage_rows(ctx, layer)); let key = self.mask_gate_key(ctx, layer, self.clipped_key(ctx, layer, key)); if let Some((b, _)) = self.cached(key) { return Some(b); diff --git a/crates/render/src/cache.rs b/crates/render/src/cache.rs index d58301185..06ed04b75 100644 --- a/crates/render/src/cache.rs +++ b/crates/render/src/cache.rs @@ -54,10 +54,17 @@ struct Entry { files: Arc, bytes: usize, last_use: u64, + /// When it was last used, for the memory accountant ([`crate::memory::tick`]). + used: u64, + /// What it took to make (its render, or its read from the disk cache), in microseconds. + cost_us: u64, } struct Inner { map: HashMap, + /// The keys by last use (`Entry::last_use`, unique: the clock moves on every use), oldest + /// first: the memory accountant asks for the oldest often, so it is not looked for. + order: std::collections::BTreeMap, bytes: usize, budget: usize, clock: u64, @@ -67,6 +74,76 @@ struct Inner { /// a render's reads started at travels with its files instead, [`ReadFiles::since`]: two /// renders of a key may overlap). missed_at: HashMap, + /// Keys let go of lately (newest last, at most [`EVICTED_KEPT`]) and how many of them were + /// asked for again: a cache that keeps making again what it just let go of is thrashing + /// ([`crate::memory::MemoryHolder::refills`]). + evicted: std::collections::VecDeque, + refills: u64, +} + +/// Keys of evicted buffers remembered to tell a refill (#3271). +const EVICTED_KEPT: usize = 256; + +impl Inner { + /// The least recently used entry's key. + fn oldest_key(&self) -> Option { + self.order.first_key_value().map(|(_, k)| *k) + } + + /// The least recently used entry nobody else holds (a render using its buffer): what the + /// memory accountant may drop to free memory now. + fn oldest_free_key(&self) -> Option { + self.order.values().copied().find(|k| self.map.get(k).is_some_and(|e| Arc::strong_count(&e.buf) == 1)) + } + + /// Mark the entry under `key` as used at `now` (the clock), for `order` and the accountant. + fn touch(&mut self, key: u64, now: u64) { + let Some(e) = self.map.get_mut(&key) else { return }; + self.order.remove(&e.last_use); + e.last_use = now; + e.used = crate::memory::tick(); + self.order.insert(now, key); + } + + /// Keep `e` under `key` (replacing what was there). + fn put(&mut self, key: u64, e: Entry) { + self.order.insert(e.last_use, key); + self.bytes = self.bytes.saturating_add(e.bytes); + if let Some(old) = self.map.insert(key, e) { + self.order.remove(&old.last_use); + self.bytes = self.bytes.saturating_sub(old.bytes); + } + } + + /// Take the entry under `key` out (its bytes no longer counted). + fn take(&mut self, key: u64) -> Option { + let e = self.map.remove(&key)?; + self.order.remove(&e.last_use); + self.bytes = self.bytes.saturating_sub(e.bytes); + Some(e) + } + + /// Drop the entry under `key`, remembering its key (a refill if it is asked for again); + /// the bytes freed. + fn evict(&mut self, key: u64) -> usize { + let Some(e) = self.take(key) else { return 0 }; + if self.evicted.len() >= EVICTED_KEPT { + self.evicted.pop_front(); + } + self.evicted.push_back(key); + e.bytes + } + + /// Drop least recently used entries until at most `bytes` are held, remembering their keys. + fn evict_to(&mut self, bytes: usize) { + if self.bytes <= bytes { + return; + } + while self.bytes > bytes { + let Some(k) = self.oldest_key() else { break }; + self.evict(k); + } + } } /// Hit/miss counters and memory use (for perf readouts and tests). @@ -88,7 +165,18 @@ impl LayerCache { /// A cache holding at most `budget` bytes of pixels. pub fn new(budget: usize) -> LayerCache { LayerCache { - inner: Mutex::new(Inner { map: HashMap::new(), bytes: 0, budget, clock: 0, hits: 0, misses: 0, missed_at: HashMap::new() }), + inner: Mutex::new(Inner { + map: HashMap::new(), + order: Default::default(), + bytes: 0, + budget, + clock: 0, + hits: 0, + misses: 0, + missed_at: HashMap::new(), + evicted: Default::default(), + refills: 0, + }), disk: Mutex::new(None), store: Mutex::new(None), virtual_id: Mutex::new(None), @@ -162,6 +250,11 @@ impl LayerCache { None => { let mut g = self.inner.lock().ok()?; g.misses += 1; + // (made again shortly after it was let go of: a refill) + if let Some(at) = g.evicted.iter().position(|k| *k == key) { + g.evicted.remove(at); + g.refills += 1; + } drop(g); let store = self.persistent(); // (before the entry is read: what it is made of may be dropped meanwhile) @@ -175,10 +268,11 @@ impl LayerCache { // Disk cache: a hit comes back into memory, read at generation `since`. let store = store?; let id = self.virtual_id(); + let read = web_time::Instant::now(); let (buf, mut files) = store.get_layer(layer_disk_key(key), id.as_deref())?; files.note_since(since); let files = Arc::new(files); - Some(self.insert_mem(key, buf, files)) + Some(self.insert_mem(key, buf, files, Some(read.elapsed()))) } } } @@ -222,7 +316,7 @@ impl LayerCache { store.put_layer(layer_disk_key(key), &buf, &entry, since); } } - self.insert_mem(key, buf, files) + self.insert_mem(key, buf, files, started.map(|t| t.elapsed())) } /// The buffer kept in memory under `key` with its files, if it is not made of a file dropped @@ -240,18 +334,18 @@ impl LayerCache { let mut g = self.inner.lock().ok()?; g.clock += 1; let now = g.clock; - let e = g.map.get_mut(&key)?; + let e = g.map.get(&key)?; + let found = (e.buf.clone(), e.files.clone()); if hit { - e.last_use = now; + g.touch(key, now); } - (e.buf.clone(), e.files.clone()) + found }; if self.made_before_a_drop(&found.1) { if let Ok(mut g) = self.inner.lock() && g.map.get(&key).is_some_and(|e| Arc::ptr_eq(&e.files, &found.1)) - && let Some(e) = g.map.remove(&key) { - g.bytes = g.bytes.saturating_sub(e.bytes); + g.take(key); } return None; } @@ -276,45 +370,43 @@ impl LayerCache { /// See [`LayerCache::insert`]: the buffer kept under `key` and its files (`buf` and `files`, /// unless one was kept first or `buf` is too large to keep). - fn insert_mem(&self, key: u64, buf: Arc, files: Arc) -> (Arc, Arc) { + /// `took`: what making it took (`None`: not timed; a typical cost is assumed, + /// [`crate::memory::DEFAULT_LAYER_US_PER_MB`]). + fn insert_mem(&self, key: u64, buf: Arc, files: Arc, took: Option) -> (Arc, Arc) { let bytes = buf.img.data.len() * std::mem::size_of::(); + let cost_us = took.map_or_else( + || crate::memory::default_cost(bytes, crate::memory::DEFAULT_LAYER_US_PER_MB), + |t| u64::try_from(t.as_micros()).unwrap_or(u64::MAX).max(1), + ); let Ok(mut g) = self.inner.lock() else { return (buf, files) }; if bytes > g.budget / 4 { return (buf, files); } g.clock += 1; let now = g.clock; - if let Some(e) = g.map.get_mut(&key) { + if let Some(e) = g.map.get(&key) { // (one made before a drop gives way: see [`LayerCache::kept`]) if !self.made_before_a_drop(&e.files) { - e.last_use = now; - return (e.buf.clone(), e.files.clone()); - } - if let Some(old) = g.map.remove(&key) { - g.bytes = g.bytes.saturating_sub(old.bytes); + let kept = (e.buf.clone(), e.files.clone()); + g.touch(key, now); + return kept; } + g.take(key); } // (checked again just before it is published: a drop may have come since `insert` // checked; one that comes later is caught when the buffer is looked up) if self.made_before_a_drop(&files) { return (buf, files); } - g.map.insert(key, Entry { buf: buf.clone(), files: files.clone(), bytes, last_use: now }); - g.bytes += bytes; + g.put(key, Entry { buf: buf.clone(), files: files.clone(), bytes, last_use: now, used: crate::memory::tick(), cost_us }); if g.bytes > g.budget { // Evict least-recently used entries down to 3/4 of the budget. let target = g.budget / 4 * 3; - let mut by_age: Vec<(u64, u64)> = g.map.iter().map(|(k, e)| (e.last_use, *k)).collect(); - by_age.sort_unstable(); - for (_, k) in by_age { - if g.bytes <= target { - break; - } - if let Some(e) = g.map.remove(&k) { - g.bytes -= e.bytes; - } - } + g.evict_to(target); } + drop(g); + // (with the lock released: the accountant asks every cache for its bytes) + crate::memory::Accountant::global().note_growth(bytes); (buf, files) } @@ -327,23 +419,13 @@ impl LayerCache { pub fn set_budget(&self, budget: usize) { let Ok(mut g) = self.inner.lock() else { return }; g.budget = budget; - if g.bytes > budget { - let mut by_age: Vec<(u64, u64)> = g.map.iter().map(|(k, e)| (e.last_use, *k)).collect(); - by_age.sort_unstable(); - for (_, k) in by_age { - if g.bytes <= budget { - break; - } - if let Some(e) = g.map.remove(&k) { - g.bytes -= e.bytes; - } - } - } + g.evict_to(budget); } pub fn clear(&self) { if let Ok(mut g) = self.inner.lock() { g.map.clear(); + g.order.clear(); g.bytes = 0; } } @@ -717,11 +799,22 @@ fn history_unkeyable(layer: &Layer, effects: Option) -> bool { reads_other_times(layer, effects) && layer.props.children.iter().any(|c| matches!(c, Node::Group(g) if g.match_id != "transform" && has_expression(g))) } -/// A still image (no proxy): its layer is cached like a text or shape layer, so the GPU -/// compositor uploads it once, not every frame (#1812: four 21120 px plates re-uploaded by every -/// preview worker ran the GPU out of memory). Movies and sequences stay in the media pool only. -fn still_footage(ctx: &EvalCtx, item: effectcraft_project::ItemId) -> bool { - ctx.project.item(item).is_some_and(|it| it.proxy.is_none() && matches!(&it.kind, ItemKind::Footage(f) if f.kind == FootageKind::Still)) +/// Footage whose processed layer is cached (keyed by item and source time for all but stills): +/// - a still image (no proxy): its layer is cached like a text or shape layer, so the GPU +/// compositor uploads it once, not every frame (#1812: four 21120 px plates re-uploaded by +/// every preview worker ran the GPU out of memory); +/// - an OpenEXR sequence (no proxy, #3271): each frame is a file read whole and its effects +/// (EXtractoR, Cryptomatte, depth effects) are costly, so a processed frame is worth keeping in +/// RAM and on disk. Its entries list the frame file they read, so Reload Footage and a changed +/// file drop them as any other. +/// +/// Movies and other sequences stay in the media pool only. +fn cached_footage(ctx: &EvalCtx, item: effectcraft_project::ItemId) -> bool { + ctx.project.item(item).is_some_and(|it| { + it.proxy.is_none() + && matches!(&it.kind, ItemKind::Footage(f) if f.kind == FootageKind::Still + || (f.kind == FootageKind::Sequence && f.sequence.first().is_some_and(|p| p.to_ascii_lowercase().ends_with(".exr")))) + }) } /// Does the layer have an animated mask that motion blur may draw at other times (Layer ▸ Mask ▸ @@ -796,7 +889,7 @@ fn key_any(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool, blur: bool, fo hash_debug(&mut h, s); } LayerSource::Text | LayerSource::Shape => {} - LayerSource::Footage { item } if footage || still_footage(ctx, ctx.media_item(layer, *item)) => { + LayerSource::Footage { item } if footage || cached_footage(ctx, ctx.media_item(layer, *item)) => { let item = ctx.media_item(layer, *item); let it = ctx.project.item(item)?; let ItemKind::Footage(f) = &it.kind else { return None }; @@ -806,7 +899,19 @@ fn key_any(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool, blur: bool, fo item.hash(&mut h); // A still is the same at every time (unless a proxy, which may be a movie, stands in). if f.kind != FootageKind::Still || it.proxy.is_some() { - ctx.source_time(layer).0.hash(&mut h); + // A sequence frame without frame blending or fields shows one file for its whole + // frame duration: keyed by its frame, so times within it (a faster comp, a + // stretched layer) share the entry (#3271). + let whole_frames = f.kind == FootageKind::Sequence + && it.proxy.is_none() + && f.fields == effectcraft_project::FieldOrder::Off + && crate::frames::frame_blend_mode(ctx, layer) == effectcraft_project::FrameBlend::Off; + if whole_frames { + 0x5e9_u16.hash(&mut h); + crate::frames::frame_position(ctx.source_time(layer), f.frame_rate).0.hash(&mut h); + } else { + ctx.source_time(layer).0.hash(&mut h); + } } // Frame blending mixes neighbouring source frames. ctx.comp.enable_frame_blending.hash(&mut h); @@ -952,6 +1057,34 @@ pub fn derive(key: u64, i: u64) -> u64 { h.finish() } +/// The layer cache in the common memory budget (#3271, #3298): each buffer is worth what +/// rendering it took (or reading it from the disk cache), per byte. +impl crate::memory::MemoryHolder for LayerCache { + fn name(&self) -> &'static str { + "layer cache" + } + fn bytes(&self) -> usize { + self.inner.lock().map(|g| g.bytes).unwrap_or(0) + } + /// Its least recently used buffer nobody else holds (dropping one a render holds would free + /// nothing yet), with what rendering it took. + fn oldest(&self) -> Option { + let g = self.inner.lock().ok()?; + let e = g.map.get(&g.oldest_free_key()?)?; + Some(crate::memory::Candidate { used: e.used, bytes: e.bytes, cost_us: e.cost_us, protected: false }) + } + fn drop_oldest(&self) -> usize { + let Ok(mut g) = self.inner.lock() else { return 0 }; + match g.oldest_free_key() { + Some(k) => g.evict(k), + None => 0, + } + } + fn refills(&self) -> u64 { + self.inner.lock().map(|g| g.refills).unwrap_or(0) + } +} + #[cfg(test)] mod shared_insert_tests { use std::sync::Arc; @@ -960,6 +1093,24 @@ mod shared_insert_tests { use effectcraft_effects::Buf; use effectcraft_raster::Image; + /// #3301 review: the memory accountant is offered only buffers nobody else holds; dropping + /// one a render still holds would free nothing, and its bytes would be counted as freed. + #[test] + fn a_buffer_held_elsewhere_is_not_offered_to_the_accountant() { + use crate::memory::MemoryHolder; + let cache = LayerCache::default(); + let buf = || Arc::new(Buf { img: Image::new(4, 4), offset: [0.0; 2], scale: 1.0 }); + let held = cache.insert(1, buf(), Default::default()).0; + drop(cache.insert(2, buf(), Default::default())); + let bytes = cache.bytes(); + let freed = cache.drop_oldest(); + assert!(freed > 0 && cache.get(1).is_some() && cache.get(2).is_none(), "the free one goes, the held one stays"); + assert_eq!(cache.bytes(), bytes - freed); + assert!(cache.oldest().is_none() && cache.drop_oldest() == 0, "only a held buffer left"); + drop(held); + assert!(cache.drop_oldest() > 0, "let go: offered"); + } + /// Two renders of one layer kept under one key: both use the buffer kept first. #[test] fn the_buffer_kept_first_is_shared() { diff --git a/crates/render/src/disk_cache.rs b/crates/render/src/disk_cache.rs index 3674b2667..1985060c2 100644 --- a/crates/render/src/disk_cache.rs +++ b/crates/render/src/disk_cache.rs @@ -53,15 +53,20 @@ const MAGIC: &[u8; 4] = b"ECDC"; /// Pending layer and matte writes before new ones are dropped. #[cfg(not(target_arch = "wasm32"))] const QUEUE_LIMIT: usize = 64; +/// What reading a megabyte of a disk cache entry back is assumed to take until reads are +/// measured, in microseconds: 10 ms (100 MB/s, a slow disk or a network share), so a quick frame +/// is not written on a guess ([`DiskCache::pays_off`]). +pub const DEFAULT_READ_US_PER_MB: u64 = 10_000; + /// Pending frame bytes before new frames are dropped. Frames have their own lane, written /// before layer buffers: a burst of large layer writes used to fill the shared queue and drop /// frames, so a fully cached comp came back with gaps in its blue bar. #[cfg(not(target_arch = "wasm32"))] const FRAME_QUEUE_BYTES: usize = 1 << 30; -/// Pending layer and matte bytes before new ones are dropped: a layer job holds its float -/// buffer until the writer compresses it (64 of them at 4K were ~8.5 GB). +/// Pending layer and plane bytes (uncompressed: they are encoded on the writer thread, #3271) +/// before new ones are dropped. #[cfg(not(target_arch = "wasm32"))] -const LAYER_QUEUE_BYTES: usize = 1 << 30; +const JOB_QUEUE_BYTES: usize = 1 << 30; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Kind { @@ -69,6 +74,9 @@ pub enum Kind { Layer, /// A Roto Brush / Object Matte segmentation. Matte, + /// Decoded footage channels (an OpenEXR frame's planes, #3271): read instead of decoding + /// the file again, after RAM let them go or in the next session. + Plane, } impl Kind { @@ -78,6 +86,7 @@ impl Kind { Kind::Frame => "frames", Kind::Layer => "layers", Kind::Matte => "mattes", + Kind::Plane => "planes", } } fn tag(self) -> u8 { @@ -85,6 +94,7 @@ impl Kind { Kind::Frame => 1, Kind::Layer => 2, Kind::Matte => 3, + Kind::Plane => 4, } } } @@ -116,6 +126,31 @@ const FORMAT_F16_FILES: u8 = 3; /// Layer entries: their source files ([`EntryFiles`]), then the buffer. The format before it /// (0, without files) reads as a miss and is deleted. const FORMAT_LAYER_FILES: u8 = 4; +/// Plane entries: their source file ([`EntryFiles`]), then one named plane ([`encode_plane_after`]). +/// (5, several `f32` planes per entry, reads as a miss and is deleted.) +const FORMAT_PLANES_FILES: u8 = 6; + +/// The most plane bytes one queued write of decoded footage channels holds +/// ([`DiskCache::put_planes`]). +#[cfg(not(test))] +const PLANE_JOB_BYTES: usize = 256 << 20; +#[cfg(test)] +const PLANE_JOB_BYTES: usize = 64 << 10; + +/// The most pixels a plane entry holds (a damaged entry can't ask for more). +const MAX_ENTRY_PIXELS: usize = 1 << 28; + +/// The disk key of a decoded footage channel: the source file's path and identity as read, and +/// the channel's name. +pub fn plane_key(path: &str, stamp: &crate::reads::FileStamp, channel: &str) -> u128 { + let mut h = Hash128::default(); + h.write(b"plane-v2"); + h.write(path.as_bytes()); + h.write(format!("{stamp:?}").as_bytes()); + h.write_u64(channel.len() as u64); + h.write(channel.as_bytes()); + h.finish() +} /// Counters for tests, the Info panel and `cache.diskStats`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -267,38 +302,111 @@ impl LayerPrefetch { #[cfg_attr(target_arch = "wasm32", allow(dead_code))] enum Job { - /// Kind, key, header format byte, payload. + /// Kind, key, header format byte, payload (encoded on the writer thread). Write(Kind, u128, u8, Payload), /// Delete the frame and layer entries made of these files ([`DiskCache::drop_files`]). Drop(Vec>), } -/// What a queued write holds. 8-bit frames and layer buffers are encoded (LZ4) on the writer -/// thread, not on the render thread that queued them: encoding a 1080p frame took ~9 ms of every -/// frame's render, and a full queue no longer throws away encoding work. +/// What a queued write stores, encoded on the writer thread (#3271): rendering threads hand over +/// the pixels they made (a layer buffer shared with the RAM cache, a frame moved in) and go on; +/// converting and compressing them is the writer's work. enum Payload { - Encoded(Vec), - /// 8-bit premultiplied RGBA, `width * height * 4` bytes, and the files it was made of. - Frame(u32, u32, Vec, EntryFiles), + /// A layer buffer and its source files. Layer(Arc, EntryFiles), + /// An 8-bit or half-float frame (width, height, pixels) and its source files. + Frame8(u32, u32, Vec, EntryFiles), + FrameF16(u32, u32, Vec, EntryFiles), + /// Decoded footage channels of width x height, each written as an entry of its own (key, + /// name, plane), and their source file. The job owns its planes: what it holds is what it + /// counts, and dropping it frees them. + Planes(u32, u32, Vec<(u128, String, Vec)>, EntryFiles), + /// Bytes to compress with LZ4 (a segmentation). + Lz4(Vec), +} + +#[cfg(test)] +thread_local! { + /// Payloads encoded on this thread (tests: none on a rendering thread). + static ENCODED_HERE: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Payloads encoded on this thread so far (tests). +#[cfg(test)] +pub(crate) fn encoded_here() -> u64 { + ENCODED_HERE.with(std::cell::Cell::get) } impl Payload { - /// Bytes it holds (the frame queue's budget). - #[cfg_attr(target_arch = "wasm32", allow(dead_code))] - fn len(&self) -> usize { + /// Encode it (its source files, then its pixels, compressed) and write it to `cache` as + /// `key` (planes: each under its own key); an entry written meanwhile by another render + /// isn't encoded again. + fn write(self, cache: &DiskCache, kind: Kind, key: u128, format: u8) { + #[cfg(test)] + if !matches!(self, Payload::Lz4(_)) { + ENCODED_HERE.with(|n| n.set(n.get() + 1)); + } + let one = |key: u128, bytes: &dyn Fn() -> Vec| { + if !cache.contains(kind, key) { + cache.write_format(kind, key, format, &bytes()); + } + }; match self { - Payload::Encoded(p) | Payload::Frame(_, _, p, _) => p.len(), - Payload::Layer(b, _) => b.img.data.len().saturating_mul(std::mem::size_of::()), + Payload::Layer(buf, files) => one(key, &|| with_files(&files, encode_layer(&buf))), + Payload::Frame8(w, h, rgba, files) => one(key, &|| with_files(&files, encode_frame(w, h, &rgba))), + Payload::FrameF16(w, h, rgba, files) => one(key, &|| with_files(&files, encode_frame_f16(w, h, &rgba))), + Payload::Planes(w, h, planes, files) => { + for (key, name, plane) in planes { + if cache.contains(kind, key) { + continue; + } + let mut entry = Vec::new(); + files.encode(&mut entry); + // (no memory for the encoder just now: the entry isn't written, and the + // plane is decoded from its file next time) + if let Some(entry) = encode_plane_after(entry, w, h, &name, &plane) { + cache.write_format(kind, key, format, &entry); + } + } + } + Payload::Lz4(raw) => one(key, &|| lz4_flex::compress_prepend_size(&raw)), } } - /// The entry's payload: its source files, then its pixels. - fn encode(self) -> Vec { + /// The bytes it holds while queued. + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + fn held(&self) -> usize { match self { - Payload::Encoded(p) => p, - Payload::Frame(w, h, rgba, files) => with_files(&files, encode_frame(w, h, &rgba)), - Payload::Layer(b, files) => with_files(&files, encode_layer(&b)), + Payload::Layer(buf, _) => buf.img.data.len().saturating_mul(16), + Payload::Frame8(_, _, p, _) => p.len(), + Payload::FrameF16(_, _, p, _) => p.len().saturating_mul(2), + Payload::Planes(_, _, planes, _) => planes.iter().map(|(_, _, p)| p.len().saturating_mul(4)).fold(0, usize::saturating_add), + Payload::Lz4(raw) => raw.len(), + } + } + + /// The bytes only this payload holds: a layer buffer the RAM cache shares counts there. + fn unique(&self) -> usize { + match self { + Payload::Layer(buf, _) if Arc::strong_count(buf) > 1 => 0, + _ => self.held(), + } + } + + /// At least the bytes its largest entry takes uncompressed (the pixels; files and header + /// are small): planes are entries of their own. + fn raw(&self) -> u64 { + match self { + Payload::Planes(_, _, planes, _) => planes.iter().map(|(_, _, p)| p.len().saturating_mul(4)).max().unwrap_or(0) as u64, + _ => self.held() as u64, + } + } + + /// The entries it writes. + fn entries(&self) -> u64 { + match self { + Payload::Planes(_, _, planes, _) => planes.len() as u64, + _ => 1, } } } @@ -308,7 +416,7 @@ struct Queue { frames: std::collections::VecDeque, #[cfg_attr(target_arch = "wasm32", allow(dead_code))] frame_bytes: usize, - /// Layer and matte writes, and their payload bytes. + /// Layer and matte writes, and the bytes they hold. jobs: std::collections::VecDeque, #[cfg_attr(target_arch = "wasm32", allow(dead_code))] job_bytes: usize, @@ -320,6 +428,18 @@ struct Queue { drops: Drops, } +impl Queue { + /// No room for a `kind` write of `len` bytes. A layer bigger than the whole budget is still + /// taken when nothing else is queued. + #[cfg(not(target_arch = "wasm32"))] + fn full(&self, kind: Kind, len: usize) -> bool { + match kind { + Kind::Frame => self.frame_bytes.saturating_add(len) > FRAME_QUEUE_BYTES, + _ => self.jobs.len() >= QUEUE_LIMIT || (self.job_bytes > 0 && self.job_bytes.saturating_add(len) > JOB_QUEUE_BYTES), + } + } +} + /// Files dropped from the cache files beyond this are not remembered one by one: everything made /// before the drop that forgot them is refused instead. const MAX_DROPPED_PATHS: usize = 1 << 16; @@ -362,29 +482,48 @@ impl Queue { fn pop(&mut self) -> Option { if let Some(j) = self.frames.pop_front() { if let Job::Write(_, _, _, p) = &j { - self.frame_bytes = self.frame_bytes.saturating_sub(p.len()); + self.frame_bytes = self.frame_bytes.saturating_sub(p.held()); } return Some(j); } let j = self.jobs.pop_front()?; if let Job::Write(_, _, _, p) = &j { - self.job_bytes = self.job_bytes.saturating_sub(p.len()); + self.job_bytes = self.job_bytes.saturating_sub(p.held()); } Some(j) } - - /// No room for a `kind` write of `len` bytes. A layer bigger than the whole budget is still - /// taken when nothing else is queued. - #[cfg(not(target_arch = "wasm32"))] - fn full(&self, kind: Kind, len: usize) -> bool { - match kind { - Kind::Frame => self.frame_bytes.saturating_add(len) > FRAME_QUEUE_BYTES, - _ => self.jobs.len() >= QUEUE_LIMIT || (self.job_bytes > 0 && self.job_bytes.saturating_add(len) > LAYER_QUEUE_BYTES), - } - } fn is_empty(&self) -> bool { self.frames.is_empty() && self.jobs.is_empty() } + + /// The newest queued layer or plane write holding bytes only the queue holds: its index and + /// those bytes. (Frame writes are never dropped: a fully cached comp would come back with + /// gaps.) + fn newest_unique(&self) -> Option<(usize, usize)> { + self.jobs.iter().enumerate().rev().find_map(|(i, j)| match j { + Job::Write(_, _, _, p) if p.unique() > 0 => Some((i, p.unique())), + _ => None, + }) + } + + /// Drop [`Queue::newest_unique`]; the bytes only it held. + fn drop_newest_unique(&mut self) -> Option { + let (i, unique) = self.newest_unique()?; + if let Some(Job::Write(_, _, _, p)) = self.jobs.remove(i) { + self.job_bytes = self.job_bytes.saturating_sub(p.held()); + } + Some(unique) + } + + /// The bytes only the queued layer and plane writes hold (no frames: see the memory holder). + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + fn unique_job_bytes(&self) -> usize { + let job = |j: &Job| match j { + Job::Write(_, _, _, p) => p.unique(), + Job::Drop(_) => 0, + }; + self.jobs.iter().map(job).fold(0, usize::saturating_add) + } } pub struct DiskCache { @@ -411,9 +550,15 @@ pub struct DiskCache { queue: Arc<(Mutex, Condvar)>, /// Layer buffers that took less than this to render are not written (ms). min_layer_ms: AtomicU64, + /// What reading a megabyte of an entry takes, in microseconds ([`DiskCache::pays_off`]): + /// [`DEFAULT_READ_US_PER_MB`] until reads are measured, then their running average. + read_us_per_mb: AtomicU64, /// Files whose entries are being deleted ([`DiskCache::drop_files`]), each with the number /// of drops of it pending: until then an entry made of one is a miss. dropping: Mutex, u32>>, + /// Bytes [`DiskCache::entry_files`] read (tests). + #[cfg(test)] + head_bytes: AtomicU64, } /// FNV-1a 128-bit (content keys). @@ -562,7 +707,10 @@ impl DiskCache { Condvar::new(), )), min_layer_ms: AtomicU64::new(30), + read_us_per_mb: AtomicU64::new(DEFAULT_READ_US_PER_MB), dropping: Mutex::new(HashMap::new()), + #[cfg(test)] + head_bytes: AtomicU64::new(0), }); dc.rescan(); // Shrinking a large cache deletes many files: the writer thread does it. @@ -584,7 +732,7 @@ impl DiskCache { /// 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, Kind::Matte] { + for kind in [Kind::Frame, Kind::Layer, Kind::Matte, Kind::Plane] { 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 }; @@ -682,8 +830,8 @@ impl DiskCache { } /// Count one entry compressed for a queued write. - fn count_encode(&self) { - self.encodes.fetch_add(1, Ordering::Relaxed); + fn count_encodes(&self, n: u64) { + self.encodes.fetch_add(n, Ordering::Relaxed); } /// Layer buffers faster to render than this are not worth a disk write. @@ -695,6 +843,38 @@ impl DiskCache { self.min_layer_ms.load(Ordering::Relaxed) } + /// What reading `bytes` of an entry back is expected to take, in microseconds (the measured + /// read rate, [`DiskCache::note_read`]). + pub fn read_us(&self, bytes: usize) -> u64 { + let rate = u128::from(self.read_us_per_mb.load(Ordering::Relaxed)); + u64::try_from(u128::try_from(bytes).unwrap_or(u128::MAX).saturating_mul(rate) >> 20).unwrap_or(u64::MAX) + } + + /// Set the read rate assumed until reads are measured (microseconds per MB; tests that need + /// every write give 0: everything pays off). + pub fn set_read_us_per_mb(&self, us: u64) { + self.read_us_per_mb.store(us, Ordering::Relaxed); + } + + /// Whether a frame or plane set of `bytes` that took `make_us` microseconds to make is worth + /// a disk write: only when making it again costs more than reading it back (#3301). A RAM + /// eviction keeps the disk copy either way. + pub fn pays_off(&self, bytes: usize, make_us: u64) -> bool { + let read = self.read_us(bytes); + read == 0 || make_us > read + } + + /// Note a read of `bytes` that took `took_us` (reads of under 64 KB are too short to time): + /// the read rate becomes a running average (7/8 the old rate, 1/8 this read's). + fn note_read(&self, bytes: usize, took_us: u64) { + if bytes < 64 << 10 { + return; + } + let rate = u64::try_from(u128::from(took_us).saturating_mul(1 << 20) / u128::try_from(bytes).unwrap_or(1).max(1)).unwrap_or(u64::MAX); + let old = self.read_us_per_mb.load(Ordering::Relaxed); + self.read_us_per_mb.store(old.saturating_mul(7).saturating_add(rate) / 8, Ordering::Relaxed); + } + pub fn contains(&self, kind: Kind, key: u128) -> bool { self.index.lock().is_ok_and(|g| g.contains(kind, key)) } @@ -731,7 +911,7 @@ impl DiskCache { if let Ok(mut g) = self.index.lock() { g.clear(); } - for kind in [Kind::Frame, Kind::Layer, Kind::Matte] { + for kind in [Kind::Frame, Kind::Layer, Kind::Matte, Kind::Plane] { let _ = std::fs::remove_dir_all(self.dir.join(kind.dir())); } } @@ -776,8 +956,12 @@ impl DiskCache { return None; } let path = self.path(kind, key); + let t0 = web_time::Instant::now(); let data = std::fs::read(&path).ok(); let ok = data.as_deref().and_then(|d| Some((*d.get(5)?, verify(d, kind)?.to_vec()))); + if let Some((_, payload)) = &ok { + self.note_read(payload.len(), u64::try_from(t0.elapsed().as_micros()).unwrap_or(u64::MAX)); + } if ok.is_none() { // Gone (another process evicted it) or damaged: forget it. if data.is_some() { @@ -863,22 +1047,24 @@ impl DiskCache { } } - /// Queue a write; `false` when it was dropped (a full queue). - fn enqueue(&self, kind: Kind, key: u128, payload: Vec) -> bool { - self.enqueue_format(kind, key, FORMAT_RGBA8, Payload::Encoded(payload), None) - } - /// [`DiskCache::enqueue`] with the entry's header format byte. `made`: the source files of a /// frame or layer entry and the drop generation its reads started at /// ([`DiskCache::drop_generation`]); refused (`false`) when one of them was dropped since. fn enqueue_format(&self, kind: Kind, key: u128, format: u8, payload: Payload, made: Option<(&EntryFiles, u64)>) -> bool { let stale = |q: &Queue| made.is_some_and(|(files, since)| q.drops.stale(files.files().iter().map(|f| &f.path), since)); + // An entry larger uncompressed than the cache may hold isn't worth encoding (#3271). + if payload.raw() > self.limit_bytes() { + return false; + } #[cfg(target_arch = "wasm32")] { if self.queue.0.lock().is_ok_and(|q| stale(&q)) { return false; } - self.write_format(kind, key, format, &payload.encode()); + if !matches!(payload, Payload::Lz4(_)) { + self.count_encodes(payload.entries()); + } + payload.write(self, kind, key, format); true } #[cfg(not(target_arch = "wasm32"))] @@ -888,16 +1074,20 @@ impl DiskCache { if stale(&q) { return false; } - if q.full(kind, payload.len()) { + if q.full(kind, payload.held()) { self.dropped.fetch_add(1, Ordering::Relaxed); return false; } + // (counted as it is accepted: the writer compresses it) + if !matches!(payload, Payload::Lz4(_)) { + self.count_encodes(payload.entries()); + } if kind == Kind::Frame { q.pending_frames.insert(key); - q.frame_bytes = q.frame_bytes.saturating_add(payload.len()); + q.frame_bytes = q.frame_bytes.saturating_add(payload.held()); q.frames.push_back(Job::Write(kind, key, format, payload)); } else { - q.job_bytes = q.job_bytes.saturating_add(payload.len()); + q.job_bytes = q.job_bytes.saturating_add(payload.held()); q.jobs.push_back(Job::Write(kind, key, format, payload)); } cv.notify_all(); @@ -916,11 +1106,13 @@ impl DiskCache { self.write_failed(&e); return; } - let data = seal_format(kind, format, payload); - // An entry that cannot fit would be evicted straight away. - if data.len() as u64 > self.limit_bytes() { + // An entry that cannot fit would be evicted straight away (asked before it is sealed). + if payload.len().saturating_add(16) as u64 > self.limit_bytes() { return; } + // (no memory for the sealed entry just now: it isn't written; a plane is decoded from its + // file next time) + let Some(data) = try_seal_format(kind, format, payload) else { return }; // Make room first, so the cache never exceeds its limit (or the free-space reserve). self.evict_to(self.limit_bytes().saturating_sub(data.len() as u64)); let n = self.tmp_counter.fetch_add(1, Ordering::Relaxed); @@ -1043,7 +1235,7 @@ impl DiskCache { /// end their drop. fn sweep(&self, paths: &[Arc]) { let set: std::collections::HashSet<&str> = paths.iter().map(|p| &**p).collect(); - for kind in [Kind::Frame, Kind::Layer] { + for kind in [Kind::Frame, Kind::Layer, Kind::Plane] { for key in self.keys(kind) { if self.entry_files(kind, key).is_some_and(|f| f.files().iter().any(|f| set.contains(&*f.path))) { self.discard(kind, key); @@ -1066,19 +1258,23 @@ impl DiskCache { /// earlier format, gone, damaged): such an entry is never used anyway. fn entry_files(&self, kind: Kind, key: u128) -> Option { use std::io::Read; - const HEAD: u64 = 64 << 10; + // (a plane entry lists its one source file: a short read holds it; there are many of + // them, one per channel and frame, and Reload Footage reads each one's head) + let head_len: u64 = if kind == Kind::Plane { 4 << 10 } else { 64 << 10 }; let parse = |d: &[u8]| { let format = *d.get(5)?; let ours = d.get(..4)? == MAGIC && *d.get(4)? == kind.tag(); - if !ours || !matches!(format, FORMAT_RGBA8_FILES | FORMAT_F16_FILES | FORMAT_LAYER_FILES) { + if !ours || !matches!(format, FORMAT_RGBA8_FILES | FORMAT_F16_FILES | FORMAT_LAYER_FILES | FORMAT_PLANES_FILES) { return None; } EntryFiles::decode(d.get(8..)?).map(|(files, _)| files) }; let path = self.path(kind, key); let mut head = Vec::new(); - std::fs::File::open(&path).ok()?.take(HEAD).read_to_end(&mut head).ok()?; - parse(&head).or_else(|| if head.len() as u64 == HEAD { parse(&std::fs::read(&path).ok()?) } else { None }) + std::fs::File::open(&path).ok()?.take(head_len).read_to_end(&mut head).ok()?; + #[cfg(test)] + self.head_bytes.fetch_add(head.len() as u64, Ordering::Relaxed); + parse(&head).or_else(|| if head.len() as u64 == head_len { parse(&std::fs::read(&path).ok()?) } else { None }) } // ------------------------------------------------------------ typed entries @@ -1118,13 +1314,12 @@ impl DiskCache { if self.contains(Kind::Frame, key) { return true; } - // (no room on the disk: refused before the pixels are compressed) + // (no room on the disk: refused before the pixels are copied) if !self.accepts_writes() { return false; } - self.count_encode(); - let payload = with_files(&files, encode_frame_f16(width, height, rgba)); - self.enqueue_format(Kind::Frame, key, FORMAT_F16_FILES, Payload::Encoded(payload), Some((&files, since))) + let payload = Payload::FrameF16(width, height, rgba.to_vec(), files.clone()); + self.enqueue_format(Kind::Frame, key, FORMAT_F16_FILES, payload, Some((&files, since))) } /// Write a half-float frame synchronously (tests); a list that can't be stored is not. @@ -1141,11 +1336,15 @@ impl DiskCache { /// render started at). #[allow(clippy::too_many_arguments)] pub fn put_frame(&self, key: u128, width: u32, height: u32, rgba: &[u8], files: &ReadFiles, virtual_id: Option>, since: u64) -> bool { + // (refused before the pixels are copied) + if rgba.len() as u64 != width as u64 * height as u64 * 4 || self.contains(Kind::Frame, key) || !self.accepts_writes() { + return self.contains(Kind::Frame, key); + } self.put_frame_owned(key, width, height, rgba.to_vec(), files, virtual_id, since) } - /// [`DiskCache::put_frame`] of a frame the caller hands over (no copy; compressed on the - /// writer thread). + /// [`DiskCache::put_frame`] taking the pixels: they move to the writer thread, which converts + /// and compresses them (#3271); the caller goes on at once. #[allow(clippy::too_many_arguments)] pub fn put_frame_owned( &self, @@ -1168,9 +1367,8 @@ impl DiskCache { if !self.accepts_writes() { return false; } - self.count_encode(); - let made = files.clone(); - self.enqueue_format(Kind::Frame, key, FORMAT_RGBA8_FILES, Payload::Frame(width, height, rgba, files), Some((&made, since))) + let payload = Payload::Frame8(width, height, rgba, files.clone()); + self.enqueue_format(Kind::Frame, key, FORMAT_RGBA8_FILES, payload, Some((&files, since))) } /// A layer buffer (key: [`layer_disk_key`]) whose source files are unchanged, with those @@ -1192,7 +1390,6 @@ impl DiskCache { if !layer_fits(buf.img.data.len()) || self.contains(Kind::Layer, key) || !self.accepts_writes() { return; } - self.count_encode(); let _ = self.enqueue_format(Kind::Layer, key, FORMAT_LAYER_FILES, Payload::Layer(buf.clone(), files.clone()), Some((files, since))); } @@ -1206,6 +1403,56 @@ impl DiskCache { } } + /// A decoded footage channel ([`plane_key`]) whose source file is unchanged, as + /// [`DiskCache::get_checked`] (#3271): its name and its `width` x `height` plane. An entry + /// of another size is a miss (nothing larger is decompressed). + pub fn get_plane(&self, key: u128, width: u32, height: u32) -> Option<(String, Vec)> { + self.get_checked(Kind::Plane, key, FORMAT_PLANES_FILES, None, |p| decode_plane(p, (width, height))).map(|(plane, _)| plane) + } + + /// The most plane bytes one queued write of decoded footage channels holds: a caller copying + /// planes for [`DiskCache::put_planes`] copies this much at a time. + pub fn plane_job_bytes(&self) -> usize { + PLANE_JOB_BYTES + } + + /// Queue decoded footage channels of `width` x `height` (each [`plane_key`], name and plane) + /// for writing, with the source file they were read from; encoded on the writer thread. + /// Planes stored already, of another size or larger than the cache may hold are left out; + /// the rest go in jobs of at most [`PLANE_JOB_BYTES`] each, so a set the queue can't take + /// whole still gets as many as fit. `false` when some were refused (no room, a full queue, + /// or the source file dropped after `since`). + pub fn put_planes(&self, width: u32, height: u32, planes: Vec<(u128, String, Vec)>, files: &EntryFiles, since: u64) -> bool { + let n = (width as usize).checked_mul(height as usize); + let most = self.limit_bytes(); + let planes: Vec<(u128, String, Vec)> = planes + .into_iter() + .filter(|(key, _, p)| Some(p.len()) == n && (p.len() as u64).saturating_mul(4) <= most && !self.contains(Kind::Plane, *key)) + .collect(); + if planes.is_empty() { + return true; + } + if !self.accepts_writes() { + return false; + } + let mut all = true; + let mut job: Vec<(u128, String, Vec)> = vec![]; + let mut bytes = 0usize; + let mut rest = planes.into_iter().peekable(); + while let Some(plane) = rest.next() { + bytes = bytes.saturating_add(plane.2.len().saturating_mul(4)); + job.push(plane); + let next = rest.peek().map_or(0, |p| p.2.len().saturating_mul(4)); + if rest.peek().is_none() || bytes.saturating_add(next) > PLANE_JOB_BYTES { + let first = job.first().map_or(0, |p| p.0); + let payload = Payload::Planes(width, height, std::mem::take(&mut job), files.clone()); + all &= self.enqueue_format(Kind::Plane, first, FORMAT_PLANES_FILES, payload, Some((files, since))); + bytes = 0; + } + } + all + } + /// A segmentation (chain key, scale) written by [`DiskCache::put_seg`]. pub fn get_seg(&self, key: u64, scale: f64) -> Option { let p = self.read(Kind::Matte, seg_key(key, scale))?; @@ -1223,7 +1470,8 @@ impl DiskCache { if self.contains(Kind::Matte, k) { return; } - let _ = self.enqueue(Kind::Matte, k, lz4_flex::compress_prepend_size(&seg.to_bytes())); + // (compressed on the writer thread) + let _ = self.enqueue_format(Kind::Matte, k, FORMAT_RGBA8, Payload::Lz4(seg.to_bytes()), None); } /// Make the frame at key `from` the frame at key `to` too (an edit that can't change it gave @@ -1308,7 +1556,7 @@ fn writer(dc: std::sync::Weak, q: Arc<(Mutex, Condvar)>) { let Some(cache) = dc.upgrade() else { return }; let written = match job { Job::Write(kind, key, format, payload) => { - cache.write_format(kind, key, format, &payload.encode()); + payload.write(&cache, kind, key, format); (kind == Kind::Frame).then_some(key) } Job::Drop(paths) => { @@ -1332,13 +1580,32 @@ fn writer(dc: std::sync::Weak, q: Arc<(Mutex, Condvar)>) { /// [`FORMAT_LAYER_FILES`] for layer buffers), payload, checksum. fn seal_format(kind: Kind, format: u8, payload: &[u8]) -> Vec { let mut data = Vec::with_capacity(payload.len() + 16); + seal_into(&mut data, kind, format, payload); + data +} + +/// [`seal_format`] with its memory taken fallibly: `None` when the system can't give it (a +/// poorly compressible 16K plane's entry is about 1 GiB), and the entry is then not written. +fn try_seal_format(kind: Kind, format: u8, payload: &[u8]) -> Option> { + let len = payload.len().checked_add(16)?; + #[cfg(test)] + if len > NO_SEAL_OVER.with(std::cell::Cell::get) { + return None; + } + let mut data = Vec::new(); + data.try_reserve_exact(len).ok()?; + seal_into(&mut data, kind, format, payload); + Some(data) +} + +/// The header, `payload` and checksum of an entry appended to `data` (room for them reserved). +fn seal_into(data: &mut Vec, kind: Kind, format: u8, payload: &[u8]) { data.extend_from_slice(MAGIC); data.push(kind.tag()); data.extend_from_slice(&[format, 0, 0]); data.extend_from_slice(payload); - let sum = checksum(&data); + let sum = checksum(data.as_slice()); data.extend_from_slice(&sum.to_le_bytes()); - data } /// A sealed 8-bit frame entry with the source files it was made of: what the browser's frame @@ -1402,12 +1669,42 @@ impl effectcraft_effects::roto::SegStore for DiskCache { } } +/// The disk cache's write queue in the common memory budget (#3271, #3298): queued entries hold +/// their pixels until the writer has written them. They are copies (a dropped write only costs +/// a later render a disk miss), worth nothing to the accountant: the first freed. +impl crate::memory::MemoryHolder for DiskCache { + fn name(&self) -> &'static str { + "disk write queue" + } + /// The bytes only the queue holds (a layer buffer the RAM cache still holds counts there). + fn bytes(&self) -> usize { + self.queue.0.lock().map(|q| q.unique_job_bytes()).unwrap_or(0) + } + /// The newest queued write holding bytes only the queue holds (newest first: the oldest is + /// the next to be written); a copy, so it costs nothing. + fn oldest(&self) -> Option { + let q = self.queue.0.lock().ok()?; + let (_, bytes) = q.newest_unique()?; + Some(crate::memory::Candidate { used: 0, bytes, cost_us: 0, protected: false }) + } + fn drop_oldest(&self) -> usize { + let Ok(mut q) = self.queue.0.lock() else { return 0 }; + match q.drop_newest_unique() { + Some(bytes) => { + self.dropped.fetch_add(1, Ordering::Relaxed); + bytes + } + None => 0, + } + } +} + impl crate::cache::LayerStore for DiskCache { /// The layer for `key` from the disk cache, or `None` when it is missing or stale. fn get_layer(&self, key: u128, virtual_id: Option>) -> Option<(Arc, ReadFiles)> { DiskCache::get_layer(self, key, virtual_id).map(|(b, f)| (Arc::new(b), f)) } - /// Queues a layer write on the disk cache. + /// Queues a layer write on the disk cache (encoded on its writer thread). fn put_layer(&self, key: u128, buf: &Arc, files: &EntryFiles, since: u64) { DiskCache::put_layer(self, key, buf, files, since); } @@ -1466,7 +1763,23 @@ fn decompress_checked(p: &[u8], expected: Option) -> Option> { return None; } // A block that ends short of the size it states is damaged: callers index by that size. - lz4_flex::decompress(p.get(4..)?, size).ok().filter(|raw| raw.len() == size) + // (memory the system can't give is a miss, not an abort) + let mut raw = zeroed(size, 0u8)?; + let got = lz4_flex::block::decompress_into(p.get(4..)?, &mut raw).ok()?; + (got == size).then_some(raw) +} + +/// `n` copies of `v`, or `None` when the system can't give the memory: a cache entry read back +/// then counts as a miss. +fn zeroed(n: usize, v: T) -> Option> { + #[cfg(test)] + if n.saturating_mul(std::mem::size_of::()) > NO_MEMORY_OVER.with(std::cell::Cell::get) { + return None; + } + let mut out = Vec::new(); + out.try_reserve_exact(n).ok()?; + out.resize(n, v); + Some(out) } fn decode_frame(p: &[u8]) -> Option { @@ -1513,7 +1826,7 @@ fn decode_frame_f16(p: &[u8]) -> Option { let h = u32::from_le_bytes(p[4..8].try_into().ok()?); let n = (w as usize).checked_mul(h as usize)?; let planes = decompress_checked(&p[8..], Some(n.checked_mul(8)?))?; - let mut rgba = vec![0u16; n * 4]; + let mut rgba = zeroed(n.checked_mul(4)?, 0u16)?; for (i, px) in rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() { for (c, v) in px.iter_mut().enumerate() { *v = u16::from_le_bytes([planes[c * n + i], planes[(4 + c) * n + i]]); @@ -1522,6 +1835,117 @@ fn decode_frame_f16(p: &[u8]) -> Option { Some(FrameF16 { width: w, height: h, rgba }) } +/// [`encode_plane_after`] alone (tests). +#[cfg(test)] +fn encode_plane(w: u32, h: u32, name: &str, plane: &[f32]) -> Vec { + encode_plane_after(Vec::new(), w, h, name, plane).unwrap_or_default() +} + +/// A plane entry's pixels (`plane`, named `name`, of `w` x `h`) appended to `out` (the entry's +/// source files): width, height, the name (length and UTF-8 bytes) and the sample type, then the +/// samples' bytes shuffled into byte planes (the first bytes of all samples, then the +/// second...), LZ4-compressed. Type 1: half floats, when every value is one exactly (a half +/// channel: half the bytes); type 2: `f32` (bit-exact: Cryptomatte IDs are float bit patterns). +/// The scratch memory and the result are taken fallibly: `None` when the system can't give them. +fn encode_plane_after(mut out: Vec, w: u32, h: u32, name: &str, plane: &[f32]) -> Option> { + let name = name.as_bytes(); + let len = name.len().min(u16::MAX as usize); + // (the size, the name and the sample type) + out.try_reserve(len.checked_add(64)?).ok()?; + out.extend_from_slice(&w.to_le_bytes()); + out.extend_from_slice(&h.to_le_bytes()); + out.extend_from_slice(&(len as u16).to_le_bytes()); + out.extend_from_slice(name.get(..len).unwrap_or_default()); + let n = plane.len(); + let mut halves = zeroed(n, half::f16::ZERO)?; + half::slice::HalfFloatSliceExt::convert_from_f32_slice(halves.as_mut_slice(), plane); + // (NaNs stay `f32`: their payloads must come back as they were) + let exact = halves.iter().zip(plane).all(|(h, v)| !v.is_nan() && h.to_f32().to_bits() == v.to_bits()); + // Shuffled straight from the samples' bits into byte planes. + let shuffled = if exact { + out.push(1); + let mut s = zeroed(n.checked_mul(2)?, 0u8)?; + let (lo, hi) = s.split_at_mut(n); + for ((l, hb), x) in lo.iter_mut().zip(hi.iter_mut()).zip(&halves) { + [*l, *hb] = x.to_bits().to_le_bytes(); + } + s + } else { + drop(halves); + out.push(2); + let mut s = zeroed(n.checked_mul(4)?, 0u8)?; + let (b0, rest) = s.split_at_mut(n); + let (b1, rest) = rest.split_at_mut(n); + let (b2, b3) = rest.split_at_mut(n); + for ((((a, b), c), d), v) in b0.iter_mut().zip(b1.iter_mut()).zip(b2.iter_mut()).zip(b3.iter_mut()).zip(plane) { + [*a, *b, *c, *d] = v.to_bits().to_le_bytes(); + } + s + }; + // (as `lz4_flex::compress_prepend_size`: the size, then the block) + let most = lz4_flex::block::get_maximum_output_size(shuffled.len()); + out.try_reserve_exact(most.checked_add(4)?).ok()?; + out.extend_from_slice(&u32::try_from(shuffled.len()).ok()?.to_le_bytes()); + let at = out.len(); + out.resize(at.checked_add(most)?, 0); + let len = lz4_flex::block::compress_into(&shuffled, out.get_mut(at..)?).ok()?; + out.truncate(at.saturating_add(len)); + Some(out) +} + +#[cfg(test)] +thread_local! { + /// Allocations [`zeroed`] refuses on this thread: those over this many bytes (tests: memory + /// the system can't give). + static NO_MEMORY_OVER: std::cell::Cell = const { std::cell::Cell::new(usize::MAX) }; + /// Sealed entries [`try_seal_format`] can't get memory for on this thread: those over this + /// many bytes (tests). + static NO_SEAL_OVER: std::cell::Cell = const { std::cell::Cell::new(usize::MAX) }; +} + +/// The name and plane of a plane entry's pixels ([`encode_plane_after`]) of `expect` (width, height); +/// `None` when damaged or of another size. +fn decode_plane(p: &[u8], expect: (u32, u32)) -> Option<(String, Vec)> { + let u32_at = |at: usize| Some(u32::from_le_bytes(p.get(at..at + 4)?.try_into().ok()?)); + let (w, h) = (u32_at(0)?, u32_at(4)?); + if (w, h) != expect { + return None; + } + let n = (w as usize).checked_mul(h as usize).filter(|n| *n <= MAX_ENTRY_PIXELS)?; + let len = u16::from_le_bytes(p.get(8..10)?.try_into().ok()?) as usize; + let name = std::str::from_utf8(p.get(10..10 + len)?).ok()?.to_string(); + let width = match *p.get(10 + len)? { + 1 => 2, + 2 => 4, + _ => return None, + }; + let body = p.get(11 + len..)?; + // (the size the compressed block says must be the plane's: nothing larger is allocated) + let want = n.checked_mul(width)?; + if u32::from_le_bytes(body.get(..4)?.try_into().ok()?) as usize != want { + return None; + } + // (every buffer taken fallibly: a plane the system can't give memory for is a miss) + let s = decompress_checked(body, Some(want))?; + let mut plane = zeroed(n, 0.0f32)?; + if width == 2 { + let (lo, hi) = s.split_at_checked(n)?; + let mut halves = zeroed(n, half::f16::ZERO)?; + for ((x, l), h) in halves.iter_mut().zip(lo).zip(hi) { + *x = half::f16::from_bits(u16::from_le_bytes([*l, *h])); + } + half::slice::HalfFloatSliceExt::convert_to_f32_slice(halves.as_slice(), &mut plane); + } else { + let (b0, rest) = s.split_at_checked(n)?; + let (b1, rest) = rest.split_at_checked(n)?; + let (b2, b3) = rest.split_at_checked(n)?; + for (o, (((a, b), c), d)) in plane.iter_mut().zip(b0.iter().zip(b1).zip(b2).zip(b3)) { + *o = f32::from_bits(u32::from_le_bytes([*a, *b, *c, *d])); + } + } + Some((name, plane)) +} + fn encode_layer(b: &Buf) -> Vec { let (w, h) = (b.img.width, b.img.height); let n = b.img.data.len(); @@ -1688,6 +2112,15 @@ pub fn frame_key(content: u128, frame: i64, scale_milli: u32, view: u64) -> u128 mod tests { use super::*; + /// #3301 review: buffers for entries read back are taken fallibly; memory the system can't + /// give is a miss, not an abort. + #[test] + fn memory_that_cannot_be_had_is_a_miss() { + assert!(zeroed(usize::MAX, 0u8).is_none()); + assert!(zeroed(usize::MAX / 2, 0.0f32).is_none()); + assert_eq!(zeroed(3, 7u16), Some(vec![7; 3])); + } + #[cfg(unix)] #[test] fn a_cache_folder_in_the_temp_folder_is_made_private_and_never_a_link() { @@ -1911,6 +2344,227 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// #3271: frame and layer entries are handed to the writer thread and converted and + /// compressed there, not on the thread that rendered them; one larger uncompressed than the + /// cache may hold is refused before anything is queued. + #[test] + fn entries_are_encoded_on_the_writer_thread() { + let dir = tmpdir("writer-encodes"); + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + let before = encoded_here(); + dc.put_layer(1, &Arc::new(buf(1, 32, 32)), &EntryFiles::default(), 0); + assert!(dc.put_frame_owned(2, 8, 8, vec![3; 8 * 8 * 4], &ReadFiles::default(), None, 0)); + assert!(dc.put_frame_f16(3, 8, 8, &[0x3c00; 8 * 8 * 4], &ReadFiles::default(), None, 0)); + assert_eq!(encoded_here(), before, "nothing encoded on the rendering thread"); + dc.flush(); + assert_eq!(dc.get_layer(1, None).map(|(b, _)| b.img), Some(buf(1, 32, 32).img)); + assert_eq!(dc.get_frame(2, None).map(|(f, _)| f.rgba), Some(vec![3; 8 * 8 * 4])); + assert!(dc.get_frame_f16(3, None).is_some()); + let encodes = dc.encodes(); + dc.set_max_bytes(1000); + dc.put_layer(4, &Arc::new(buf(1, 64, 64)), &EntryFiles::default(), 0); + dc.flush(); + assert_eq!(dc.encodes(), encodes, "too large uncompressed: not queued"); + assert!(!dc.contains(Kind::Layer, 4)); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A source file for plane entries (it must exist: hits check it is unchanged). + fn plane_source(dir: &Path) -> (EntryFiles, crate::reads::FileStamp) { + std::fs::create_dir_all(dir).unwrap(); + let src = dir.join("plate.exr"); + std::fs::write(&src, b"exr").unwrap(); + let stamp = crate::reads::FileStamp::of_metadata(&std::fs::metadata(&src).unwrap()); + let mut files = ReadFiles::default(); + files.add(crate::reads::ReadFile::new(src.to_string_lossy().to_string(), stamp)); + (EntryFiles::of(&files, None).unwrap(), stamp) + } + + /// #3271: a plane entry gives back every value bit for bit. A plane of half values is stored + /// as half floats (half the bytes), any other (Cryptomatte IDs, NaN payloads, values a half + /// can't hold) as `f32`; -0.0 and denormals come back as they were. An entry of another size, + /// a damaged one and one of the earlier format read as misses. + #[test] + fn plane_entries_round_trip_bit_for_bit() { + let dir = tmpdir("planes"); + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + let (files, _) = plane_source(&dir.join("src")); + let (w, h) = (16u32, 8u32); + let n = (w * h) as usize; + let halves: Vec = (0..n).map(|i| half::f16::from_bits((i * 517) as u16 & 0x7bff).to_f32()).collect(); + let mut mixed: Vec = (0..n).map(|i| f32::from_bits(0x3f80_0001 + i as u32 * 7919)).collect(); + mixed[0] = f32::from_bits(0x7fc0_1234); + mixed[1] = -0.0; + mixed[2] = f32::from_bits(1); + let mut nan_half = halves.clone(); + nan_half[3] = f32::from_bits(0x7fc0_0000 | 0x2000); + let set = vec![(1, "A.R".to_string(), halves.clone()), (2, "A.id".to_string(), mixed.clone()), (3, "A.nan".to_string(), nan_half.clone())]; + for ((_, name, plane), want) in set.iter().zip([1u8, 2, 2]) { + let p = encode_plane(w, h, name, plane); + let len = p[8] as usize; + assert_eq!(p[10 + len], want, "{name}: sample type"); + } + assert!(dc.put_planes(w, h, set, &files, 0)); + dc.flush(); + for (key, name, want) in [(1, "A.R", &halves), (2, "A.id", &mixed), (3, "A.nan", &nan_half)] { + let (got_name, got) = dc.get_plane(key, w, h).unwrap(); + assert_eq!(got_name, name); + assert_eq!(got.iter().map(|v| v.to_bits()).collect::>(), want.iter().map(|v| v.to_bits()).collect::>(), "{name}"); + } + assert!(dc.get_plane(1, w, h + 1).is_none(), "another size: a miss"); + let entry = encode_plane(w, h, "A.id", &mixed); + assert!(decode_plane(entry.get(..entry.len() - 9).unwrap(), (w, h)).is_none(), "short"); + let mut damaged = entry.clone(); + let len = damaged[8] as usize; + damaged[10 + len] = 3; + assert!(decode_plane(&damaged, (w, h)).is_none(), "unknown sample type"); + // An entry of the earlier format (5) is a miss, and deleted. + dc.write_format(Kind::Plane, 9, 5, &with_files(&files, encode_plane(w, h, "A.R", &halves))); + assert!(dc.contains(Kind::Plane, 9)); + assert!(dc.get_plane(9, w, h).is_none()); + assert!(!dc.contains(Kind::Plane, 9), "deleted"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// #3750 review: a plane write whose encoder can't get its scratch memory (the half or + /// shuffled buffer of a 16K plane) writes no entry and goes on, instead of aborting; with the + /// memory it is written. + #[test] + fn a_plane_write_without_memory_for_its_encoder_is_skipped() { + let dir = tmpdir("planes-no-memory"); + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + let (files, _) = plane_source(&dir.join("src")); + let job = |key: u128| Payload::Planes(16, 8, vec![(key, "A.R".to_string(), vec![0.5f32; 128])], files.clone()); + // (this thread's allocations through the encoder's scratch over 64 bytes are refused) + NO_MEMORY_OVER.with(|c| c.set(64)); + job(1).write(&dc, Kind::Plane, 1, FORMAT_PLANES_FILES); + NO_MEMORY_OVER.with(|c| c.set(usize::MAX)); + assert!(!dc.contains(Kind::Plane, 1), "no entry without the encoder's memory"); + job(2).write(&dc, Kind::Plane, 2, FORMAT_PLANES_FILES); + assert!(dc.get_plane(2, 16, 8).is_some(), "written with it"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// #3750 review: a plane entry that can't get the memory to be sealed (a poorly compressible + /// 16K plane's is about 1 GiB) is not written, and the planes after it are; a sealed entry + /// is the same bytes either way. + #[test] + fn a_plane_entry_without_memory_to_seal_is_skipped_and_the_rest_written() { + let dir = tmpdir("planes-no-seal"); + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + let (files, _) = plane_source(&dir.join("src")); + // (noise compresses poorly: its entry is over 2 KiB; the flat plane's is far under) + let noise: Vec = (0..1024u32).map(|i| f32::from_bits(0x3f00_0000 | i.wrapping_mul(2_654_435_761) >> 9)).collect(); + let flat = vec![0.5f32; 1024]; + let job = Payload::Planes(32, 32, vec![(1, "A.id".to_string(), noise.clone()), (2, "A.R".to_string(), flat)], files.clone()); + NO_SEAL_OVER.with(|c| c.set(2048)); + job.write(&dc, Kind::Plane, 0, FORMAT_PLANES_FILES); + NO_SEAL_OVER.with(|c| c.set(usize::MAX)); + assert!(!dc.contains(Kind::Plane, 1), "no memory to seal it: not written"); + assert!(dc.get_plane(2, 32, 32).is_some(), "the next plane is written"); + let mut entry = Vec::new(); + files.encode(&mut entry); + let entry = encode_plane_after(entry, 32, 32, "A.id", &noise).unwrap(); + assert!(entry.len() > 2048); + assert_eq!(try_seal_format(Kind::Plane, FORMAT_PLANES_FILES, &entry), Some(seal_format(Kind::Plane, FORMAT_PLANES_FILES, &entry)), "the same bytes"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// #3271: a queued plane write owns its planes, counts them for the memory accountant (all + /// of them, not a share of the store's set) and frees them when the accountant drops it; + /// frames stay. 69 channels are queued without loss, each written as an entry of its own + /// and counted as one encode. + #[test] + fn queued_planes_count_what_they_hold_and_are_written_each() { + let dir = tmpdir("planes-job"); + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + let (files, _) = plane_source(&dir.join("src")); + let planes = || -> Vec<(u128, String, Vec)> { (0..69).map(|i| (100 + i as u128, format!("c{i:02}"), vec![i as f32; 8])).collect() }; + { + let mut q = dc.queue.0.lock().unwrap(); + let job = Payload::Planes(4, 2, planes(), files.clone()); + assert_eq!((job.held(), job.unique(), job.raw(), job.entries()), (69 * 8 * 4, 69 * 8 * 4, 32, 69)); + q.jobs.push_back(Job::Write(Kind::Plane, 1, FORMAT_PLANES_FILES, job)); + q.frames.push_back(Job::Write(Kind::Frame, 2, FORMAT_RGBA8_FILES, Payload::Frame8(1, 1, vec![0; 4], files.clone()))); + assert_eq!(q.unique_job_bytes(), 69 * 8 * 4, "what the memory holder reports"); + assert_eq!(q.drop_newest_unique(), Some(69 * 8 * 4), "dropped as reported"); + assert_eq!(q.drop_newest_unique(), None, "frame writes are never dropped"); + assert!(q.jobs.is_empty() && q.frames.len() == 1); + q.frames.clear(); + } + let encodes = dc.encodes(); + assert!(dc.put_planes(4, 2, planes(), &files, 0)); + dc.flush(); + assert_eq!(dc.keys(Kind::Plane).len(), 69); + assert_eq!(dc.encodes() - encodes, 69, "one encode per entry"); + assert_eq!(dc.stats().dropped, 0); + assert_eq!(crate::memory::MemoryHolder::bytes(&*dc), 0, "written: the queue holds nothing"); + assert_eq!(dc.get_plane(168, 4, 2).map(|(n, p)| (n, p[0])), Some(("c68".to_string(), 68.0))); + let _ = std::fs::remove_dir_all(&dir); + } + + /// #3271 review: Reload Footage looks at each plane entry's head for its source file; a plane + /// entry lists one, so only a short head is read (a sequence of many channels has a great + /// many plane entries), and the entry is still found and deleted. + #[test] + fn reload_reads_only_a_short_head_of_plane_entries() { + let dir = tmpdir("planes-sweep"); + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + let (files, _) = plane_source(&dir.join("src")); + // A plane that doesn't compress: its entry is far larger than any head read. + let (w, h) = (256u32, 256u32); + let mut x = 0x1234_5678u32; + let plane: Vec = (0..w * h) + .map(|_| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + f32::from_bits(0x3f00_0000 | (x >> 9)) + }) + .collect(); + assert!(dc.put_planes(w, h, vec![(400, "noise".into(), plane)], &files, 0)); + dc.flush(); + assert_eq!(dc.keys(Kind::Plane), [400]); + assert!(std::fs::metadata(dc.path(Kind::Plane, 400)).unwrap().len() > 64 << 10); + let before = dc.head_bytes.load(Ordering::Relaxed); + dc.drop_files([dir.join("src").join("plate.exr").to_string_lossy().to_string()]); + dc.flush(); + let until = std::time::Instant::now() + std::time::Duration::from_secs(10); + while dc.is_dropping() && std::time::Instant::now() < until { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(dc.keys(Kind::Plane).is_empty(), "the plane entry of the reloaded file is deleted"); + let read = dc.head_bytes.load(Ordering::Relaxed) - before; + assert!(read > 0 && read <= 4 << 10, "{read} bytes read"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// #3271 review: a set of planes larger together than the cache may hold, or than one queued + /// write takes ([`PLANE_JOB_BYTES`]), still reaches the disk plane by plane (a 4K file of 31 + /// channels or more was refused whole); only a single plane larger than the cache is left out. + #[test] + fn a_large_plane_set_is_written_plane_by_plane() { + let dir = tmpdir("planes-large"); + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + let (files, _) = plane_source(&dir.join("src")); + // 8 planes of 32 KiB: 256 KiB together, over the cache's 80 KiB and over a queued write. + let (w, h) = (128u32, 64u32); + let plane = (w * h) as usize; + dc.set_max_bytes(80 << 10); + let set: Vec<(u128, String, Vec)> = (0..8).map(|i| (200 + i as u128, format!("p{i}"), vec![0.5; plane])).collect(); + assert!(set.len() * plane * 4 > PLANE_JOB_BYTES); + assert!(dc.put_planes(w, h, set, &files, 0)); + dc.flush(); + assert!(!dc.keys(Kind::Plane).is_empty(), "planes reached the disk"); + assert!(dc.get_plane(207, w, h).is_some(), "the last one too"); + // One plane larger than the whole cache: left out. + dc.set_max_bytes(16 << 10); + assert!(dc.put_planes(w, h, vec![(300, "big".into(), vec![0.5; plane])], &files, 0)); + dc.flush(); + assert!(!dc.contains(Kind::Plane, 300)); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn hit_miss_and_exact_round_trip() { let dir = tmpdir("hit"); @@ -1989,7 +2643,7 @@ mod tests { } /// Layer jobs hold float buffers until they are compressed: the queue holds at most - /// [`LAYER_QUEUE_BYTES`] of them (64 at 4K held ~8.5 GB), and a single bigger one only alone. + /// [`JOB_QUEUE_BYTES`] of them (64 at 4K held ~8.5 GB), and a single bigger one only alone. #[test] fn layer_writes_queue_within_a_byte_budget() { let mut q = Queue { @@ -2001,19 +2655,19 @@ mod tests { pending_frames: Default::default(), drops: Drops::default(), }; - let layer = LAYER_QUEUE_BYTES / 4 + 1; + let layer = JOB_QUEUE_BYTES / 4 + 1; for _ in 0..3 { assert!(!q.full(Kind::Layer, layer)); - q.jobs.push_back(Job::Write(Kind::Layer, 0, 0, Payload::Encoded(vec![]))); + q.jobs.push_back(Job::Write(Kind::Layer, 0, 0, Payload::Lz4(vec![]))); q.job_bytes += layer; } assert!(q.full(Kind::Layer, layer), "a fourth would pass the budget"); assert!(!q.full(Kind::Frame, 1024), "frames have their own budget"); let mut empty = Queue { jobs: Default::default(), job_bytes: 0, ..q }; - assert!(!empty.full(Kind::Layer, 2 * LAYER_QUEUE_BYTES), "a single big layer, alone"); + assert!(!empty.full(Kind::Layer, 2 * JOB_QUEUE_BYTES), "a single big layer, alone"); // Taking a job gives its bytes back. empty.job_bytes = 3; - empty.jobs.push_back(Job::Write(Kind::Layer, 0, 0, Payload::Encoded(vec![0; 3]))); + empty.jobs.push_back(Job::Write(Kind::Layer, 0, 0, Payload::Lz4(vec![0; 3]))); assert!(empty.pop().is_some()); assert_eq!(empty.job_bytes, 0); } @@ -2643,4 +3297,29 @@ mod tests { assert!(!dc.made_of_dropped(&files, &dc.drops_now()), "read after the drop: used"); let _ = std::fs::remove_dir_all(&dir); } + + /// #3301: a frame or plane set is written only when making it again costs more than + /// reading it back: a cheap one is not written, an expensive one is; the read rate follows + /// the reads measured. + #[test] + fn only_items_dearer_to_make_than_to_read_are_written() { + let dir = tmpdir("pays-off"); + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + let eight_mb = 8 << 20; + // Until a read is measured: 10 ms per MB, 80 ms for 8 MB. + assert_eq!(dc.read_us(eight_mb), 8 * DEFAULT_READ_US_PER_MB); + assert!(!dc.pays_off(eight_mb, 1_000), "rendered in 1 ms: not written"); + assert!(dc.pays_off(eight_mb, 200_000), "rendered in 200 ms: written"); + // Reads measured at 1 ms per MB: a 20 ms frame of 8 MB is now worth writing. + assert!(!dc.pays_off(eight_mb, 20_000)); + for _ in 0..40 { + dc.note_read(1 << 20, 1_000); + } + assert!(dc.pays_off(eight_mb, 20_000), "{}", dc.read_us(eight_mb)); + // Tiny reads are not timed. + dc.note_read(100, 1_000_000); + assert!(dc.pays_off(eight_mb, 20_000)); + drop(dc); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/render/src/footage.rs b/crates/render/src/footage.rs index 25a5ef608..5d9ab4a21 100644 --- a/crates/render/src/footage.rs +++ b/crates/render/src/footage.rs @@ -37,6 +37,21 @@ pub trait FootageSource: Send + Sync { None => self.frame(item, footage, t), } } + /// [`FootageSource::frame_with`] where only the rows `rows` (of the footage's frame, at + /// full resolution) are shown (#3271: a viewer region of interest mapped back through the + /// layer): a source may leave the other rows empty (any value) and read only those. Sources + /// that read whole frames can leave the default, which reads it all. + fn frame_rows(&self, item: ItemId, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve, rows: (i64, i64)) -> Option> { + let _ = rows; + self.frame_with(item, footage, t, size, float) + } + /// Whether [`FootageSource::frame_rows`] reads only the rows asked for of `footage` at `t` + /// (#3271). A source that reads the whole frame anyway leaves the default: the renderer then + /// asks for the whole frame, which its layer cache keeps. + fn reads_rows(&self, footage: &Footage, t: Tick) -> bool { + let _ = (footage, t); + false + } /// [`FootageSource::frame_with`]'s full-size frame as 8-bit levels: each pixel is /// [`effectcraft_raster::quantize_px_u8`] of the float pixel `frame_with` would give, so /// [`effectcraft_raster::expand_u8`] makes that frame quantised to 8 bpc, bit for bit, from a @@ -57,12 +72,47 @@ pub trait FootageSource: Send + Sync { fn aux(&self, _item: ItemId, _footage: &Footage, _t: Tick) -> Option> { None } + /// [`FootageSource::aux`] of only what `need` reads (#3271): the channels its lookups find, + /// or more (sources may hand over a set that holds them; [`effectcraft_raster::AuxChannels::listed`] + /// then names every channel). Sources that read every channel anyway can leave the default. + fn aux_for( + &self, + item: ItemId, + footage: &Footage, + t: Tick, + need: &effectcraft_raster::channels3d::AuxNeed, + ) -> Option> { + let _ = need; + self.aux(item, footage, t) + } + /// The channel names of [`FootageSource::aux`] (planes may be empty: read from the file's + /// headers alone), for channel lists and popups. Never handed to an effect. + fn aux_names(&self, item: ItemId, footage: &Footage, t: Tick) -> Option> { + self.aux(item, footage, t) + } /// The footage files (by [`Footage::path`]) whose channels effects of the project read /// through [`FootageSource::aux`] (EXtractoR, Cryptomatte and the other 3D Channel effects), /// replacing the set given before. A source that decodes a file's picture and its channels /// separately can decode both at once for these from the first frame on. Sources that don't /// ignore it. fn set_aux_footage(&self, _paths: &[String]) {} + /// What the effects reading the channels of each footage file (by [`Footage::path`], as + /// [`FootageSource::set_aux_footage`] names them) read of them (#3271), replacing what was + /// given before: the picture of such footage is then decoded together with those channels + /// only. A file not named here reads every channel. Sources that don't care ignore it. + fn set_aux_needs(&self, _needs: &[(String, effectcraft_raster::channels3d::AuxNeed)]) {} + /// The disk cache (Settings ▸ Media & Disk Cache), `None` when it is off: sources that + /// decode costly footage keep what they decoded there too (#3271: OpenEXR channels). + /// Sources without such a tier ignore it. + fn set_disk_cache(&self, _cache: Option>) {} + /// Settings ▸ Disk ▸ Localize Network Footage: copy network footage in the background and + /// read the copies once they are complete and verified (`None`: off). Sources that don't read + /// files ignore it. + fn set_localizer(&self, _config: Option) {} + /// What the localizer is doing (`None`: off or not supported). + fn localize_status(&self) -> Option { + None + } /// The parsed 3D model of a [`effectcraft_project::FootageKind::Model`] item (Advanced 3D). fn model(&self, _item: ItemId, _footage: &Footage) -> Option> { None @@ -180,12 +230,37 @@ impl FootageSource for CancellableFootage<'_> { fn audio(&self, item: ItemId, footage: &Footage, t: Tick, frames: usize, rate: u32) -> Option> { self.inner.audio(item, footage, t, frames, rate) } + // (decoding channels is a read like a frame's: called off with the render, between batches) fn aux(&self, item: ItemId, footage: &Footage, t: Tick) -> Option> { - self.inner.aux(item, footage, t) + self.read(|| self.inner.aux(item, footage, t)) + } + fn aux_for( + &self, + item: ItemId, + footage: &Footage, + t: Tick, + need: &effectcraft_raster::channels3d::AuxNeed, + ) -> Option> { + self.read(|| self.inner.aux_for(item, footage, t, need)) + } + fn aux_names(&self, item: ItemId, footage: &Footage, t: Tick) -> Option> { + self.inner.aux_names(item, footage, t) } fn set_aux_footage(&self, paths: &[String]) { self.inner.set_aux_footage(paths) } + fn set_aux_needs(&self, needs: &[(String, effectcraft_raster::channels3d::AuxNeed)]) { + self.inner.set_aux_needs(needs) + } + fn set_disk_cache(&self, cache: Option>) { + self.inner.set_disk_cache(cache) + } + fn set_localizer(&self, config: Option) { + self.inner.set_localizer(config) + } + fn localize_status(&self) -> Option { + self.inner.localize_status() + } fn model(&self, item: ItemId, footage: &Footage) -> Option> { self.inner.model(item, footage) } @@ -223,6 +298,12 @@ impl FootageSource for CancellableFootage<'_> { fn frame_with(&self, item: ItemId, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve) -> Option> { self.read(|| self.inner.frame_with(item, footage, t, size, float)) } + fn frame_rows(&self, item: ItemId, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve, rows: (i64, i64)) -> Option> { + self.read(|| self.inner.frame_rows(item, footage, t, size, float, rows)) + } + fn reads_rows(&self, footage: &Footage, t: Tick) -> bool { + self.inner.reads_rows(footage, t) + } fn frame8(&self, item: ItemId, footage: &Footage, t: Tick, float: FloatCurve) -> Option> { self.read(|| self.inner.frame8(item, footage, t, float)) } @@ -268,3 +349,34 @@ impl FootageSource for NoFootage { f() } } + +/// Settings ▸ Disk ▸ Localize Network Footage (#3271): where network footage is copied, how much +/// the copies may take, which locations count as network besides UNC paths, and how to read the +/// copies' disk's free space (the disk cache's reserve stays free there). +#[derive(Clone)] +pub struct LocalizeConfig { + pub folder: std::path::PathBuf, + pub max_bytes: u64, + /// Path prefixes that count as network footage (a drive letter mapped to a share, `P:\`). + pub network: Vec, + /// The copies' disk: `(total, available)` bytes, `None` unknown. + pub disk_space: Option Option<(u64, u64)> + Send + Sync>>, +} + +/// What the footage localizer is doing (Settings ▸ Disk shows it). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct LocalizeReport { + /// Complete local copies and their bytes, and the most they may take. + pub files: usize, + pub bytes: u64, + pub max_bytes: u64, + /// Files waiting to be copied, and those too large or that failed to copy. + pub queued: usize, + pub skipped: usize, + /// The file being copied now. + pub copying: Option, + /// The locations that count as network besides UNC paths. + pub network: Vec, + /// Free disk space holds the copies below the size limit. + pub reserve_limited: bool, +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 1b81a7e5c..2408c3cf1 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -16,6 +16,7 @@ pub mod disk_cache; use color::Region; pub mod eval; pub mod masks; +pub mod memory; pub mod passes; pub mod reads; pub mod shapes; @@ -47,7 +48,9 @@ mod opts; mod pipeline; pub use accel::{Accelerator, Backend, FrameMemory, FxStep, FxTarget}; -pub use footage::{CancellableFootage, FloatCurve, FootageSource, NoFootage, is_vector_footage, missing_item_problem, vector_fit}; +pub use footage::{ + CancellableFootage, FloatCurve, FootageSource, LocalizeConfig, LocalizeReport, NoFootage, is_vector_footage, missing_item_problem, vector_fit, +}; pub use frames::{ adaptive_samples, blend_frames, cineon_frame, content_bounds, extended_region, field_frame, frame_position, frame_size, interpret_pixels, kurbo_path, mix_window, render_frame, roi_inside, diff --git a/crates/render/src/memory.rs b/crates/render/src/memory.rs new file mode 100644 index 000000000..8412401b7 --- /dev/null +++ b/crates/render/src/memory.rs @@ -0,0 +1,1013 @@ +//! One memory accountant for the big caches (#3271, #3298): the layer cache, the media pool's +//! frames, the decoded footage planes, the preview frames and the disk cache's write queue +//! register here as [`MemoryHolder`]s and share one budget ([`Accountant::set_budget`], from +//! Settings ▸ Memory & CPU ▸ RAM Reserved for Other Applications). No holder has a share of its +//! own: when they hold more than the budget together, the accountant frees the least valuable +//! item first, whichever holder keeps it, in large steps: down to [`TRIM_TO`] of the budget, so +//! a cache doesn't fill up and trim again with every insert. +//! +//! An item's value is what it would cost to make again per byte ([`Candidate::cost_us`], the +//! measured render or decode time where known, else a typical one: [`DEFAULT_LAYER_US_PER_MB`] +//! and its neighbours), decayed slowly by the time since it was last used (by the logarithm of +//! the seconds unused, so a costly frame unused for minutes still outlives a cheap one): +//! [`value`]. A copy of data another cache holds (a queued disk write) costs nothing to make +//! again. Each holder offers the item it would drop next (its least recently used one, +//! [`MemoryHolder::oldest`]); the accountant drops the least valuable of those, asks that holder +//! for its next one, and repeats. +//! +//! A holder that had to make again what it let go of shortly before (its "refills", +//! [`MemoryHolder::refills`]) is thrashing: its items are worth [`THRASH_BOOST`] times more +//! until it settles, so the data that is needed again is kept longest. +//! +//! Holders are held weakly: a cache that goes away is forgotten. The accountant never calls a +//! holder while it holds its own lock, and holders call [`Accountant::note_growth`] after +//! releasing theirs. + +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError, TryLockError, Weak}; + +/// The share of the budget the accountant frees down to once it is over (hysteresis). +pub const TRIM_TO: f64 = 0.9; + +/// While a holder thrashes, its items are worth this many times more ([`value`]). +pub const THRASH_BOOST: f64 = 4.0; + +/// What it typically costs to make again a megabyte of each holder's data when its own time was +/// not measured (microseconds per MB): a processed layer buffer… +pub const DEFAULT_LAYER_US_PER_MB: u64 = 4_000; +/// …a RAM preview frame (the whole comp rendered)… +pub const DEFAULT_PREVIEW_US_PER_MB: u64 = 8_000; +/// …a decoded footage frame… +pub const DEFAULT_FRAME_US_PER_MB: u64 = 2_000; +/// …and decoded footage planes (OpenEXR channels). +pub const DEFAULT_PLANE_US_PER_MB: u64 = 2_000; + +/// The typical cost (µs) of making again `bytes` bytes at `us_per_mb`. +pub fn default_cost(bytes: usize, us_per_mb: u64) -> u64 { + let mb = u64::try_from(bytes).unwrap_or(u64::MAX) >> 20; + mb.max(1).saturating_mul(us_per_mb) +} + +/// The use stamp holders give their items: microseconds since the process's first stamp, and +/// later uses get larger stamps (two uses never tie: holders may key their order by it). +pub fn tick() -> u64 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let start = START.get_or_init(web_time::Instant::now); + let now = u64::try_from(start.elapsed().as_micros()).unwrap_or(u64::MAX); + let mut last = LAST.load(Ordering::Relaxed); + loop { + let next = now.max(last.saturating_add(1)); + match LAST.compare_exchange_weak(last, next, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => return next, + Err(seen) => last = seen, + } + } +} + +/// Inserts balance at most this often ([`Accountant::note_growth`])… +const BALANCE_EVERY: std::time::Duration = std::time::Duration::from_millis(100); + +/// …unless the holders grew by more than this part of the budget since the last balance +/// (several large decodes landing within one interval could otherwise overshoot by gigabytes). +const GROWTH_PART: usize = 16; + +/// How long a holder that refilled stays protected. +const THRASH_FOR: std::time::Duration = std::time::Duration::from_secs(10); + +/// The item a holder would drop next ([`MemoryHolder::oldest`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Candidate { + /// When it was last used ([`tick`]). + pub used: u64, + /// The bytes dropping it frees. + pub bytes: usize, + /// What making it again costs, in microseconds (0: a copy of data another cache holds). + pub cost_us: u64, + /// About to be used: a frame a playing RAM preview shows next. Kept over the budget by up to + /// [`preview_overage`] while other items can go instead, never past the hard limit. + pub protected: bool, +} + +impl Candidate { + /// An item that is not [`Candidate::protected`]. + pub fn new(used: u64, bytes: usize, cost_us: u64) -> Candidate { + Candidate { used, bytes, cost_us, protected: false } + } +} + +/// How far protected items (frames a playing preview shows next) may keep the caches over a +/// budget of `budget` bytes while other items can go instead: a tenth of it, at most 1 GB. +pub fn preview_overage(budget: usize) -> usize { + (budget / 10).min(1 << 30) +} + +/// How often the process's memory is read at most ([`Accountant::set_process_memory`]), in +/// [`tick`]'s units (microseconds). +const PROCESS_READ_EVERY: u64 = 250_000; + +/// The process's memory as the accountant watches it ([`Accountant::set_process_memory`]). +struct ProcessWatch { + /// Reads the memory the process uses now, in bytes (`None`: unknown). + read: Option Option>, + /// Above this the caches are trimmed by what is over, even when they are within their + /// budget (memory nobody accounts for: GPU staging, effect buffers, the allocator's + /// fragmentation)… + purge_at: u64, + /// …and above this also the protected items go ([`Candidate::protected`]). + hard_at: u64, + /// When it was last read ([`tick`]'s units). + read_at: Option, + /// What the caches freed for it since it was last under its purge limit: freed memory often + /// stays in the reading (the allocator keeps it), so it counts as freed; the caches give way + /// again only for memory that grew beyond that, and are never emptied for one reading. + credited: u64, +} + +/// What an item is worth keeping at `now` ([`tick`]): its cost to make again per byte, divided +/// by `ln(seconds unused + 1) + 1` (a slow decay: about a fifth after a minute unused, a +/// seventh after ten), [`THRASH_BOOST`] times more while its holder thrashes. +pub fn value(c: &Candidate, now: u64, thrashing: bool) -> f64 { + let per_byte = c.cost_us as f64 / c.bytes.max(1) as f64; + let age_s = now.saturating_sub(c.used) as f64 / 1e6; + let v = per_byte / ((age_s + 1.0).ln() + 1.0); + if thrashing { v * THRASH_BOOST } else { v } +} + +/// A cache the accountant keeps within the common budget. +pub trait MemoryHolder: Send + Sync { + /// A name for logs and stats. + fn name(&self) -> &'static str; + /// The bytes it holds now. + fn bytes(&self) -> usize; + /// The item it would drop next, its least recently used one it may drop (`None`: nothing it + /// may drop, such as data in use). + fn oldest(&self) -> Option; + /// Drop that item; the bytes freed (0: nothing dropped). + fn drop_oldest(&self) -> usize; + /// How many times so far it made again what it had let go of shortly before (0 when it + /// doesn't tell). + fn refills(&self) -> u64 { + 0 + } +} + +struct Registered { + holder: Weak, + /// Its refills at the last balance, and until when it counts as thrashing (it refilled). + refills: u64, + thrash_until: Option, +} + +/// The common budget of the big caches (see the module notes). +pub struct Accountant { + budget: AtomicUsize, + holders: Mutex>, + /// Bytes freed by the accountant so far (stats, tests). + freed: AtomicUsize, + /// Bytes the holders said they grew by since the last balance ([`Accountant::note_growth`]). + grown: AtomicUsize, + /// One balance at a time (another one asked for meanwhile is run by the one running, see + /// `requested`), and when the last one ran. + balancing: Mutex>, + /// A balance was asked for since the running one read the budget: it runs again (a budget + /// lowered meanwhile is not lost, #3301 review). + requested: AtomicBool, + /// The clock items' ages are measured with ([`tick`]; tests give their own). + clock: fn() -> u64, + /// The process's memory, read and checked by each balance. + process: Mutex, +} + +impl Default for Accountant { + fn default() -> Self { + Accountant::new(usize::MAX) + } +} + +impl Accountant { + /// An accountant with `budget` bytes (`usize::MAX`: no limit). + pub const fn new(budget: usize) -> Accountant { + Accountant::with_clock(budget, tick) + } + + /// An accountant with `budget` bytes measuring ages with `clock` (in [`tick`]'s units). + pub const fn with_clock(budget: usize, clock: fn() -> u64) -> Accountant { + Accountant { + budget: AtomicUsize::new(budget), + holders: Mutex::new(Vec::new()), + freed: AtomicUsize::new(0), + grown: AtomicUsize::new(0), + balancing: Mutex::new(None), + requested: AtomicBool::new(false), + clock, + process: Mutex::new(ProcessWatch { read: None, purge_at: u64::MAX, hard_at: u64::MAX, read_at: None, credited: 0 }), + } + } + + /// Watch the process's memory with `read` (the bytes it uses now): a balance (at most every + /// 250 ms) trims the caches by what it is over `purge_at`, even while they are within their + /// budget, and above `hard_at` also the frames a playing preview shows next. + pub fn set_process_memory(&self, read: fn() -> Option, purge_at: u64, hard_at: u64) { + { + let mut p = self.process.lock().unwrap_or_else(PoisonError::into_inner); + p.read = Some(read); + p.purge_at = purge_at; + p.hard_at = hard_at.max(purge_at); + } + self.balance(); + } + + /// What a balance at `now` must free beyond the budget for the process's memory, and whether + /// it is past the hard limit (a reading at most every [`PROCESS_READ_EVERY`]). What the caches + /// already freed for it counts as freed ([`ProcessWatch::credited`]). + fn process_excess(&self, now: u64) -> (u64, bool) { + let mut p = self.process.lock().unwrap_or_else(PoisonError::into_inner); + let Some(read) = p.read else { return (0, false) }; + if p.read_at.is_some_and(|at| now.saturating_sub(at) < PROCESS_READ_EVERY) { + return (0, false); + } + p.read_at = Some(now); + let Some(used) = read() else { return (0, false) }; + if used <= p.purge_at { + p.credited = 0; + return (0, false); + } + let used = used.saturating_sub(p.credited); + // (down to the trim line under the purge limit, as for the budget) + let line = (p.purge_at as f64 * TRIM_TO) as u64; + (used.saturating_sub(line), used > p.hard_at) + } + + /// The caches freed `bytes` for the process's memory. + fn credit(&self, bytes: usize) { + let mut p = self.process.lock().unwrap_or_else(PoisonError::into_inner); + p.credited = p.credited.saturating_add(u64::try_from(bytes).unwrap_or(u64::MAX)); + } + + /// The process's accountant. + pub fn global() -> &'static Accountant { + static GLOBAL: Accountant = Accountant::new(usize::MAX); + &GLOBAL + } + + /// Set the common budget and free down to it: right away when no balance is running; when + /// one is (on another thread, or this one further up the stack), that balance runs again + /// with the new budget once its pass ends, so this may return before the caches are within + /// it ([`Accountant::balance`]). + pub fn set_budget(&self, bytes: usize) { + self.budget.store(bytes, Ordering::Relaxed); + self.balance(); + } + + pub fn budget(&self) -> usize { + self.budget.load(Ordering::Relaxed) + } + + /// Keep `holder` within the common budget (held weakly). + pub fn register(&self, holder: &Arc) { + let mut h = self.holders.lock().unwrap_or_else(PoisonError::into_inner); + h.retain(|r| r.holder.strong_count() > 0); + let weak = Arc::downgrade(holder); + // (registered again with each new budget: once is enough) + if h.iter().any(|r| r.holder.ptr_eq(&weak)) { + return; + } + h.push(Registered { holder: weak, refills: holder.refills(), thrash_until: None }); + } + + /// A holder grew by `bytes` (an insert): balance, at most every [`BALANCE_EVERY`] (the + /// holders' locks aren't taken on every insert), or at once when the holders grew by more + /// than a [`GROWTH_PART`]th of the budget since the last balance. + pub fn note_growth(&self, bytes: usize) { + let budget = self.budget(); + if budget == usize::MAX { + return; + } + let grown = self.grown.fetch_add(bytes, Ordering::Relaxed).saturating_add(bytes); + let burst = grown > budget / GROWTH_PART; + let ran_lately = |last: &Option| last.is_some_and(|t| t.elapsed() < BALANCE_EVERY); + // (a balance running now counts as recent; a poisoned lock still holds the time) + let recent = match self.balancing.try_lock() { + Ok(g) => ran_lately(&g), + Err(TryLockError::Poisoned(p)) => ran_lately(&p.into_inner()), + Err(TryLockError::WouldBlock) => true, + }; + // (a balance asked for while this read held the lock found it busy: serve it here) + if burst || !recent || self.requested.load(Ordering::SeqCst) { + self.balance(); + } + } + + /// The holders alive now, and whether each is thrashing. + fn alive(&self) -> Vec<(Arc, bool)> { + let mut h = self.holders.lock().unwrap_or_else(PoisonError::into_inner); + h.retain(|r| r.holder.strong_count() > 0); + h.iter_mut() + .filter_map(|r| { + let holder = r.holder.upgrade()?; + let refills = holder.refills(); + let now = web_time::Instant::now(); + if refills > r.refills { + r.thrash_until = Some(now + THRASH_FOR); + } + r.refills = refills; + Some((holder, r.thrash_until.is_some_and(|t| t > now))) + }) + .collect() + } + + /// The bytes all holders hold now. + pub fn total(&self) -> usize { + let h = self.holders.lock().unwrap_or_else(PoisonError::into_inner); + let alive: Vec> = h.iter().filter_map(|r| r.holder.upgrade()).collect(); + drop(h); + alive.iter().map(|h| h.bytes()).fold(0, usize::saturating_add) + } + + /// Bytes freed by the accountant so far. + pub fn freed(&self) -> usize { + self.freed.load(Ordering::Relaxed) + } + + /// When the holders together are over the budget, free down to [`TRIM_TO`] of it, the least + /// valuable item first whichever holder keeps it ([`value`]; equal values: the least + /// recently used first, then the holder registered first). + /// + /// One balance runs at a time. One asked for while another runs (a lowered budget, more + /// growth) is run by that one when it is done, with the budget then in force (or by + /// [`Accountant::note_growth`], when that held the lock to read the time); a poisoned lock + /// (a holder panicked in a balance) doesn't stop balancing. + pub fn balance(&self) { + self.requested.store(true, Ordering::SeqCst); + loop { + let mut last: MutexGuard<'_, Option> = match self.balancing.try_lock() { + Ok(g) => g, + Err(TryLockError::Poisoned(p)) => p.into_inner(), + // (the running balance sees `requested` and runs again) + Err(TryLockError::WouldBlock) => return, + }; + while self.requested.swap(false, Ordering::SeqCst) { + *last = Some(web_time::Instant::now()); + self.balance_once(); + } + drop(last); + // (asked for between the last pass and the unlock: run it, unless another took over) + if !self.requested.load(Ordering::SeqCst) { + return; + } + } + } + + /// One pass of [`Accountant::balance`] with the budget in force now. + /// + /// Over the budget the caches are freed down to [`TRIM_TO`] of it; with the process's memory + /// over its purge limit ([`Accountant::set_process_memory`]) also by what that is over. + /// Protected items ([`Candidate::protected`]) go last, and only while the caches are more than + /// [`preview_overage`] over the target (or the process is past its hard limit). + fn balance_once(&self) { + let budget = self.budget(); + if budget == usize::MAX { + return; + } + self.grown.store(0, Ordering::Relaxed); + let now = (self.clock)(); + let (excess, hard) = self.process_excess(now); + let holders = self.alive(); + let mut total: usize = holders.iter().map(|(h, _)| h.bytes()).fold(0, usize::saturating_add); + let excess = usize::try_from(excess).unwrap_or(usize::MAX); + if total <= budget && excess == 0 { + return; + } + let held = total; + let trimmed = if total > budget { (budget as f64 * TRIM_TO) as usize } else { total }; + // (the caches can free at most what they hold) + let target = trimmed.min(total.saturating_sub(excess.min(total))); + let overage = if hard { 0 } else { preview_overage(budget) }; + // Each holder's next item (`None`: it has nothing more it may drop). + let mut next: Vec> = holders.iter().map(|(h, _)| h.oldest()).collect(); + while total > target { + // (protected items only once nothing else can go, or past the overage) + let any_unprotected = next.iter().flatten().any(|c| !c.protected); + let protected_ok = !any_unprotected && total > target.saturating_add(overage); + let pick = next + .iter() + .enumerate() + .filter_map(|(i, c)| { + let c = (*c)?; + if c.protected && !protected_ok { + return None; + } + let thrashing = holders.get(i).is_some_and(|(_, t)| *t); + Some((i, value(&c, now, thrashing), c.used)) + }) + .min_by(|a, b| a.1.total_cmp(&b.1).then(a.2.cmp(&b.2)).then(a.0.cmp(&b.0))); + let Some((i, _, _)) = pick else { break }; + let Some((h, _)) = holders.get(i) else { break }; + let freed = h.drop_oldest(); + if let Some(slot) = next.get_mut(i) { + *slot = if freed == 0 { None } else { h.oldest() }; + } + total = total.saturating_sub(freed); + self.freed.fetch_add(freed, Ordering::Relaxed); + } + if excess > 0 { + // (what went beyond the budget's own trim was freed for the process's memory) + let for_budget = held.saturating_sub(trimmed.max(target)); + self.credit(held.saturating_sub(total).saturating_sub(for_budget).min(excess)); + } + } +} + +/// What the system's memory allows one request for a file's decoded planes (an OpenEXR's +/// channels) to take; 0: not known yet ([`decode_limit`]). +static DECODE_LIMIT: AtomicUsize = AtomicUsize::new(0); + +/// Counts the changes of that limit: a refusal made under an older one is out of date +/// ([`decode_limit_generation`]). +static DECODE_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// How often the system was asked for the limit without an answer ([`decode_limit`]). +static DECODE_UNANSWERED: AtomicUsize = AtomicUsize::new(0); + +/// Reads that limit from the system when nothing set it ([`set_decode_limit_source`]). +static DECODE_SOURCE: Mutex Option>> = Mutex::new(None); + +/// One reading of the system at a time: the second asker takes the first one's answer. +static DECODE_ASKING: Mutex<()> = Mutex::new(()); + +/// The system is asked this often at most for the limit when it does not answer. +const DECODE_ASKS: usize = 2; + +fn store_decode_limit(bytes: usize) { + // (the limit before its generation, both sequentially consistent: whoever sees the new + // generation sees the new limit) + if DECODE_LIMIT.swap(bytes, Ordering::SeqCst) != bytes { + DECODE_GENERATION.fetch_add(1, Ordering::SeqCst); + } +} + +/// Set what the system's memory allows one request for a file's decoded planes to take +/// (`None`: unknown again). The session sets it with the memory budget once the installed RAM +/// is read. +pub fn set_decode_limit(bytes: Option) { + store_decode_limit(bytes.unwrap_or(0)); + DECODE_UNANSWERED.store(0, Ordering::Relaxed); +} + +/// Changes whenever [`decode_limit`] gives another answer: a request refused for its size is +/// asked again after that. +pub fn decode_limit_generation() -> u64 { + DECODE_GENERATION.load(Ordering::SeqCst) +} + +/// Where [`decode_limit`] reads the limit from while nothing set it: the CLI and the MCP server +/// read no memory otherwise. The reading may take a second, so it is only asked for when a +/// request is over the fixed floor. +pub fn set_decode_limit_source(source: Option Option>) { + *DECODE_SOURCE.lock().unwrap_or_else(PoisonError::into_inner) = source; + DECODE_UNANSWERED.store(0, Ordering::Relaxed); +} + +/// The most bytes one request of `need` bytes for a file's decoded planes may take: `floor` +/// (the fixed limit), or what the system's memory allows when that is more. The system is +/// asked only when `need` is over `floor`, and the answer is kept; when it gives none (a reading +/// that failed) it is asked once more later, then `floor` stays. The browser keeps `floor`. +pub fn decode_limit(floor: usize, need: usize) -> usize { + if need <= floor || cfg!(target_arch = "wasm32") { + return floor; + } + if DECODE_LIMIT.load(Ordering::SeqCst) == 0 { + let _asking = DECODE_ASKING.lock().unwrap_or_else(PoisonError::into_inner); + // (another thread may have just read it, or have used up the asks) + if DECODE_LIMIT.load(Ordering::SeqCst) == 0 && DECODE_UNANSWERED.load(Ordering::Relaxed) < DECODE_ASKS { + let source = *DECODE_SOURCE.lock().unwrap_or_else(PoisonError::into_inner); + match source.and_then(|read| read()) { + // (only while nothing set a limit meanwhile: the session's figure, set during the + // reading, is newer than this one) + Some(bytes) => { + if DECODE_LIMIT.compare_exchange(0, bytes, Ordering::SeqCst, Ordering::SeqCst).is_ok() && bytes != 0 { + DECODE_GENERATION.fetch_add(1, Ordering::SeqCst); + } + } + None => { + DECODE_UNANSWERED.fetch_add(1, Ordering::Relaxed); + // (a request refused for its size before this reading is asked again, so the + // reading left is not shut out by that refusal) + DECODE_GENERATION.fetch_add(1, Ordering::SeqCst); + } + } + } + } + floor.max(DECODE_LIMIT.load(Ordering::SeqCst)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A holder of items `(used, bytes, cost_us)`, least recently used first. + struct Fake { + name: &'static str, + items: Mutex>, + refills: Mutex, + } + + impl Fake { + fn new(name: &'static str, items: &[(u64, usize, u64)]) -> Arc { + let items = items.iter().map(|&(used, bytes, cost_us)| Candidate::new(used, bytes, cost_us)).collect(); + Arc::new(Fake { name, items: Mutex::new(items), refills: Mutex::new(0) }) + } + fn held(&self) -> usize { + self.items.lock().unwrap().iter().map(|c| c.bytes).sum() + } + fn count(&self) -> usize { + self.items.lock().unwrap().len() + } + fn push(&self, used: u64, bytes: usize, cost_us: u64) { + self.items.lock().unwrap().push_back(Candidate::new(used, bytes, cost_us)); + } + } + + impl MemoryHolder for Fake { + fn name(&self) -> &'static str { + self.name + } + fn bytes(&self) -> usize { + self.held() + } + fn oldest(&self) -> Option { + self.items.lock().unwrap().front().copied() + } + fn drop_oldest(&self) -> usize { + self.items.lock().unwrap().pop_front().map_or(0, |c| c.bytes) + } + fn refills(&self) -> u64 { + *self.refills.lock().unwrap() + } + } + + fn holder(f: &Arc) -> Arc { + f.clone() + } + + /// The tests' clock: everything is measured at 100 s. + fn at_100s() -> u64 { + 100_000_000 + } + + fn accountant(budget: usize, held: &[&Arc]) -> (Accountant, Vec>) { + let acc = Accountant::with_clock(budget, at_100s); + let held: Vec> = held.iter().map(|f| holder(f)).collect(); + for h in &held { + acc.register(h); + } + (acc, held) + } + + const S: u64 = 1_000_000; + + /// #3298: an expensive preview frame outlives a cheap footage plane of the same age and size. + #[test] + fn an_expensive_item_outlives_a_cheap_one_of_the_same_age() { + let preview = Fake::new("preview frames", &[(90 * S, 100, 50_000)]); + let planes = Fake::new("footage planes", &[(90 * S, 100, 5_000)]); + let (acc, _held) = accountant(150, &[&preview, &planes]); + acc.balance(); + assert_eq!((preview.count(), planes.count()), (1, 0)); + } + + /// #3298: a recent, costly plane outlives an older, cheap preview frame (by kind alone the + /// preview frames were freed last, whatever they cost and however long unused). + #[test] + fn a_recent_costly_plane_outlives_an_old_cheap_preview_frame() { + let preview = Fake::new("preview frames", &[(0, 100, 5_000)]); + let planes = Fake::new("footage planes", &[(99 * S, 100, 50_000)]); + let (acc, _held) = accountant(150, &[&planes, &preview]); + acc.balance(); + assert_eq!((preview.count(), planes.count()), (0, 1)); + } + + /// Value decays with time unused: of two items that cost the same, the older goes first, and + /// one unused for long enough goes before a costlier one used just now. + #[test] + fn value_falls_with_time_unused() { + let c = |used, cost_us| Candidate::new(used, 100, cost_us); + assert!(value(&c(0, 1000), at_100s(), false) < value(&c(99 * S, 1000), at_100s(), false)); + let fresh = value(&c(at_100s(), 1000), at_100s(), false); + assert!((fresh - 10.0).abs() < 1e-9, "{fresh}"); + let a_second = value(&c(at_100s() - S, 1000), at_100s(), false); + assert!((a_second - 10.0 / (2f64.ln() + 1.0)).abs() < 1e-9, "{a_second}"); + // #3301: the decay is slow: unused for ten minutes, an item keeps more than a tenth of its + // value (it kept under a twentieth when it halved every 30 s). + let ten_minutes = value(&c(0, 1000), 600 * S, false); + assert!(ten_minutes > fresh / 10.0, "{ten_minutes}"); + assert!(value(&c(0, 2000), at_100s(), false) < value(&c(at_100s(), 1000), at_100s(), false)); + assert_eq!(value(&c(at_100s(), 0), at_100s(), false), 0.0, "a copy is worth nothing"); + assert_eq!(value(&c(0, 1000), at_100s(), true), THRASH_BOOST * value(&c(0, 1000), at_100s(), false)); + } + + /// Over the budget, items go least valuable first across holders, down to 90 % of the + /// budget in one step; under it nothing is touched, and a copy goes first. + #[test] + fn least_valuable_first_down_to_the_trim_line() { + let queue = Fake::new("disk write queue", &[(99 * S, 300, 0)]); + let frames = Fake::new("footage frames", &[(10 * S, 100, 2_000), (20 * S, 100, 2_000), (30 * S, 100, 2_000), (40 * S, 100, 2_000)]); + let layers = Fake::new("layer cache", &[(10 * S, 100, 40_000), (20 * S, 100, 40_000), (30 * S, 100, 40_000)]); + let (acc, _held) = accountant(1000, &[&layers, &frames, &queue]); + acc.balance(); + assert_eq!((queue.held(), frames.held(), layers.held()), (300, 400, 300), "at the budget: nothing freed"); + frames.push(50 * S, 200, 4_000); + acc.balance(); + // 1200 held, down to 900: the queued copy goes first (300), nothing more is needed. + assert_eq!((queue.held(), frames.held(), layers.held()), (0, 600, 300)); + assert_eq!(acc.total(), 900); + assert_eq!(acc.freed(), 300); + // A little over again: freed in one step to 900 or below, the cheap frames first. + layers.push(60 * S, 300, 120_000); + acc.balance(); + assert!(acc.total() <= 900, "{}", acc.total()); + assert_eq!(layers.held(), 600, "the costly layers stay"); + } + + /// A holder that makes again what it let go of is kept longer: its items are worth more + /// while it thrashes. + #[test] + fn a_thrashing_holder_is_protected() { + let cheap = Fake::new("cheap", &[(50 * S, 300, 1_000), (50 * S, 300, 1_000)]); + let other = Fake::new("other", &[(50 * S, 300, 2_000), (50 * S, 300, 2_000)]); + let (acc, _held) = accountant(1000, &[&cheap, &other]); + *cheap.refills.lock().unwrap() += 3; + acc.balance(); + assert_eq!(cheap.held(), 600, "thrashing: kept"); + assert_eq!(other.held(), 300); + } + + /// One holder alone may fill the whole budget: no holder has a share of its own (#3298: a + /// workload of footage only was held to the Footage Frame Cache). + #[test] + fn one_holder_may_use_the_whole_budget() { + let frames = Fake::new("footage frames", &[]); + let layers = Fake::new("layer cache", &[]); + let (acc, _held) = accountant(1000, &[&frames, &layers]); + for i in 0..10 { + frames.push(i * S, 100, 2_000); + } + acc.balance(); + assert_eq!(frames.held(), 1000); + } + + /// Growth within the balance interval still balances once it passes a part of the budget: + /// a burst of large inserts can't run far past the budget before the next interval. + #[test] + fn a_burst_of_growth_balances_at_once() { + let frames = Fake::new("footage frames", &[]); + let (acc, _held) = accountant(1600, &[&frames]); + acc.balance(); + // (within the interval of the balance just run) + for i in 0..10 { + frames.push(i * S, 200, 2_000); + acc.note_growth(200); + } + assert!(frames.held() <= 1600 + 200, "{}", frames.held()); + } + + /// Holders that went away are forgotten; no budget means nothing is freed. + #[test] + fn holders_are_held_weakly() { + let acc = Accountant::new(10); + { + let gone = Fake::new("gone", &[(0, 500, 1)]); + acc.register(&holder(&gone)); + } + assert_eq!(acc.total(), 0); + let free = Accountant::default(); + let kept = Fake::new("kept", &[(0, 500, 1)]); + free.register(&holder(&kept)); + free.balance(); + assert_eq!(kept.held(), 500); + } + + /// The layer cache as a holder: its least recently used buffer goes first, and a buffer + /// asked for again after the accountant let it go counts as a refill. + #[test] + fn the_layer_cache_is_trimmed_and_tells_refills() { + use effectcraft_effects::Buf; + use effectcraft_raster::Image; + let cache = Arc::new(crate::cache::LayerCache::new(1 << 30)); + let one = 8 * 8 * std::mem::size_of::(); + for k in 0..4u64 { + cache.insert(k, Arc::new(Buf { img: Image::new(8, 8), offset: [0.0; 2], scale: 1.0 }), Default::default()); + } + let acc = Accountant::new(2 * one); + let layers: Arc = cache.clone(); + acc.register(&layers); + acc.balance(); + assert!(layers.bytes() <= (2.0 * one as f64 * TRIM_TO) as usize, "{}", layers.bytes()); + assert!(cache.get(0).is_none(), "the oldest went first"); + assert_eq!(layers.refills(), 1, "asked for again after it was let go of"); + let next = layers.oldest().unwrap(); + assert!(next.cost_us > 0 && next.bytes == one, "{next:?}"); + } + + /// Halving a full budget (Reduce Cache Size When System Is Low on Memory) frees thousands of + /// items in one balance, on the thread that inserted last: each step must be cheap (the + /// layer cache keeps its buffers ordered by use instead of looking for the oldest). + #[test] + fn halving_a_full_budget_is_quick() { + use effectcraft_effects::Buf; + use effectcraft_raster::Image; + let cache = Arc::new(crate::cache::LayerCache::new(1 << 40)); + for k in 0..5000u64 { + cache.insert(k, Arc::new(Buf { img: Image::new(8, 8), offset: [0.0; 2], scale: 1.0 }), Default::default()); + } + let frames = Fake::new("footage frames", &[]); + for i in 0..5000 { + frames.push(i, 1024, 2_000); + } + let acc = Accountant::new(usize::MAX); + let held: Vec> = vec![cache.clone(), holder(&frames)]; + for h in &held { + acc.register(h); + } + let full = acc.total(); + let t = web_time::Instant::now(); + acc.set_budget(full / 2); + let took = t.elapsed(); + eprintln!("halving {full} bytes of 10000 items took {took:?}"); + assert!(acc.total() <= (full as f64 / 2.0 * TRIM_TO) as usize + 1024); + assert!(took < std::time::Duration::from_secs(2), "{took:?}"); + } + + /// A holder that lowers the accountant's budget the first time it is asked to drop an item + /// (another thread setting a lower budget while a balance runs). + struct Lowering { + inner: Arc, + acc: std::sync::OnceLock>, + to: usize, + done: AtomicBool, + } + + impl MemoryHolder for Lowering { + fn name(&self) -> &'static str { + "lowering" + } + fn bytes(&self) -> usize { + self.inner.held() + } + fn oldest(&self) -> Option { + self.inner.oldest() + } + fn drop_oldest(&self) -> usize { + if !self.done.swap(true, Ordering::SeqCst) + && let Some(acc) = self.acc.get() + { + acc.set_budget(self.to); + } + self.inner.drop_oldest() + } + } + + /// #3301 review: a budget lowered while a balance runs is kept: the running balance runs + /// again with it (it was skipped, and the caches stayed over the new budget). + #[test] + fn a_budget_lowered_during_a_balance_is_kept() { + let items: Vec<(u64, usize, u64)> = (0..20).map(|i| (i * S, 100, 1_000)).collect(); + let lowering = Arc::new(Lowering { inner: Fake::new("frames", &items), acc: std::sync::OnceLock::new(), to: 500, done: AtomicBool::new(false) }); + let acc = Arc::new(Accountant::with_clock(1900, at_100s)); + let _ = lowering.acc.set(acc.clone()); + let held: Arc = lowering.clone(); + acc.register(&held); + acc.balance(); + assert_eq!(acc.budget(), 500); + assert!(acc.total() <= 450, "{}", acc.total()); + } + + /// #3301 review: a holder that panicked in a balance poisons its lock; balancing goes on + /// (it stopped for good), and growth still balances. + #[test] + fn a_poisoned_balance_lock_does_not_stop_balancing() { + let frames = Fake::new("frames", &[]); + let (acc, _held) = accountant(1000, &[&frames]); + let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let mut g = acc.balancing.lock().unwrap(); + *g = None; + std::panic::resume_unwind(Box::new("a holder panicked")); + })); + assert!(poisoned.is_err() && acc.balancing.is_poisoned()); + for i in 0..12 { + frames.push(i * S, 100, 1_000); + } + // (a small growth: no burst; the last balance is long ago) + acc.note_growth(1); + assert!(frames.held() <= 900, "growth balanced: {}", frames.held()); + for i in 12..20 { + frames.push(i * S, 100, 1_000); + } + acc.balance(); + assert!(frames.held() <= 900, "{}", frames.held()); + } + + /// #3301 review: a balance asked for while `note_growth` held the lock to read the time + /// (it found the lock busy and left the work to the holder) is served by `note_growth`. + #[test] + fn a_balance_asked_for_during_a_growth_check_is_served() { + let frames = Fake::new("frames", &[]); + let (acc, _held) = accountant(1000, &[&frames]); + acc.balance(); + for i in 0..12 { + frames.push(i * S, 100, 1_000); + } + // Just balanced (recent), a small growth (no burst), and a balance left pending. + *acc.balancing.lock().unwrap() = Some(web_time::Instant::now()); + acc.requested.store(true, Ordering::SeqCst); + acc.note_growth(1); + assert!(frames.held() <= 900, "{}", frames.held()); + } + + static PROCESS_NOW: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + static PROCESS_CLOCK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(100_000_000); + fn process_now() -> Option { + Some(PROCESS_NOW.load(Ordering::SeqCst)) + } + fn process_clock() -> u64 { + PROCESS_CLOCK.load(Ordering::SeqCst) + } + /// (the process-memory tests share the statics above: one at a time) + static PROCESS_SERIAL: Mutex<()> = Mutex::new(()); + + /// #3301: memory nobody accounts for (GPU staging, effect buffers, fragmentation): with the + /// caches within their budget but the process over its purge limit, the caches give way by + /// what it is over, least valuable first; a reading that stays high (freed memory not shown + /// yet) doesn't empty them; over the hard limit the protected items go too. + #[test] + fn the_process_memory_over_its_limit_trims_the_caches() { + let _serial = PROCESS_SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + let frames = Fake::new("frames", &[]); + for i in 0..10 { + frames.push(i * S, 100, 1_000); + } + let acc = Accountant::with_clock(10_000, process_clock); + let held: Arc = frames.clone(); + acc.register(&held); + // Under its purge limit (2000): nothing goes. + PROCESS_NOW.store(1_500, Ordering::SeqCst); + acc.set_process_memory(process_now, 2_000, 3_000); + assert_eq!(frames.held(), 1000, "within the budget and the limit"); + // 2500 measured, down to the trim line under the limit (1800): 700 go. + PROCESS_CLOCK.fetch_add(PROCESS_READ_EVERY, Ordering::SeqCst); + PROCESS_NOW.store(2_500, Ordering::SeqCst); + acc.balance(); + assert_eq!(frames.held(), 300, "the caches gave way for the process"); + // The reading stays high (the memory not handed back yet), for a minute: what was freed + // counts, the caches are not drained. + for _ in 0..240 { + PROCESS_CLOCK.fetch_add(PROCESS_READ_EVERY, Ordering::SeqCst); + acc.balance(); + } + assert_eq!(frames.held(), 300, "the same reading doesn't drain the caches"); + // Read at most every 250 ms: a higher reading within that waits. + PROCESS_NOW.store(2_600, Ordering::SeqCst); + acc.balance(); + assert_eq!(frames.held(), 300); + // 100 more than last time: the caches give way by that. + PROCESS_CLOCK.fetch_add(PROCESS_READ_EVERY, Ordering::SeqCst); + acc.balance(); + assert_eq!(frames.held(), 200, "grown by 100: 100 more go"); + // Under the limit again, then over: counted afresh. + PROCESS_CLOCK.fetch_add(PROCESS_READ_EVERY, Ordering::SeqCst); + PROCESS_NOW.store(1_000, Ordering::SeqCst); + acc.balance(); + PROCESS_CLOCK.fetch_add(PROCESS_READ_EVERY, Ordering::SeqCst); + PROCESS_NOW.store(2_050, Ordering::SeqCst); + acc.balance(); + // (250 over the trim line, with nothing counted as freed: the 200 held go) + assert_eq!(frames.held(), 0, "counted afresh"); + } + + /// #3301: frames a playing preview shows next (protected) keep the caches over the budget by + /// at most a tenth of it while other items can go instead, and go once nothing else can or + /// past that overage; past the process's hard limit no overage is allowed. + #[test] + fn protected_items_go_last_and_only_a_bounded_way_over() { + let _serial = PROCESS_SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + let preview = Fake::new("preview", &[]); + for i in 0..4 { + preview.items.lock().unwrap().push_back(Candidate { used: i * S, bytes: 100, cost_us: 1, protected: true }); + } + let footage = Fake::new("footage", &[(99 * S, 300, 1_000_000)]); + let acc = Accountant::with_clock(usize::MAX, process_clock); + let held: Vec> = vec![holder(&preview), holder(&footage)]; + for h in &held { + acc.register(h); + } + // 700 held, budget 500 (target 450, overage 50): the footage goes though worth more. + acc.set_budget(500); + assert_eq!((preview.held(), footage.held()), (400, 0)); + // Budget 300 (target 270, overage 30): nothing else left, the preview frames go down to + // the overage over the target. + acc.set_budget(300); + assert_eq!(preview.held(), 300, "over the target by at most the overage"); + // Past the process's hard limit: no overage. + PROCESS_CLOCK.fetch_add(PROCESS_READ_EVERY, Ordering::SeqCst); + PROCESS_NOW.store(10_000, Ordering::SeqCst); + acc.set_process_memory(process_now, 1_000, 2_000); + assert!(preview.held() <= 200, "{}", preview.held()); + } + + static ASKED: AtomicUsize = AtomicUsize::new(0); + + fn ram_says() -> Option { + ASKED.fetch_add(1, Ordering::SeqCst); + Some(300) + } + + fn ram_unknown() -> Option { + ASKED.fetch_add(1, Ordering::SeqCst); + None + } + + /// #3749: a request for a file's planes may take the fixed floor, or the system's memory + /// when that is more: the system is asked only for a request over the floor, once. + #[test] + fn a_request_over_the_floor_is_limited_by_the_systems_memory() { + let _serial = PROCESS_SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + set_decode_limit(None); + set_decode_limit_source(Some(ram_says)); + ASKED.store(0, Ordering::SeqCst); + // Under the floor: nobody is asked. + assert_eq!(decode_limit(100, 50), 100); + assert_eq!(ASKED.load(Ordering::SeqCst), 0, "a request under the floor reads no memory"); + // Over it: the system's 300, asked once. + assert_eq!(decode_limit(100, 200), 300); + assert_eq!(decode_limit(100, 250), 300); + assert_eq!(ASKED.load(Ordering::SeqCst), 1, "asked once, then kept"); + // A smaller figure than the floor never lowers it. + set_decode_limit(Some(40)); + assert_eq!(decode_limit(100, 200), 100); + // The session's figure replaces the asked one. + set_decode_limit(Some(900)); + assert_eq!(decode_limit(100, 200), 900); + // Unknown memory leaves the floor; a reading that failed once is tried once more, then + // not asked again (and what is not known is never kept as the floor). + set_decode_limit(None); + set_decode_limit_source(Some(ram_unknown)); + ASKED.store(0, Ordering::SeqCst); + for _ in 0..4 { + assert_eq!(decode_limit(100, 200), 100); + } + assert_eq!(ASKED.load(Ordering::SeqCst), 2, "a failed reading is tried twice"); + // A source that answers later is not shut out by the floor kept earlier. + set_decode_limit_source(Some(ram_says)); + assert_eq!(decode_limit(7, 200), 300, "a limit is not tied to the floor of an earlier request"); + // The generation tells that the limit changed. + let before = decode_limit_generation(); + set_decode_limit(Some(300)); + assert_eq!(decode_limit_generation(), before, "the same figure is no change"); + set_decode_limit(Some(500)); + assert_ne!(decode_limit_generation(), before); + set_decode_limit(None); + set_decode_limit_source(None); + } + + /// The session sets its figure while the system is being read (the reading takes up to a + /// second). + fn ram_says_after_the_session_set_its_figure() -> Option { + set_decode_limit(Some(12)); + Some(48) + } + + /// #3750 review: a limit the session sets while the system's memory is being read stays; + /// the older reading does not replace it. + #[test] + fn a_limit_set_during_the_reading_is_not_replaced_by_it() { + let _serial = PROCESS_SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + set_decode_limit(None); + set_decode_limit_source(Some(ram_says_after_the_session_set_its_figure)); + assert_eq!(decode_limit(1, 100), 12, "the session's figure set during the reading stays"); + assert_eq!(decode_limit(1, 100), 12); + set_decode_limit(None); + set_decode_limit_source(None); + } + + /// #3750 review: a reading that gave no answer makes earlier refusals for size out of date, + /// so the second reading is asked for by the next request instead of being shut out. + #[test] + fn a_reading_without_answer_makes_earlier_refusals_out_of_date() { + let _serial = PROCESS_SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + set_decode_limit(None); + set_decode_limit_source(Some(ram_unknown)); + let before = decode_limit_generation(); + assert_eq!(decode_limit(100, 200), 100); + let after_first = decode_limit_generation(); + assert_ne!(after_first, before, "a refusal made before the failed reading is out of date"); + assert_eq!(decode_limit(100, 200), 100); + let after_second = decode_limit_generation(); + assert_ne!(after_second, after_first); + // No reading is left: the generation stays, and a refusal is kept. + assert_eq!(decode_limit(100, 200), 100); + assert_eq!(decode_limit_generation(), after_second, "no reading, no change"); + set_decode_limit(None); + set_decode_limit_source(None); + } +} diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index a57771363..da97f5ca6 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -1149,7 +1149,9 @@ impl<'a> Renderer<'a> { let proxy = self.proxy_for(item); let pf = proxy.unwrap_or(f); let size = self.reduced_size(f.width, f.height).filter(|_| proxy.is_none()); - let img = self.footage_frame(ctx, layer, item, pf, lt, size)?; + // Only the rows a viewer region of interest shows of it (#3271). + let rows = proxy.is_none().then(|| self.footage_rows(ctx, layer, f)).flatten(); + let img = self.footage_frame_in(ctx, layer, item, pf, lt, size, rows)?; Some((img, pf)) } @@ -1192,6 +1194,11 @@ impl<'a> Renderer<'a> { return None; } } + // (some rows of the frame for a region of interest, #3271: a part of the picture, never + // shared as the whole) + if self.proxy_for(item).is_none() && self.footage_rows(ctx, layer, f).is_some() { + return None; + } let (img, _) = self.footage_picture_of(ctx, layer, item, f)?; let FootageLayout::Native { scale } = self.footage_layout(&img, f.width, f.height) else { return None }; // `layer_input`'s rebase into effect space (`Buf::rebase` of a buffer at the origin). @@ -1220,6 +1227,76 @@ impl<'a> Renderer<'a> { /// `t` falls between frames (footage rate ≠ comp rate, time stretch, time remapping). /// `size`: a plain frame may come resampled to it ([`FootageSource::frame_at_size`]). fn footage_frame(&self, ctx: &EvalCtx, layer: &Layer, item: ItemId, f: &Footage, t: Tick, size: Option<(u32, u32)>) -> Option> { + self.footage_frame_in(ctx, layer, item, f, t, size, None) + } + + /// The footage rows a top-level region of interest shows of footage layer `layer` (`f`), at + /// full resolution, grown by what reaches into them: the layer's resampling (wider at a + /// reduced scale) and its effects' declared margins (#3271). `None` (the whole frame) without + /// a region, when the rows are all of it, or when anything may read the layer's other pixels: + /// a 3D layer, motion blur, frame blending, fields, layer styles, an effect that doesn't + /// declare its margin, or anything in the comp that reads layers' pixels (an effect's layer + /// parameter, an expression). + pub(crate) fn footage_rows(&self, ctx: &EvalCtx, layer: &Layer, f: &Footage) -> Option<(i64, i64)> { + // (a caller that needs the whole layer: the Layer panel, sampleImage, effect inputs) + let roi = self.opts.roi.filter(|_| self.top && !self.whole_raster)?; + // (a collapsed precomp's layers are placed through the outer layers too, and an + // adjustment layer's footprint is keyed whole: the whole frame there) + if self.outer.is_some() || self.collapse3d.is_some() || self.depth > 0 || layer.switches.adjustment { + return None; + } + if layer.switches.three_d + || f.fields != effectcraft_project::FieldOrder::Off + || !matches!(f.kind, FootageKind::Still | FootageKind::Sequence) + || self.mb_on(ctx, layer) + || frame_blend_mode(ctx, layer) != FrameBlend::Off + || styles::group(layer).is_some() + { + return None; + } + let fx_margin = effects_margin(ctx, layer)?; + // (a source that reads whole frames anyway: the whole frame, which the layer cache keeps) + if comp_reads_pixels(ctx) || !self.footage.reads_rows(f, ctx.source_time(layer)) { + return None; + } + // (the transform the compositor places the 2D layer with: a 3D parent's matrix projected + // to the comp's plane) + let inv = ctx.layer_to_comp(layer).0.inverse()?; + let ys: Vec = [[roi[0], roi[1]], [roi[0] + roi[2], roi[1]], [roi[0], roi[1] + roi[3]], [roi[0] + roi[2], roi[1] + roi[3]]] + .iter() + .map(|p| inv.apply(effectcraft_geom::vec2(p[0], p[1])).y) + .collect(); + let (lo, hi) = ys.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), y| (lo.min(*y), hi.max(*y))); + if !lo.is_finite() || !hi.is_finite() { + return None; + } + // The warp samples its source with point taps (bilinear, bicubic: ±2 source pixels), so + // the rows reach 2 buffer pixels past the region's mapped centres (a reduced buffer's + // pixels are 1/scale footage rows), plus the region's rounding to output pixels: one + // output pixel is `k / scale` footage rows, `k` the footage rows per comp pixel. + let s = self.opts.scale.max(1e-3); + let k = [effectcraft_geom::vec2(1.0, 0.0), effectcraft_geom::vec2(0.0, 1.0)].iter().map(|v| inv.apply_vec(*v).length()).fold(1.0f64, f64::max); + if !k.is_finite() { + return None; + } + let margin = 2.0 + (2.0 / s).ceil() + (2.0 * k / s).ceil() + fx_margin.ceil(); + let h = i64::from(f.height); + let (y0, y1) = (((lo - margin).floor() as i64).clamp(0, h), ((hi + margin).ceil() as i64).clamp(0, h)); + (y0 > 0 || y1 < h).then_some((y0, y1.max(y0))) + } + + /// [`Renderer::footage_frame`] of only the rows `rows` (see [`Renderer::footage_rows`]). + #[allow(clippy::too_many_arguments)] + fn footage_frame_in( + &self, + ctx: &EvalCtx, + layer: &Layer, + item: ItemId, + f: &Footage, + t: Tick, + size: Option<(u32, u32)>, + rows: Option<(i64, i64)>, + ) -> Option> { // Interpret Footage ▸ Separate Fields: each field is a frame at twice the rate. if f.fields != effectcraft_project::FieldOrder::Off && matches!(f.kind, FootageKind::Video | FootageKind::Sequence) { let field_rate = FrameRate::new(f.frame_rate.num * 2, f.frame_rate.den); @@ -1233,7 +1310,11 @@ impl<'a> Renderer<'a> { // Interpretation is per pixel but not linear: it runs on the frame before resampling. let per_pixel = f.invert_alpha || f.linear_light_applies(); let size = size.filter(|_| !(per_pixel || f.cineon_applies())); - let img = self.footage_frame_raw(ctx, layer, item, f, t, size)?; + let img = match rows { + // (no frame blending, no fields: see `footage_rows`) + Some(rows) => self.read(|| self.footage.frame_rows(item, f, t, size, self.pipe.float_curve(f), rows)).map(|img| cineon_frame(img, f))?, + None => self.footage_frame_raw(ctx, layer, item, f, t, size)?, + }; if per_pixel { Some(Arc::new(interpret_pixels(&img, f, self.pipe.linear_footage_space(f)))) } else { Some(img) } } @@ -1271,6 +1352,17 @@ impl<'a> Renderer<'a> { self.read(|| self.footage.frame_with(item, f, t, size, float)).map(|img| cineon_frame(img, f)) } + /// Is footage layer `layer` read in part ([`Renderer::footage_rows`]). + pub(crate) fn reads_footage_rows(&self, ctx: &EvalCtx, layer: &Layer) -> bool { + let LayerSource::Footage { item } = &layer.source else { return false }; + let item = ctx.media_item(layer, *item); + if self.opts.roi.is_none() || !self.top || self.proxy_for(item).is_some() { + return false; + } + let Some(ItemKind::Footage(f)) = ctx.project.item(item).map(|it| &it.kind) else { return false }; + self.footage_rows(ctx, layer, f).is_some() + } + /// A frame-blended footage frame at source time `t` when one comp frame runs through many /// source frames: the average of the source frames the comp frame spans, each weighted by /// the share of it the span covers ([`super::frames::mix_window`]). Both Frame Mix and @@ -1435,6 +1527,9 @@ impl<'a> Renderer<'a> { } return Some((b, key, files)); } + // A footage layer read in part (a region of interest, #3271) isn't kept: its key names + // the whole layer (a whole buffer kept before is used above). + let key = key.filter(|_| !self.reads_footage_rows(ctx, layer)); let (buf, files) = self.recorded(key, |r| { // (what expressions read while it is made, at shutter times too, goes to its files) let ctx = &r.with_reads(ctx); @@ -1456,6 +1551,8 @@ impl<'a> Renderer<'a> { fn whole_layer_input(&self, ctx: &EvalCtx, layer: &Layer, effects: usize) -> Option> { let key = self.cache.and_then(|_| cache::input_key(ctx, layer, self.raster_scale(ctx, layer), self.opts.draft, self.mb_on(ctx, layer), effects)); + // (a footage layer read in part is never kept under a whole layer's key, #3271) + let key = key.filter(|_| !self.reads_footage_rows(ctx, layer)); let key = self.content_key(ctx, layer, self.clipped_key(ctx, layer, key)); if let Some((b, _)) = self.cached(key) { return Some(b); @@ -1474,6 +1571,33 @@ impl<'a> Renderer<'a> { } } +/// How far the enabled effects of `layer` reach around a pixel (layer pixels), `None` when one +/// doesn't declare it (`effectcraft_effects::pixel_margin`). +fn effects_margin(ctx: &EvalCtx, layer: &Layer) -> Option { + if !layer.switches.effects { + return Some(0.0); + } + let mut most: f64 = 0.0; + for g in layer.effects().into_iter().flat_map(|fx| fx.groups()).filter(|g| g.enabled) { + let effectcraft_project::GroupKind::Effect { effect } = &g.kind else { return None }; + let params = effectcraft_effects::flatten_params(g, &mut |p| ctx.value(layer, p)); + most = most.max(effectcraft_effects::pixel_margin(effect, ¶ms)?); + } + Some(most) +} + +/// Does anything in the comp read layers' pixels where it likes: an enabled effect with a layer +/// parameter set, or an expression (`sampleImage`). +fn comp_reads_pixels(ctx: &EvalCtx) -> bool { + fn group(g: &effectcraft_project::PropGroup, effects: bool) -> bool { + g.children.iter().any(|c| match c { + effectcraft_project::Node::Prop(p) => p.has_expression() || (effects && matches!(p.value, effectcraft_keyframe::Value::Layer(Some(_)))), + effectcraft_project::Node::Group(sub) => group(sub, effects || matches!(sub.kind, effectcraft_project::GroupKind::Effect { .. })), + }) + } + ctx.comp.layers.iter().any(|l| group(&l.props, false)) +} + /// Snap cells can be finer than 1/16 unit: preserve every coordinate bit so visible /// clips cannot collide with another cell or the empty behind-camera raster. pub(crate) fn raster_clip_key(key: u64, clip: kurbo::Rect) -> u64 { diff --git a/crates/render/src/tests/footage_size.rs b/crates/render/src/tests/footage_size.rs index 6c59f3fb2..5dd31363a 100644 --- a/crates/render/src/tests/footage_size.rs +++ b/crates/render/src/tests/footage_size.rs @@ -107,6 +107,206 @@ fn still_layers_are_cached_across_times_and_movies_are_not() { } } +/// #3271: an OpenEXR sequence's layer is cached per frame (keyed by its source time): the same +/// frame again is served from the layer cache, another frame has another key. Other sequences +/// stay in the media pool only. +#[test] +fn exr_sequence_layers_are_cached_per_frame() { + for (ext, fetches) in [("exr", 1), ("png", 2)] { + let (mut p, cid) = project(BitDepth::Bpc8, false); + let Some(LayerSource::Footage { item }) = p.comp(cid).map(|c| c.layers[0].source.clone()) else { panic!("footage layer") }; + if let Some(ItemKind::Footage(f)) = p.item_mut(item).map(|it| &mut it.kind) { + f.kind = FootageKind::Sequence; + f.sequence = (1..=30).map(|i| format!("/shot/plate_{i:04}.{ext}")).collect(); + f.path = f.sequence[0].clone(); + } + let key = |t: f64| { + let c = p.comp(cid).unwrap(); + crate::cache::layer_key(&crate::EvalCtx::new(&p, cid, c, Tick::from_seconds_f64(t)), &c.layers[0], 0.5, false, false) + }; + assert_eq!(key(0.0).is_some(), ext == "exr", "{ext}"); + if ext == "exr" { + assert_ne!(key(0.0), key(0.1), "another frame, another key"); + assert_eq!(key(0.0), key(0.01), "the same frame"); + } + let cache = crate::LayerCache::default(); + let src = Clip { sizes: Some(Mutex::default()) }; + let opts = RenderOpts { scale: 0.5, ..Default::default() }; + for _ in 0..2 { + let mut r = Renderer::new(&p, &src, opts); + r.cache = Some(&cache); + r.comp_frame(cid, Tick::ZERO); + } + assert_eq!(src.sizes.unwrap().into_inner().unwrap().len(), fetches, "{ext}"); + } +} + +/// #3271 review: with a viewer region of interest, a still from a source that reads whole frames +/// anyway (not by rows) is asked for whole and stays in the layer cache: a second render reads +/// nothing. A source that reads rows is asked for only the rows the region shows. +#[test] +fn a_source_that_reads_whole_frames_keeps_the_layer_cached_under_a_region() { + struct Counting { + reads: Mutex>>, + by_rows: bool, + } + impl FootageSource for Counting { + fn frame(&self, item: ItemId, f: &Footage, t: Tick) -> Option> { + self.reads.lock().unwrap().push(None); + Clip { sizes: None }.frame(item, f, t) + } + fn frame_rows(&self, item: ItemId, f: &Footage, t: Tick, _: Option<(u32, u32)>, _: crate::FloatCurve, rows: (i64, i64)) -> Option> { + self.reads.lock().unwrap().push(Some(rows)); + Clip { sizes: None }.frame(item, f, t) + } + fn reads_rows(&self, _: &Footage, _: Tick) -> bool { + self.by_rows + } + } + let (mut p, cid) = project(BitDepth::Bpc8, false); + let Some(LayerSource::Footage { item }) = p.comp(cid).map(|c| c.layers[0].source.clone()) else { panic!("footage layer") }; + if let Some(ItemKind::Footage(f)) = p.item_mut(item).map(|it| &mut it.kind) { + f.kind = FootageKind::Still; + f.path = "/still.png".into(); + } + let opts = RenderOpts { roi: Some([0.0, 0.0, 96.0, 10.0]), ..Default::default() }; + for by_rows in [false, true] { + let src = Counting { reads: Mutex::default(), by_rows }; + let cache = crate::LayerCache::default(); + for _ in 0..2 { + let mut r = Renderer::new(&p, &src, opts); + r.cache = Some(&cache); + r.comp_frame(cid, Tick::ZERO); + } + let reads = src.reads.into_inner().unwrap(); + if by_rows { + assert_eq!(reads.len(), 2, "by rows, each render: {reads:?}"); + assert!(reads.iter().all(|r| r.is_some_and(|(y0, y1)| y0 == 0 && y1 < 54)), "{reads:?}"); + } else { + assert_eq!(reads, [None], "whole, once: the layer cache keeps it"); + } + } +} + +/// #3301 merge with #3333: under a viewer region of interest, a footage layer read by rows is +/// never offered as the shared decoded picture (the GPU would upload a part of the frame as the +/// whole); without a region it is. +#[test] +fn a_footage_layer_read_by_rows_is_not_the_shared_picture() { + struct Rows; + impl FootageSource for Rows { + fn frame(&self, item: ItemId, f: &Footage, t: Tick) -> Option> { + Clip { sizes: None }.frame(item, f, t) + } + fn frame_rows(&self, item: ItemId, f: &Footage, t: Tick, _: Option<(u32, u32)>, _: crate::FloatCurve, _: (i64, i64)) -> Option> { + Clip { sizes: None }.frame(item, f, t) + } + fn reads_rows(&self, _: &Footage, _: Tick) -> bool { + true + } + } + let (mut p, cid) = project(BitDepth::Bpc32, false); + let Some(LayerSource::Footage { item }) = p.comp(cid).map(|c| c.layers[0].source.clone()) else { panic!("footage layer") }; + if let Some(ItemKind::Footage(f)) = p.item_mut(item).map(|it| &mut it.kind) { + f.kind = FootageKind::Still; + f.path = "/still.exr".into(); + } + let comp = p.comp(cid).unwrap(); + let ctx = crate::EvalCtx::new(&p, cid, comp, Tick::ZERO); + let whole = Renderer::new(&p, &Rows, RenderOpts::default()); + assert!(whole.footage_picture(&ctx, &comp.layers[0]).is_some(), "no region: the shared picture"); + let region = Renderer::new(&p, &Rows, RenderOpts { roi: Some([0.0, 0.0, 96.0, 10.0]), ..Default::default() }); + let Some(ItemKind::Footage(f)) = p.item(item).map(|it| &it.kind) else { panic!("footage") }; + assert!(region.footage_rows(&ctx, &comp.layers[0], f).is_some(), "read by rows"); + assert!(region.footage_picture(&ctx, &comp.layers[0]).is_none(), "a part of the frame is never shared"); + // #3301 review: a caller that needs the whole layer (Layer panel, sampleImage, effect inputs) + // reads the whole frame under a region too. + let whole_layer = Renderer { whole_raster: true, ..region }; + assert!(whole_layer.footage_rows(&ctx, &comp.layers[0], f).is_none(), "whole layer: the whole frame"); +} + +/// #3750 review: a 2D footage layer under a 3D parent (a null turned 60° about X) is placed by +/// its world matrix projected to the comp's plane, which halves its height: the comp's rows 0..10 +/// show its rows 0..20, and those are read (inverting the unprojected matrix gave rows 0..5). +#[test] +fn rows_under_a_3d_parent_follow_the_projected_layer() { + struct Rows; + impl FootageSource for Rows { + fn frame(&self, item: ItemId, f: &Footage, t: Tick) -> Option> { + Clip { sizes: None }.frame(item, f, t) + } + fn frame_rows(&self, item: ItemId, f: &Footage, t: Tick, _: Option<(u32, u32)>, _: crate::FloatCurve, _: (i64, i64)) -> Option> { + Clip { sizes: None }.frame(item, f, t) + } + fn reads_rows(&self, _: &Footage, _: Tick) -> bool { + true + } + } + use effectcraft_keyframe::Value; + let (mut p, cid) = project(BitDepth::Bpc32, false); + let Some(LayerSource::Footage { item }) = p.comp(cid).map(|c| c.layers[0].source.clone()) else { panic!("footage layer") }; + if let Some(ItemKind::Footage(f)) = p.item_mut(item).map(|it| &mut it.kind) { + f.kind = FootageKind::Still; + f.path = "/still.exr".into(); + } + let comp = p.comp(cid).unwrap().clone(); + let mut null = build::layer(&mut p, &comp, "Null", LayerSource::Null, (100, 100), None); + null.switches.three_d = true; + null.props.prop_mut("transform/anchor").unwrap().value = Value::Vec3([0.0, 0.0, 0.0]); + null.props.prop_mut("transform/position").unwrap().value = Value::Vec3([0.0, 0.0, 0.0]); + null.props.prop_mut("transform/rotationX").unwrap().value = Value::Scalar(60.0); + let mut l = comp.layers[0].clone(); + // (the layer's own transform is the identity: its anchor at its position) + l.props.prop_mut("transform/position").unwrap().value = Value::Vec3([48.0, 27.0, 0.0]); + l.props.prop_mut("transform/anchor").unwrap().value = Value::Vec3([48.0, 27.0, 0.0]); + l.parent = Some(null.id); + p.comp_mut(cid).unwrap().layers = vec![l, null].into(); + let comp = p.comp(cid).unwrap(); + let ctx = crate::EvalCtx::new(&p, cid, comp, Tick::ZERO); + let region = Renderer::new(&p, &Rows, RenderOpts { roi: Some([0.0, 0.0, 96.0, 10.0]), ..Default::default() }); + let Some(ItemKind::Footage(f)) = p.item(item).map(|it| &it.kind) else { panic!("footage") }; + let rows = region.footage_rows(&ctx, &comp.layers[0], f).expect("read by rows"); + assert!(rows.0 == 0 && rows.1 >= 20, "rows 0..20 and the warp's reach: {rows:?}"); +} + +/// #3271 review: a render's channel reads (an effect's EXR channels) are called off with the +/// render like its frame reads: they run under the render's cancel flag (a decode stops between +/// batches), and once it is set they don't start. +#[test] +fn channel_reads_are_called_off_with_the_render() { + use std::sync::atomic::{AtomicBool, Ordering}; + thread_local! { + static UNDER: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + #[derive(Default)] + struct Channels { + reads: Mutex>, + } + impl FootageSource for Channels { + fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option> { + None + } + fn cancellable(&self, _: &Arc, f: &mut dyn FnMut()) { + UNDER.with(|u| u.set(true)); + f(); + UNDER.with(|u| u.set(false)); + } + fn aux_for(&self, _: ItemId, f: &Footage, _: Tick, _: &effectcraft_raster::channels3d::AuxNeed) -> Option> { + self.reads.lock().unwrap().push(UNDER.with(|u| u.get())); + Some(Arc::new(effectcraft_raster::AuxChannels::new(f.width, f.height, 1.0))) + } + } + let inner = Channels::default(); + let cancel = Arc::new(AtomicBool::new(false)); + let src = crate::CancellableFootage { inner: &inner, cancel: cancel.clone() }; + let f = Footage { width: 4, height: 2, ..Default::default() }; + let need = effectcraft_raster::channels3d::AuxNeed::Lookups(vec![]); + assert!(src.aux_for(ItemId(1), &f, Tick::ZERO, &need).is_some()); + cancel.store(true, Ordering::Relaxed); + assert!(src.aux_for(ItemId(1), &f, Tick::ZERO, &need).is_none(), "called off"); + assert_eq!(*inner.reads.lock().unwrap(), [true], "read once, under the render's flag"); +} + /// [`Clip`] that also keeps its frames as 8-bit levels, counting the times it's asked for them. struct Clip8 { asked: std::sync::atomic::AtomicUsize, diff --git a/crates/ui-egui/src/a11y.rs b/crates/ui-egui/src/a11y.rs index b8f88ae23..b33c8ac05 100644 --- a/crates/ui-egui/src/a11y.rs +++ b/crates/ui-egui/src/a11y.rs @@ -103,6 +103,17 @@ pub(crate) fn check_box(r: &Response, label: &str, checked: bool, enabled: bool) }); } +/// A push button that is one of a set of choices (a view-layout button): `pressed` is whether it is +/// the current one, exposed as the toggled state. `description` says what the set is. +pub(crate) fn choice_button(r: &Response, label: &str, description: &str, pressed: bool) { + node(r, |n| { + n.set_role(Role::Button); + n.set_label(label); + n.set_description(description); + n.set_toggled(if pressed { Toggled::True } else { Toggled::False }); + }); +} + /// A drop-down: `label` says what it sets and `value` is what it is set to. pub(crate) fn combo_box(r: &Response, label: &str, value: &str, enabled: bool) { node(r, |n| { diff --git a/crates/ui-egui/src/app/prefs.rs b/crates/ui-egui/src/app/prefs.rs index 6fc424e01..218760337 100644 --- a/crates/ui-egui/src/app/prefs.rs +++ b/crates/ui-egui/src/app/prefs.rs @@ -23,7 +23,9 @@ impl EffectcraftApp { ctx.set_zoom_factor(p.appearance.ui_scale as f32 / 100.0); self.ui.cache_when_idle = p.previews.cache_frames_when_idle; self.ui.viewer.fast_preview = p.previews.fast_previews; - self.frames.set_budget(p.cache_budgets(self.session.sys_memory).preview); + // No limit of its own below the common budget on the desktop, the browser's cap there: + // the memory accountant keeps it (#3298). + self.frames.set_budget(self.session.memory_budget().caps(cfg!(target_arch = "wasm32")).preview); } /// Change settings from the UI (applied next frame and saved). diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rs index a0c2f94b5..ea4d7dbc0 100644 --- a/crates/ui-egui/src/frames.rs +++ b/crates/ui-egui/src/frames.rs @@ -172,6 +172,15 @@ impl FrameImage { fn is_gpu(&self) -> bool { matches!(self, FrameImage::Gpu(_)) } + /// Held outside the cache too (a viewer showing it): dropping the cache's entry frees + /// nothing yet. + fn held_elsewhere(&self) -> bool { + match self { + FrameImage::Cpu(i) => Arc::strong_count(i) > 1, + FrameImage::CpuF16(i) => Arc::strong_count(i) > 1, + FrameImage::Gpu(i) => Arc::strong_count(i) > 1, + } + } } /// A viewer frame: its comp's content, the frame, scale, view and render options. `revision` is @@ -263,6 +272,10 @@ struct Cached { /// (`None`: rendered without a disk cache, or elsewhere; never written from here). #[cfg_attr(target_arch = "wasm32", allow(dead_code))] since: Option, + /// When it was last shown or stored, for the memory accountant (`memory::tick`). + used: u64, + /// What rendering it took, in microseconds (a typical cost when not timed). + cost_us: u64, } /// A disk cache and its drop generation ([`DiskCache::drop_generation`]) when a render started. @@ -308,9 +321,20 @@ impl Cache { } /// [`Cache::insert`] with the source files the frame was made of and the disk cache's drop /// generation when its render started. + #[cfg(test)] fn insert_with(&mut self, k: FrameKey, img: FrameImage, files: Option>, since: Option) { + self.insert_took(k, img, files, since, None); + } + /// Keep a frame with the source files it was made of, the disk cache drop generation when its + /// render started, and what rendering it took (`None`: not timed). + fn insert_took(&mut self, k: FrameKey, img: FrameImage, files: Option>, since: Option, took: Option) { let (sz, gpu) = (img.bytes(), img.is_gpu()); - if let Some(old) = self.map.insert(k, Cached { img, files, since }) { + let cost_us = took.map_or_else( + || effectcraft_engine::render::memory::default_cost(sz, effectcraft_engine::render::memory::DEFAULT_PREVIEW_US_PER_MB), + |t| u64::try_from(t.as_micros()).unwrap_or(u64::MAX).max(1), + ); + let used = effectcraft_engine::render::memory::tick(); + if let Some(old) = self.map.insert(k, Cached { img, files, since, used, cost_us }) { self.forget(&old.img); } else { self.order.push_back(k); @@ -329,14 +353,18 @@ impl Cache { /// prefetch kept refilling while it evicted the next frames (#595). Frames of another scale /// than the one on screen go first (a zoom or resolution change). fn victim(&self) -> Option { + self.victim_of(|_| true) + } + /// [`Cache::victim`] among the frames `eligible` accepts (in the same order). + fn victim_of(&self, eligible: impl Fn(&FrameKey) -> bool) -> Option { if let Some(s) = self.scale - && let Some(i) = self.order.iter().position(|k| k.scale != s) + && let Some(i) = self.order.iter().position(|k| k.scale != s && eligible(k)) { return Some(i); } - let Some(p) = &self.playhead else { return (!self.order.is_empty()).then_some(0) }; + let Some(p) = &self.playhead else { return self.order.iter().position(&eligible) }; let mut farthest: Option<(i64, usize)> = None; - for (i, k) in self.order.iter().enumerate() { + for (i, k) in self.order.iter().enumerate().filter(|(_, k)| eligible(k)) { match p.ahead(k) { None => return Some(i), Some(d) if farthest.is_none_or(|(f, _)| d > f) => farthest = Some((d, i)), @@ -345,6 +373,11 @@ impl Cache { } farthest.map(|(_, i)| i) } + /// [`Cache::victim`] among the frames in RAM (a GPU frame's bytes are video memory) nobody + /// else holds: what the memory accountant may drop to free RAM now. + fn free_victim(&self) -> Option { + self.victim_of(|k| self.map.get(k).is_some_and(|c| !c.img.is_gpu() && !c.img.held_elsewhere())) + } /// Video memory: drop the oldest GPU frames past their own budget, frames of another scale /// than the one on screen first (a zoom or resolution change). fn evict_gpu(&mut self) { @@ -393,6 +426,9 @@ impl Cache { } /// Shown again: last in line for eviction. fn touch(&mut self, k: &FrameKey) { + if let Some(c) = self.map.get_mut(k) { + c.used = effectcraft_engine::render::memory::tick(); + } if let Some(i) = self.order.iter().rposition(|o| o == k) && let Some(k) = self.order.remove(i) { @@ -428,6 +464,45 @@ impl Cache { } } +/// The preview frames (in RAM; GPU frames have their own budget) in the common memory budget +/// (#3271, #3298): each frame is worth what rendering it took, per byte. The frame offered is +/// the one the cache would evict next ([`Cache::free_victim`]: it spares the frames a playing +/// preview shows next). +struct PreviewMemory(Arc>); + +impl effectcraft_engine::render::memory::MemoryHolder for PreviewMemory { + fn name(&self) -> &'static str { + "preview frames" + } + fn bytes(&self) -> usize { + self.0.lock().map(|c| c.bytes.saturating_sub(c.gpu_bytes)).unwrap_or(0) + } + // (only frames in RAM: dropping a GPU frame frees no RAM, and loses a viewer frame) + /// A frame a playing preview shows next is protected: the accountant lets it keep the caches + /// over the budget by a bounded amount while other items can go instead (#3301: one rendered + /// from cached layers costs little, and older footage outlived it, so the preview played into + /// live renders). A frame costs at least a typical render + /// ([`effectcraft_engine::render::memory::DEFAULT_PREVIEW_US_PER_MB`]): a quick one still + /// stands for a whole comp. + fn oldest(&self) -> Option { + use effectcraft_engine::render::memory::{Candidate, DEFAULT_PREVIEW_US_PER_MB, default_cost}; + let c = self.0.lock().ok()?; + let k = c.order.get(c.free_victim()?)?; + let f = c.map.get(k)?; + let bytes = f.img.bytes(); + let protected = c.playhead.as_ref().is_some_and(|p| p.ahead(k).is_some()); + let cost_us = f.cost_us.max(default_cost(bytes, DEFAULT_PREVIEW_US_PER_MB)); + Some(Candidate { used: f.used, bytes, cost_us, protected }) + } + fn drop_oldest(&self) -> usize { + let Ok(mut c) = self.0.lock() else { return 0 }; + let Some(old) = c.free_victim().and_then(|i| c.order.remove(i)) else { return 0 }; + let bytes = c.map.get(&old).map_or(0, |f| f.img.bytes()); + c.remove(&old); + bytes + } +} + /// What a render job needs (all cheap clones). #[derive(Clone)] pub struct RenderSource { @@ -660,6 +735,8 @@ pub fn comp_has_effects(project: &Project, comp: ItemId) -> bool { pub struct Frames { cache: Arc>, + /// The preview frames in the common memory budget (#3271), held here (registered weakly). + _memory: Arc, /// Keys queued or rendering. inflight: Arc>>, /// Pending jobs, picked by priority when a pool thread frees up (the viewer's frame first). @@ -767,8 +844,23 @@ impl Frames { let queue = Queue { idle_lanes: (0..lanes.len()).collect(), lanes: lanes.len(), gpu_limit: 1, ..Default::default() }; #[cfg(target_arch = "wasm32")] let queue = Queue::default(); + let cache = Arc::new(Mutex::new(Cache { + map: HashMap::new(), + order: VecDeque::new(), + bytes: 0, + gpu_bytes: 0, + budget: 3 << 30, + gpu_budget: GPU_BUDGET, + gpu_pressure: None, + gpu_adjusted: None, + playhead: None, + scale: None, + })); + let memory: Arc = Arc::new(PreviewMemory(cache.clone())); + effectcraft_engine::render::memory::Accountant::global().register(&memory); Frames { - cache: Arc::new(Mutex::new(Cache { map: HashMap::new(), order: VecDeque::new(), bytes: 0, gpu_bytes: 0, budget: 3 << 30, gpu_budget: GPU_BUDGET, gpu_pressure: None, gpu_adjusted: None, playhead: None, scale: None })), + cache, + _memory: memory, inflight: Arc::new(Mutex::new(HashSet::new())), queue: Arc::new(Mutex::new(queue)), #[cfg(not(target_arch = "wasm32"))] @@ -1225,6 +1317,10 @@ impl Frames { // (only with the generation its render started at, for this cache: a frame // made of a file Reload Footage dropped since holds the pixels from before) let since = c.since.as_ref().and_then(|s| s.for_cache(&dc)).filter(|s| !dc.dropped_since(files, *s))?; + // (only a frame that costs more to render again than to read back, #3301) + if !dc.pays_off(c.img.bytes(), c.cost_us) { + return None; + } let dk = disk_cache::frame_key(content, k.frame, k.scale, k.view ^ oh); let tries = written.1.get(&dk).copied().unwrap_or(0); (tries < 2 && !dc.contains(disk_cache::Kind::Frame, dk) && !dc.frame_pending(dk) && queued.insert(dk)) @@ -1857,10 +1953,13 @@ impl Worker { // and compression. Persistence still runs on this worker, using the same snapshot. let since = disk.as_ref().map(|(dc, _, since)| DiskSince::of(dc, *since)); self.finish(&job, ci.clone(), Some(files.clone()), since, t0); + let took_us = u64::try_from(t0.elapsed().as_micros()).unwrap_or(u64::MAX); // The GPU's part is done; storing it on disk is the CPU's. drop(slot); if !disk_hit && let Some((dc, k, since)) = &disk + // (only a frame that costs more to render again than to read back, #3301) + && dc.pays_off(ci.bytes(), took_us) && put_disk_frame(dc, *k, &ci, &files, self.virtual_id.as_deref(), *since) && let Some(ctx) = &self.ctx { @@ -1897,11 +1996,14 @@ impl Worker { if urgent && let Ok(mut l) = self.last.lock() { *l = t0.elapsed().as_secs_f64() * 1000.0; } + let ram = if img.is_gpu() { 0 } else { img.bytes() }; if let Ok(mut c) = self.cache.lock() && (!img.is_gpu() || !self.gpu_retired.load(Ordering::Acquire)) { - c.insert_with(key, img, files, since); + c.insert_took(key, img, files, since, Some(t0.elapsed())); } + // (with the lock released: the accountant asks every cache for its bytes) + effectcraft_engine::render::memory::Accountant::global().note_growth(ram); self.release(key, urgent); } diff --git a/crates/ui-egui/src/frames/tests.rs b/crates/ui-egui/src/frames/tests.rs index 45398de21..6632a70cc 100644 --- a/crates/ui-egui/src/frames/tests.rs +++ b/crates/ui-egui/src/frames/tests.rs @@ -2399,6 +2399,56 @@ fn a_keyframe_edit_reaches_only_the_keys_around_it() { } } +/// A key edit of an effect parameter re-renders only around the keys it changed, as a Transform +/// key edit does (#3324): Exposure keyed at frames 30, 60 and 90, its middle key changed. Write-on +/// reads its Brush Position at every earlier time (a dab per Brush Spacing since the layer's +/// start), so its middle key edit reaches every frame after it. Every frame kept renders as +/// before. +#[test] +fn an_effect_key_edit_reaches_only_the_frames_that_read_it() { + use effectcraft_engine::Session; + use effectcraft_engine::project::{LayerId, Value}; + use effectcraft_engine::render::render_frame; + use serde_json::{Value as Json, json}; + let v2 = |x: f64, y: f64| (json!([x, y]), Value::Vec2([x, y])); + let edits = [ + ("Exposure", "master/exposure", [json!(0.0), json!(1.0), json!(0.0)], Value::Scalar(3.0)), + ("Write-on", "brushPosition", [v2(2.0, 2.0).0, v2(14.0, 14.0).0, v2(2.0, 14.0).0], v2(14.0, 2.0).1), + ]; + for (effect, param, values, mid) in edits { + let mut s = Session::default(); + let cid = + ItemId(s.execute("comp.new", json!({"name": "A", "width": 16, "height": 16, "duration": 4, "frameRate": 30})).unwrap()["comp"].as_u64().unwrap()); + let l = s.execute("layer.newSolid", json!({"color": "#808080", "width": 16, "height": 16})).unwrap()["layer"].as_u64().unwrap(); + s.execute("effect.apply", json!({"layers": [l], "effect": effect})).unwrap(); + let path = format!("effects/#1/{param}"); + let fr = s.project.comp(cid).unwrap().frame_rate; + for (f, v) in [30, 60, 90].into_iter().zip(values) { + let add: Json = json!({"layer": l, "path": path, "time": fr.tick_of(f).seconds(), "value": v}); + s.execute("prop.addKey", add).unwrap(); + } + let p0 = s.project.clone(); + let f = Frames::default(); + let k = |content: u64, frame: i64| FrameKey { content, comp: cid.0, ..key(0, frame, 0) }; + let id0 = f.content_of(&p0, 1, cid); + (0..120).for_each(|i| insert(&f, k(id0, i))); + let mut p1 = p0.clone(); + Arc::make_mut(&mut p1).comp_mut(cid).unwrap().layer_mut(LayerId(l)).unwrap().props.prop_mut(&path).unwrap().keys[1].value = mid; + let kept = f.cached_frames(&k(f.content_of(&p1, 2, cid), 0)); + let same = |i: i64| render_frame(&p0, cid, fr.tick_of(i), 1.0).data == render_frame(&p1, cid, fr.tick_of(i), 1.0).data; + assert!(!same(60), "{effect}: the edit shows"); + assert!(![45, 60, 75].iter().any(|i| kept.contains(i)), "{effect}: {kept:?}"); + if effect == "Exposure" { + assert!((0..=27).chain(93..120).all(|i| kept.contains(&i)), "{effect}: the frames outside the keys stay: {kept:?}"); + } else { + assert!(!same(110) && !kept.contains(&110), "{effect}: the stroke drawn by frame 110 passes the edited key: {kept:?}"); + } + for i in kept { + assert!(same(i), "{effect}: kept frame {i} renders differently after the edit"); + } + } +} + /// Music's Audio Levels keep every frame, in RAM and on disk, while the project's expressions /// can't read audio (a wiggle); an expression naming the music's Audio Levels re-renders its layer. #[test] @@ -2885,6 +2935,8 @@ mod frame_files { fn session(p: &Arc, dir: &Path) -> Session { let disk = DiskCache::open(dir.join("cache"), 1 << 30).unwrap(); + // (every frame is written, however quick to render: not decided by this machine's speed) + disk.set_read_us_per_mb(0); let hook_calls = Arc::new(AtomicUsize::new(0)); let mut frames = Frames::default(); let calls = hook_calls.clone(); @@ -3124,6 +3176,125 @@ mod frame_files { } } +/// #3271 review: the memory accountant trims the preview frames held in RAM; GPU frames (video +/// memory, their own budget) are left alone, even when they are the least recently shown. +#[test] +fn the_accountant_trims_only_frames_in_ram() { + let Some(gpu) = Gpu::headless() else { + eprintln!("no GPU adapter: skipped"); + return; + }; + let texture = gpu.device().create_texture(&eframe::wgpu::TextureDescriptor { + label: None, + size: eframe::wgpu::Extent3d { width: 2, height: 2, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: eframe::wgpu::TextureDimension::D2, + format: eframe::wgpu::TextureFormat::Rgba8Unorm, + usage: eframe::wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }); + let gpu_frame = || FrameImage::Gpu(Arc::new(DisplayFrame { texture: texture.clone(), width: 2, height: 2 })); + let frames = Frames::default(); + { + let mut c = frames.cache.lock().unwrap(); + // The oldest frames are on the GPU. + c.insert(key(1, 0, 0), gpu_frame()); + c.insert(key(1, 1, 0), gpu_frame()); + c.insert(key(1, 2, 0), img()); + c.insert(key(1, 3, 0), img()); + } + let memory = PreviewMemory(frames.cache.clone()); + use effectcraft_engine::render::memory::MemoryHolder; + assert_eq!(memory.bytes(), 2 * 16); + let next = memory.oldest().unwrap(); + assert_eq!(next.bytes, 16, "a frame in RAM is offered"); + assert!(next.cost_us > 0); + assert_eq!(memory.drop_oldest(), 16); + let c = frames.cache.lock().unwrap(); + assert!(c.map.contains_key(&key(1, 0, 0)) && c.map.contains_key(&key(1, 1, 0)), "the GPU frames stay"); + assert!(!c.map.contains_key(&key(1, 2, 0)) && c.map.contains_key(&key(1, 3, 0)), "the oldest frame in RAM went"); + drop(c); + assert_eq!(memory.bytes(), 16); +} + +/// #3301 review: a frame someone still holds (the viewer showing it, from `Frames::get`) is not +/// offered to the memory accountant: dropping the cache's entry would free nothing, and its bytes +/// would be counted as freed. +#[test] +fn a_frame_held_elsewhere_is_not_offered_to_the_accountant() { + use effectcraft_engine::render::memory::MemoryHolder; + let frames = Frames::default(); + { + let mut c = frames.cache.lock().unwrap(); + c.insert(key(1, 0, 0), img()); + c.insert(key(1, 1, 0), img()); + } + let shown = frames.get(&key(1, 0, 0)).unwrap(); + // (the other one shown since and let go: the held frame is the least recently shown) + drop(frames.get(&key(1, 1, 0))); + let memory = PreviewMemory(frames.cache.clone()); + assert_eq!(memory.drop_oldest(), 16, "the frame nobody holds goes"); + { + let c = frames.cache.lock().unwrap(); + assert!(c.map.contains_key(&key(1, 0, 0)) && !c.map.contains_key(&key(1, 1, 0)), "the shown frame stays"); + } + assert!(memory.oldest().is_none() && memory.drop_oldest() == 0, "only a held frame left"); + drop(shown); + assert_eq!(memory.drop_oldest(), 16, "let go: offered"); +} + +/// #3301: frames a playing preview shows next are protected: other caches give way first, even +/// for items worth more, until the caches are more than the bounded overage over; past it the +/// preview frames go too. A frame rendered quickly still costs a typical render. +#[test] +fn preview_frames_ahead_of_the_playhead_outlive_old_footage() { + use effectcraft_engine::render::memory::{self, Accountant, Candidate, MemoryHolder}; + struct Footage(Mutex>); + impl MemoryHolder for Footage { + fn name(&self) -> &'static str { + "footage frames" + } + fn bytes(&self) -> usize { + self.0.lock().unwrap().iter().map(|c| c.bytes).sum() + } + fn oldest(&self) -> Option { + self.0.lock().unwrap().first().copied() + } + fn drop_oldest(&self) -> usize { + let mut v = self.0.lock().unwrap(); + if v.is_empty() { 0 } else { v.remove(0).bytes } + } + } + let frames = Frames::default(); + { + let mut c = frames.cache.lock().unwrap(); + for i in 10..12 { + c.insert_took(key(1, i, 0), img(), None, None, Some(std::time::Duration::from_micros(100))); + } + } + let preview: Arc = Arc::new(PreviewMemory(frames.cache.clone())); + // Stopped: the oldest frame is offered unprotected, with at least a typical render's cost. + let offered = preview.oldest().unwrap(); + assert!(!offered.protected); + assert_eq!(offered.cost_us, memory::default_cost(16, memory::DEFAULT_PREVIEW_US_PER_MB)); + // Playing from frame 10: the frames ahead are protected. + frames.set_playhead(Some(playhead(10, false))); + assert!(preview.oldest().unwrap().protected); + // A footage frame worth far more per byte, used just now, still goes first. + let footage = Arc::new(Footage(Mutex::new(vec![Candidate::new(memory::tick(), 16, 1_000_000)]))); + let footage_holder: Arc = footage.clone(); + let acc = Accountant::new(1000); + acc.register(&preview); + acc.register(&footage_holder); + acc.set_budget(40); + assert_eq!(footage.bytes(), 0, "the footage frame went"); + assert_eq!(preview.bytes(), 32, "the preview frames stay, a bounded way over"); + // Far over the budget, past the overage: the preview frames go too. + acc.set_budget(10); + assert!(preview.bytes() < 32, "{}", preview.bytes()); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn gpu_renders_in_flight_stay_within_the_cap() { diff --git a/crates/ui-egui/src/i18n/ui.rs b/crates/ui-egui/src/i18n/ui.rs index b2e0b3631..e964037e3 100644 --- a/crates/ui-egui/src/i18n/ui.rs +++ b/crates/ui-egui/src/i18n/ui.rs @@ -181,6 +181,7 @@ pub(crate) fn tr_args(text: &str, args: &[&dyn Display]) -> String { /// Japanese: the same rows, in the same order, as the Chinese catalogs below. const JAPANESE: &[(&str, &str)] = &[ + ("Views:", "画面:"), ("Click to sample color", "クリックして色をサンプル"), ("Appearance Settings…", "外観設定…"), ("Add to favorites", "お気に入りに追加"), @@ -886,12 +887,21 @@ const JAPANESE: &[(&str, &str)] = &[ ("Media Cache", "メディアキャッシュ"), ("Database and Cache Folder", "データベースとキャッシュのフォルダー"), ("Conformed Audio Folder", "適合オーディオフォルダー"), + ("Network Footage", "ネットワークフッテージ"), + ("Localize Network Footage", "ネットワークフッテージをローカルにコピー"), + ("Maximum Local Copies Size", "ローカルコピーの最大サイズ"), + ("Local Copies Folder", "ローカルコピーのフォルダー"), + ("Network Footage Locations", "ネットワークフッテージの場所"), + ("Local copies: {} files, {} of {} GB; {} queued, {} skipped", "ローカルコピー: {} ファイル、{} / {} GB、待機 {}、スキップ {}"), + ("Copying {}", "コピー中: {}"), + ("UNC paths (\\\\server\\share)", "UNC パス (\\\\server\\share)"), + ("Network footage: {}", "ネットワークフッテージ: {}"), + ("Limited by free disk space", "ディスクの空き容量により制限されています"), + ("Folders or drives, separated by ;", "フォルダーまたはドライブ(; で区切る)"), ("Memory & CPU", "メモリとCPU"), ("RAM Reserved for Other Applications", "他のアプリケーション用に確保するRAM"), - ("Cache Budgets", "キャッシュの割り当て"), - ("Layer Cache", "レイヤーキャッシュ"), - ("Footage Frame Cache", "フッテージフレームキャッシュ"), - ("Preview (RAM) Cache", "プレビュー(RAM)キャッシュ"), + ("EffectCraft may use: {} of {}", "EffectCraftが使用できるメモリ:{}/{}"), + ("EffectCraft may use: {} (installed RAM unknown)", "EffectCraftが使用できるメモリ:{}(搭載RAMは不明)"), ("Reduce Cache Size When System Is Low on Memory", "システムのメモリが不足しているときにキャッシュサイズを減らす"), ("GPU Frames Rendered at Once", "一度にレンダリングするGPUフレーム数"), ("Video", "ビデオ"), @@ -1325,6 +1335,7 @@ const JAPANESE: &[(&str, &str)] = &[ ]; const SIMPLIFIED_CHINESE: &[(&str, &str)] = &[ + ("Views:", "视图:"), ("Click to sample color", "单击以取样颜色"), ("Appearance Settings…", "外观设置…"), ("Add to favorites", "添加到收藏"), @@ -2021,12 +2032,21 @@ const SIMPLIFIED_CHINESE: &[(&str, &str)] = &[ ("Media Cache", "媒体缓存"), ("Database and Cache Folder", "数据库和缓存文件夹"), ("Conformed Audio Folder", "符合的音频文件夹"), + ("Network Footage", "网络素材"), + ("Localize Network Footage", "将网络素材复制到本地"), + ("Maximum Local Copies Size", "本地副本最大大小"), + ("Local Copies Folder", "本地副本文件夹"), + ("Network Footage Locations", "网络素材位置"), + ("Local copies: {} files, {} of {} GB; {} queued, {} skipped", "本地副本:{} 个文件,{} / {} GB;{} 个排队,{} 个跳过"), + ("Copying {}", "正在复制 {}"), + ("UNC paths (\\\\server\\share)", "UNC 路径 (\\\\server\\share)"), + ("Network footage: {}", "网络素材:{}"), + ("Limited by free disk space", "受磁盘可用空间限制"), + ("Folders or drives, separated by ;", "文件夹或驱动器,以 ; 分隔"), ("Memory & CPU", "内存和 CPU"), ("RAM Reserved for Other Applications", "为其他应用程序保留的内存"), - ("Cache Budgets", "缓存预算"), - ("Layer Cache", "图层缓存"), - ("Footage Frame Cache", "素材帧缓存"), - ("Preview (RAM) Cache", "预览(内存)缓存"), + ("EffectCraft may use: {} of {}", "EffectCraft 可使用:{},共 {}"), + ("EffectCraft may use: {} (installed RAM unknown)", "EffectCraft 可使用:{}(已安装内存未知)"), ("Reduce Cache Size When System Is Low on Memory", "系统内存不足时减少缓存大小"), ("GPU Frames Rendered at Once", "GPU 同时渲染的帧数"), ("Video", "视频"), @@ -2445,6 +2465,7 @@ const SIMPLIFIED_CHINESE: &[(&str, &str)] = &[ /// Swedish (`sv`), written from the English source. const SWEDISH: &[(&str, &str)] = &[ + ("Views:", "Vyer:"), ("Appearance Settings…", "Utseendeinställningar…"), ("Add to favorites", "Lägg till i favoriter"), ("Remove from favorites", "Ta bort från favoriter"), @@ -3136,12 +3157,21 @@ const SWEDISH: &[(&str, &str)] = &[ ("Media Cache", "Mediecache"), ("Database and Cache Folder", "Databas- och cachemapp"), ("Conformed Audio Folder", "Mapp för konformerat ljud"), + ("Network Footage", "Nätverksmaterial"), + ("Localize Network Footage", "Kopiera nätverksmaterial lokalt"), + ("Maximum Local Copies Size", "Största storlek för lokala kopior"), + ("Local Copies Folder", "Mapp för lokala kopior"), + ("Network Footage Locations", "Platser för nätverksmaterial"), + ("Local copies: {} files, {} of {} GB; {} queued, {} skipped", "Lokala kopior: {} filer, {} av {} GB; {} i kö, {} överhoppade"), + ("Copying {}", "Kopierar {}"), + ("UNC paths (\\\\server\\share)", "UNC-sökvägar (\\\\server\\share)"), + ("Network footage: {}", "Nätverksmaterial: {}"), + ("Limited by free disk space", "Begränsas av ledigt diskutrymme"), + ("Folders or drives, separated by ;", "Mappar eller enheter, åtskilda med ;"), ("Memory & CPU", "Minne och processor"), ("RAM Reserved for Other Applications", "RAM reserverat för andra program"), - ("Cache Budgets", "Cachebudgetar"), - ("Layer Cache", "Lagercache"), - ("Footage Frame Cache", "Bildrutecache för material"), - ("Preview (RAM) Cache", "Förhandsgranskningscache (RAM)"), + ("EffectCraft may use: {} of {}", "EffectCraft får använda: {} av {}"), + ("EffectCraft may use: {} (installed RAM unknown)", "EffectCraft får använda: {} (installerat RAM okänt)"), ("Reduce Cache Size When System Is Low on Memory", "Minska cachestorleken när systemet har ont om minne"), ("GPU Frames Rendered at Once", "GPU-bildrutor som renderas samtidigt"), ("Video", "Video"), @@ -3721,6 +3751,7 @@ const SWEDISH: &[(&str, &str)] = &[ ]; const TRADITIONAL_CHINESE: &[(&str, &str)] = &[ + ("Views:", "檢視:"), ("Click to sample color", "按一下以取樣顏色"), ("Appearance Settings…", "外觀設定…"), ("Add to favorites", "加入最愛"), @@ -4363,12 +4394,21 @@ const TRADITIONAL_CHINESE: &[(&str, &str)] = &[ ("Media Cache", "媒體快取"), ("Database and Cache Folder", "資料庫和快取資料夾"), ("Conformed Audio Folder", "符合的音訊資料夾"), + ("Network Footage", "網路素材"), + ("Localize Network Footage", "將網路素材複製到本機"), + ("Maximum Local Copies Size", "本機副本最大大小"), + ("Local Copies Folder", "本機副本資料夾"), + ("Network Footage Locations", "網路素材位置"), + ("Local copies: {} files, {} of {} GB; {} queued, {} skipped", "本機副本:{} 個檔案,{} / {} GB;{} 個排隊,{} 個略過"), + ("Copying {}", "正在複製 {}"), + ("UNC paths (\\\\server\\share)", "UNC 路徑 (\\\\server\\share)"), + ("Network footage: {}", "網路素材:{}"), + ("Limited by free disk space", "受磁碟可用空間限制"), + ("Folders or drives, separated by ;", "資料夾或磁碟機,以 ; 分隔"), ("Memory & CPU", "記憶體和 CPU"), ("RAM Reserved for Other Applications", "為其他應用程式保留的記憶體"), - ("Cache Budgets", "快取預算"), - ("Layer Cache", "圖層快取"), - ("Footage Frame Cache", "素材影格快取"), - ("Preview (RAM) Cache", "預覽(記憶體)快取"), + ("EffectCraft may use: {} of {}", "EffectCraft 可使用:{},共 {}"), + ("EffectCraft may use: {} (installed RAM unknown)", "EffectCraft 可使用:{}(已安裝記憶體未知)"), ("Reduce Cache Size When System Is Low on Memory", "系統記憶體不足時減少快取大小"), ("GPU Frames Rendered at Once", "GPU 同時算圖的影格數"), ("Video", "視訊"), @@ -4790,6 +4830,7 @@ const TRADITIONAL_CHINESE: &[(&str, &str)] = &[ /// Ukrainian (uk): original translations of the same interface rows as the Chinese catalogs. /// Technical names, key names and substituted project content keep their original spelling. const UKRAINIAN: &[(&str, &str)] = &[ + ("Views:", "Вигляди:"), ("Click to sample color", "Клацніть, щоб узяти зразок кольору"), ("Appearance Settings…", "Налаштування вигляду…"), ("Add to favorites", "Додати до вибраного"), @@ -5380,6 +5421,7 @@ const UKRAINIAN: &[(&str, &str)] = &[ // Brazilian Portuguese. const PORTUGUESE: &[(&str, &str)] = &[ + ("Views:", "Visualizações:"), ("Click to sample color", "Clique para obter uma amostra de cor"), ("Export Scene to Blender...", "Exportar cena para o Blender..."), (" OK ", " OK "), @@ -5857,8 +5899,18 @@ const PORTUGUESE: &[(&str, &str)] = &[ ("Automatically Reload Footage", "Recarregar mídias automaticamente"), ("Automatically Save Projects", "Salvar projetos automaticamente"), ("Brightness", "Brilho"), - ("Cache Budgets", "Orçamentos de cache"), ("Conformed Audio Folder", "Pasta de áudio conformado"), + ("Network Footage", "Mídia de rede"), + ("Localize Network Footage", "Copiar mídia de rede localmente"), + ("Maximum Local Copies Size", "Tamanho máximo das cópias locais"), + ("Local Copies Folder", "Pasta das cópias locais"), + ("Network Footage Locations", "Locais de mídia de rede"), + ("Local copies: {} files, {} of {} GB; {} queued, {} skipped", "Cópias locais: {} arquivos, {} de {} GB; {} na fila, {} ignorados"), + ("Copying {}", "Copiando {}"), + ("UNC paths (\\\\server\\share)", "Caminhos UNC (\\\\server\\share)"), + ("Network footage: {}", "Mídia de rede: {}"), + ("Limited by free disk space", "Limitado pelo espaço livre em disco"), + ("Folders or drives, separated by ;", "Pastas ou unidades, separadas por ;"), ("Create Layers at Composition Start Time", "Criar camadas no tempo inicial da composição"), ("Create Split Layers Above Original Layer", "Criar camadas divididas acima da camada original"), ("Custom", "Personalizado"), @@ -5879,6 +5931,8 @@ const PORTUGUESE: &[(&str, &str)] = &[ "EffectCraft always uses its own colour picker (the same on every platform and the web).", "O EffectCraft sempre usa o próprio seletor de cores (o mesmo em todas as plataformas e na web).", ), + ("EffectCraft may use: {} of {}", "O EffectCraft pode usar: {} de {}"), + ("EffectCraft may use: {} (installed RAM unknown)", "O EffectCraft pode usar: {} (RAM instalada desconhecida)"), ("Empty Disk Cache", "Esvaziar cache do disco"), ("Enable Disk Cache", "Ativar cache do disco"), ("Enable JavaScript Debugger", "Ativar depurador JavaScript"), @@ -5899,7 +5953,6 @@ const PORTUGUESE: &[(&str, &str)] = &[ ("Fit", "Ajustar"), ("Fit up to 100%", "Ajustar até 100%"), ("Floating Window", "Janela flutuante"), - ("Footage Frame Cache", "Cache de quadros de mídia"), ("GPU Information...", "Informações da GPU..."), ("Gridline Every", "Grade a cada"), ("Hardware Accelerate Composition, Layer and Footage Panels", "Aceleração por hardware dos painéis de composição, camada e mídia"), @@ -5907,7 +5960,6 @@ const PORTUGUESE: &[(&str, &str)] = &[ ("Interpret Unlabeled Alpha As", "Interpretar alfa não rotulado como"), ("Keyframes", "Keyframes"), ("Labels and Colors", "Rótulos e cores"), - ("Layer Cache", "Cache de camada"), ("Length of Composition", "Duração da composição"), ("Levels of Undo", "Níveis de desfazer"), ("Light Theme", "Tema claro"), @@ -5933,7 +5985,6 @@ const PORTUGUESE: &[(&str, &str)] = &[ ("OpenGL (compatibility)", "OpenGL (compatibilidade)"), ("Panels are always drawn by the GPU (wgpu).", "Os painéis são sempre desenhados pela GPU (wgpu)."), ("Preserve Constant Vertex and Feather Point Count when Editing Masks", "Preservar o número constante de vértices e pontos de feather ao editar máscaras"), - ("Preview (RAM) Cache", "Cache de pré-visualização (RAM)"), ("RAM Reserved for Other Applications", "RAM reservada para outros aplicativos"), ("RGB Straight", "RGB direto"), ("Realtime Shadows in Draft", "Sombras em tempo real no rascunho"), @@ -6148,6 +6199,7 @@ const PORTUGUESE: &[(&str, &str)] = &[ /// Polish (pl): original translations covering every row in the Chinese panel catalogs. const POLISH: &[(&str, &str)] = &[ + ("Views:", "Widoki:"), ("Click to sample color", "Kliknij, aby pobrać próbkę koloru"), ("Appearance Settings…", "Ustawienia wyglądu…"), ("Add to favorites", "Dodaj do ulubionych"), @@ -6840,12 +6892,21 @@ const POLISH: &[(&str, &str)] = &[ ("Media Cache", "Pamięć multimediów"), ("Database and Cache Folder", "Folder bazy danych i pamięci"), ("Conformed Audio Folder", "Folder dopasowanego audio"), + ("Network Footage", "Materiał sieciowy"), + ("Localize Network Footage", "Kopiuj materiał sieciowy lokalnie"), + ("Maximum Local Copies Size", "Maksymalny rozmiar kopii lokalnych"), + ("Local Copies Folder", "Folder kopii lokalnych"), + ("Network Footage Locations", "Lokalizacje materiału sieciowego"), + ("Local copies: {} files, {} of {} GB; {} queued, {} skipped", "Kopie lokalne: {} plików, {} z {} GB; {} w kolejce, {} pominiętych"), + ("Copying {}", "Kopiowanie {}"), + ("UNC paths (\\\\server\\share)", "Ścieżki UNC (\\\\server\\share)"), + ("Network footage: {}", "Materiał sieciowy: {}"), + ("Limited by free disk space", "Ograniczone wolnym miejscem na dysku"), + ("Folders or drives, separated by ;", "Foldery lub dyski, rozdzielone znakiem ;"), ("Memory & CPU", "Pamięć i procesor"), ("RAM Reserved for Other Applications", "Pamięć RAM zarezerwowana dla innych aplikacji"), - ("Cache Budgets", "Budżety pamięci podręcznej"), - ("Layer Cache", "Pamięć warstw"), - ("Footage Frame Cache", "Pamięć klatek materiałów"), - ("Preview (RAM) Cache", "Pamięć podglądu (RAM)"), + ("EffectCraft may use: {} of {}", "EffectCraft może użyć: {} z {}"), + ("EffectCraft may use: {} (installed RAM unknown)", "EffectCraft może użyć: {} (zainstalowana pamięć RAM nieznana)"), ("Reduce Cache Size When System Is Low on Memory", "Zmniejsz pamięć podręczną, gdy w systemie brakuje pamięci"), ("Video", "Wideo"), ("Enable Video Preview Output", "Włącz wyjście podglądu wideo"), @@ -6909,6 +6970,7 @@ const POLISH: &[(&str, &str)] = &[ /// Czech (cs): original translations covering every row in the Chinese panel catalogs. const CZECH: &[(&str, &str)] = &[ + ("Views:", "Zobrazení:"), ("Click to sample color", "Kliknutím naberete barvu"), (" OK ", " OK "), (" Delete ", " Odstranit "), @@ -7479,6 +7541,7 @@ const CZECH: &[(&str, &str)] = &[ /// order. Terms follow the Spanish menu catalog (composición, material de archivo, cola de procesamiento, /// ajuste preestablecido, método abreviado). Written from the English source. const SPANISH: &[(&str, &str)] = &[ + ("Views:", "Vistas:"), ("Click to sample color", "Haz clic para tomar una muestra de color"), ("Copy Source Path", "Copiar ruta de origen"), ("Appearance Settings…", "Ajustes de apariencia…"), @@ -8051,6 +8114,7 @@ const SPANISH: &[(&str, &str)] = &[ /// Georgian (ka): every row of the Chinese catalogs, in the same order (the tests keep them in step). const GEORGIAN: &[(&str, &str)] = &[ + ("Views:", "ხედები:"), ("Click to sample color", "დააწკაპუნეთ ფერის ნიმუშის ასაღებად"), ("Appearance Settings…", "იერსახის პარამეტრები…"), ("Add to favorites", "რჩეულებში დამატება"), @@ -8754,12 +8818,21 @@ const GEORGIAN: &[(&str, &str)] = &[ ("Media Cache", "მედიაქეში"), ("Database and Cache Folder", "მონაცემთა ბაზისა და ქეშის საქაღალდე"), ("Conformed Audio Folder", "მისადაგებული აუდიოს საქაღალდე"), + ("Network Footage", "ქსელური მასალა"), + ("Localize Network Footage", "ქსელური მასალის ლოკალურად კოპირება"), + ("Maximum Local Copies Size", "ლოკალური ასლების მაქსიმალური ზომა"), + ("Local Copies Folder", "ლოკალური ასლების საქაღალდე"), + ("Network Footage Locations", "ქსელური მასალის მდებარეობები"), + ("Local copies: {} files, {} of {} GB; {} queued, {} skipped", "ლოკალური ასლები: {} ფაილი, {} / {} GB; რიგში {}, გამოტოვებული {}"), + ("Copying {}", "კოპირდება {}"), + ("UNC paths (\\\\server\\share)", "UNC ბილიკები (\\\\server\\share)"), + ("Network footage: {}", "ქსელური მასალა: {}"), + ("Limited by free disk space", "შეზღუდულია დისკის თავისუფალი ადგილით"), + ("Folders or drives, separated by ;", "საქაღალდეები ან დისკები, გამოყოფილი ;-ით"), ("Memory & CPU", "მეხსიერება და CPU"), ("RAM Reserved for Other Applications", "სხვა აპლიკაციებისთვის დაჯავშნული RAM"), - ("Cache Budgets", "ქეშის ლიმიტები"), - ("Layer Cache", "შრეების ქეში"), - ("Footage Frame Cache", "ვიდეომასალის კადრების ქეში"), - ("Preview (RAM) Cache", "წინასწარი ნახვის (RAM) ქეში"), + ("EffectCraft may use: {} of {}", "EffectCraft-ს შეუძლია გამოიყენოს: {} {}-დან"), + ("EffectCraft may use: {} (installed RAM unknown)", "EffectCraft-ს შეუძლია გამოიყენოს: {} (დაყენებული RAM უცნობია)"), ("Reduce Cache Size When System Is Low on Memory", "ქეშის ზომის შემცირება, როცა სისტემას მეხსიერება აკლია"), ("Video", "ვიდეო"), ("Enable Video Preview Output", "ვიდეოს წინასწარი ნახვის გამოტანის ჩართვა"), @@ -9023,6 +9096,7 @@ const GEORGIAN_PANELS: &[(&str, &str)] = &[ /// clé, métrage, file d'attente de rendu, chronologie, repère, estampe). A no-break space precedes /// `:`, `;`, `?` and `!`, and the apostrophe is the typographic one. Written from the English source. const FRENCH: &[(&str, &str)] = &[ + ("Views:", "Vues\u{a0}:"), ("Appearance Settings…", "Paramètres d’apparence…"), ("Add to favorites", "Ajouter aux favoris"), ("Remove from favorites", "Retirer des favoris"), @@ -9738,12 +9812,21 @@ const FRENCH: &[(&str, &str)] = &[ ("Media Cache", "Cache des médias"), ("Database and Cache Folder", "Dossier de la base de données et du cache"), ("Conformed Audio Folder", "Dossier de l’audio conformé"), + ("Network Footage", "Métrage réseau"), + ("Localize Network Footage", "Copier le métrage réseau en local"), + ("Maximum Local Copies Size", "Taille maximale des copies locales"), + ("Local Copies Folder", "Dossier des copies locales"), + ("Network Footage Locations", "Emplacements du métrage réseau"), + ("Local copies: {} files, {} of {} GB; {} queued, {} skipped", "Copies locales\u{a0}: {} fichiers, {} sur {} Go\u{a0}; {} en attente, {} ignorés"), + ("Copying {}", "Copie de {}"), + ("UNC paths (\\\\server\\share)", "Chemins UNC (\\\\server\\share)"), + ("Network footage: {}", "Métrage réseau\u{a0}: {}"), + ("Limited by free disk space", "Limité par l’espace disque libre"), + ("Folders or drives, separated by ;", "Dossiers ou lecteurs, séparés par\u{a0};"), ("Memory & CPU", "Mémoire et CPU"), ("RAM Reserved for Other Applications", "Mémoire vive réservée aux autres applications"), - ("Cache Budgets", "Budgets de cache"), - ("Layer Cache", "Cache des calques"), - ("Footage Frame Cache", "Cache des images du métrage"), - ("Preview (RAM) Cache", "Cache de prévisualisation (RAM)"), + ("EffectCraft may use: {} of {}", "EffectCraft peut utiliser : {} sur {}"), + ("EffectCraft may use: {} (installed RAM unknown)", "EffectCraft peut utiliser : {} (mémoire vive installée inconnue)"), ("Reduce Cache Size When System Is Low on Memory", "Réduire la taille du cache quand le système manque de mémoire"), ("Video", "Vidéo"), ("Enable Video Preview Output", "Activer la sortie de prévisualisation vidéo"), diff --git a/crates/ui-egui/src/panels/project.rs b/crates/ui-egui/src/panels/project.rs index 01f53c6ee..57d2c60fa 100644 --- a/crates/ui-egui/src/panels/project.rs +++ b/crates/ui-egui/src/panels/project.rs @@ -120,13 +120,13 @@ pub fn drop_folder(project: &effectcraft_engine::project::Project, row: Option)>>>>); +struct PendingThumb(u128, Arc)>>>>); /// The Project panel's thumbnail texture of `item`, once its render has landed. pub fn cached_thumbnail(ctx: &egui::Context, item: ItemId) -> Option { @@ -142,13 +142,54 @@ pub fn forget_thumbnails(ctx: &egui::Context) { }); } -/// Thumbnail of a comp (its current time) or footage (first frame), cached per item/revision. -/// Rendered on a background thread (inline on wasm32): until the new one lands the previous -/// thumbnail stays up, so selecting a big comp or editing it never stalls the panel. +/// The content key of item `it`'s thumbnail at `t` ([`effectcraft_engine::Session::thumbnail_key`]), +/// worked out again only when the project's revision, the footage reloads (Reload Footage or a +/// watched file that changed: the project's revision stays), the preferences (Switches Affect +/// Nested Comps and real-time shadows change what a comp shows) or the time changed. `false` +/// with it: the key is of an earlier state (held back while edits come fast), so no render of +/// the state now may be made under it. +fn thumbnail_key(app: &EffectcraftApp, ctx: &egui::Context, it: &Item, t: effectcraft_engine::time::Tick) -> (u128, bool) { + let id = egui::Id::unique(("proj-thumb-key", it.id.0)); + let rev = app.session.revision; + let reloads = app.session.footage_reloads.load(std::sync::atomic::Ordering::Relaxed); + let prefs = app.session.prefs_revision; + let now = ctx.input(|i| i.time); + if let Some((r, n, pr, at, k, when)) = ctx.data(|d| d.get_temp::(id)) { + if r == rev && n == reloads && pr == prefs && at == t.0 { + return (k, true); + } + // (the key hashes the comp's content: while edits come fast, at most every 0.25 s) + if now - when < THUMB_KEY_EVERY { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(THUMB_KEY_EVERY)); + return (k, false); + } + } + // (no key: the revision stands in, as before) + let k = app.session.thumbnail_key(it.id, t, THUMB_SIDE).unwrap_or(u128::from(rev) | (1 << 127)); + ctx.data_mut(|d| d.insert_temp::(id, (rev, reloads, prefs, t.0, k, now))); + (k, true) +} + +/// A thumbnail's content key as last worked out: (project revision, footage reloads, preferences +/// revision, time, key, when, in seconds of UI time). +type ThumbKey = (u64, u64, u64, i64, u128, f64); + +/// The longest side of a Project panel thumbnail, in pixels. +const THUMB_SIDE: u32 = 192; + +/// A thumbnail's content key is worked out again at most this often (seconds) while the +/// project keeps changing. +const THUMB_KEY_EVERY: f64 = 0.25; + +/// Thumbnail of a comp (its current time) or footage (first frame), cached per item by what it +/// shows ([`thumbnail_key`], #3271): an edit that doesn't change the picture doesn't render it +/// again. Rendered on a background thread (inline on wasm32): until the new one lands the +/// previous thumbnail stays up, so selecting a big comp or editing it never stalls the panel. fn thumbnail(app: &EffectcraftApp, ctx: &egui::Context, it: &Item) -> Option { let key = egui::Id::unique(("proj-thumb", it.id.0)); let pkey = egui::Id::unique(("proj-thumb-pending", it.id.0)); - let rev = app.session.revision; + let t = app.session.state.times.get(&it.id).copied().unwrap_or_default(); + let (rev, current) = thumbnail_key(app, ctx, it, t); let cached: Option = ctx.data(|d| d.get_temp(key)); let mut tex = cached.as_ref().map(|Thumb(_, t)| t.clone()); let have = cached.as_ref().map(|Thumb(r, _)| *r); @@ -179,11 +220,12 @@ fn thumbnail(app: &EffectcraftApp, ctx: &egui::Context, it: &Item) -> Option)>>>> = Arc::default(); if cfg!(target_arch = "wasm32") { *slot.lock().ok()? = Some(job()); @@ -1541,8 +1583,8 @@ mod tests { let (key, pkey) = (egui::Id::unique(("proj-thumb", 1u64)), egui::Id::unique(("proj-thumb-pending", 1u64))); let tex = ctx.load_texture("t", egui::ColorImage::from_rgba_unmultiplied([1, 1], &[255; 4]), egui::TextureOptions::LINEAR); ctx.data_mut(|d| { - d.insert_temp(key, Thumb(app.session.revision, tex)); - d.insert_temp(pkey, PendingThumb(app.session.revision, Arc::default())); + d.insert_temp(key, Thumb(u128::from(app.session.revision), tex)); + d.insert_temp(pkey, PendingThumb(u128::from(app.session.revision), Arc::default())); }); app.session.execute("file.closeProject", serde_json::json!({})).unwrap(); app.handle_events(&ctx); @@ -1550,6 +1592,36 @@ mod tests { assert!(ctx.data(|d| d.get_temp::(pkey)).is_none(), "a closed project's render is awaited"); } + /// #3301 review: while edits come fast the thumbnail's key is held back (it is of an + /// earlier state); no render of the state now is started under it, so it can never be kept + /// as the earlier state's picture. The thumbnail shown stays. + #[test] + fn no_thumbnail_render_starts_under_a_held_back_key() { + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + let comp = ItemId( + app.session.execute("comp.new", serde_json::json!({"name": "C", "width": 8, "height": 6, "duration": 1})).unwrap()["comp"].as_u64().unwrap(), + ); + let ctx = egui::Context::default(); + let it = app.session.project.item(comp).unwrap().clone(); + let (key, pkey, kkey) = + (egui::Id::unique(("proj-thumb", comp.0)), egui::Id::unique(("proj-thumb-pending", comp.0)), egui::Id::unique(("proj-thumb-key", comp.0))); + let tex = ctx.load_texture("t", egui::ColorImage::from_rgba_unmultiplied([1, 1], &[255; 4]), egui::TextureOptions::LINEAR); + // A key worked out just now for an earlier revision, and a thumbnail of another state. + let now = ctx.input(|i| i.time); + let (rev, prefs) = (app.session.revision, app.session.prefs_revision); + ctx.data_mut(|d| { + d.insert_temp::(kkey, (rev.wrapping_sub(1), 0, prefs, 0, 7, now)); + d.insert_temp(key, Thumb(5, tex)); + }); + assert!(thumbnail(&app, &ctx, &it).is_some(), "the thumbnail shown stays"); + assert!(ctx.data(|d| d.get_temp::(pkey)).is_none(), "no render under a held-back key"); + // Worked out again (the key is current): the render starts. + ctx.data_mut(|d| d.remove::(kkey)); + thumbnail(&app, &ctx, &it); + assert!(ctx.data(|d| d.get_temp::(pkey)).is_some(), "a current key: rendered"); + app.session.execute("file.closeProject", serde_json::json!({})).unwrap(); + } + /// Long names show in full: the Name column fits them (it stopped at 260 points with "…") /// up to the panel's width less the Label column and, while optional columns show, room for /// them; a width the user dragged wins. diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rs index cdeb85116..ba9af77f1 100644 --- a/crates/ui-egui/src/panels/settings.rs +++ b/crates/ui-egui/src/panels/settings.rs @@ -73,6 +73,7 @@ fn page_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, page: &Page, cur: &Value } Item::Labels => labels_ui(app, ui, cur, acts), Item::BrowserStorage => browser_storage_ui(app, ui, t, acts), + Item::MemoryUse => memory_use_ui(app, ui, t), Item::Models(task) => models_ui(app, ui, t, acts, task), Item::PluginLibrary => library_ui(app, ui, t, acts), Item::AudioDevices { key } => { @@ -106,7 +107,9 @@ fn page_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, page: &Page, cur: &Value Item::Setting { key, label, kind, live } => { let v = get(key); let id = format!("settings.{key}"); - let tip = (!live).then(|| tr("Stored, but not used by EffectCraft yet")); + let tip = (!live) + .then(|| tr("Stored, but not used by EffectCraft yet")) + .or_else(|| (key == "disk.networkFootageLocations").then(|| tr(LOCATIONS_HINT))); let mut resp: Option = None; // What the control is set to, for assistive technology. let mut value_text = String::new(); @@ -184,7 +187,11 @@ fn page_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, page: &Page, cur: &Value } Kind::Text | Kind::Path => { let mut s = v.as_str().unwrap_or("").to_string(); - let r = ui.add(egui::TextEdit::singleline(&mut s).desired_width(if kind == Kind::Path { 230.0 } else { 260.0 })); + let mut edit = egui::TextEdit::singleline(&mut s).desired_width(if kind == Kind::Path { 230.0 } else { 260.0 }); + if key == "disk.networkFootageLocations" { + edit = edit.hint_text(tr(LOCATIONS_HINT)); + } + let r = ui.add(edit); value_text = s.clone(); if r.changed() { acts.push(Act::Set(key.into(), json!(s))); @@ -238,11 +245,78 @@ fn page_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, page: &Page, cur: &Value if key == "disk.diskCacheMaxGb" { disk_cache_limit_ui(app, ui, t); } + if key == "disk.localizeFootage" + && let Some(s) = app.session.localize_status() + { + localize_status_ui(app, ui, t, &s); + } } } } } +/// The hint of Network Footage Locations: what the field takes. +const LOCATIONS_HINT: &str = "Folders or drives, separated by ;"; + +/// How soon to draw the localizer's status again: while it has files to copy, every half +/// second; idle, not at all. +pub(crate) fn localize_repaint(s: &effectcraft_engine::render::LocalizeReport) -> Option { + (s.queued > 0 || s.copying.is_some()).then(|| std::time::Duration::from_millis(500)) +} + +/// Settings ▸ Disk, under Localize Network Footage (#3271): the local copies, what is queued and +/// being copied, and which locations count as network. Automation id +/// `settings.disk.localizeStatus`, labelled `files=… bytes=… queued=… skipped=…`. +fn localize_status_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, t: &Tokens, s: &effectcraft_engine::render::LocalizeReport) { + const GB: f64 = (1u64 << 30) as f64; + // (the status changes on its own while files are copied: drawn again until it is idle) + if let Some(after) = localize_repaint(s) { + ui.ctx().request_repaint_after(after); + } + let mut lines = vec![tr_args( + "Local copies: {} files, {} of {} GB; {} queued, {} skipped", + &[&s.files, &format!("{:.1}", s.bytes as f64 / GB), &format!("{:.1}", s.max_bytes as f64 / GB), &s.queued, &s.skipped], + )]; + if let Some(p) = &s.copying { + lines.push(tr_args("Copying {}", &[p])); + } + let mut network = vec![tr("UNC paths (\\\\server\\share)").to_string()]; + network.extend(s.network.iter().cloned()); + lines.push(tr_args("Network footage: {}", &[&network.join(", ")])); + if s.reserve_limited { + lines.push(tr("Limited by free disk space").to_string()); + } + let r = ui + .vertical(|ui| { + for line in &lines { + ui.label(RichText::new(line).color(t.text_dim)); + } + }) + .response; + let label = format!("files={} bytes={} queued={} skipped={}", s.files, s.bytes, s.queued, s.skipped); + app.auto.add("settings.disk.localizeStatus", r.rect, &label); +} + +/// Settings ▸ Memory & CPU, under RAM Reserved for Other Applications: the memory EffectCraft's +/// caches may use (one budget they share, `Session::memory_budget`), of the installed RAM. +/// Automation id `settings.memory.use`, labelled `budgetMb=… installedMb=… reduced=…` (the same +/// in every interface language; `installedMb=unknown` without a reading). +fn memory_use_ui(app: &mut EffectcraftApp, ui: &mut egui::Ui, t: &Tokens) { + let b = app.session.memory_budget(); + let r = ui.label(RichText::new(memory_use_line(b.bytes as u64, b.installed)).color(t.text_dim)); + let installed = b.installed.map_or_else(|| "unknown".to_string(), |i| (i >> 20).to_string()); + app.auto.add("settings.memory.use", r.rect, &format!("budgetMb={} installedMb={installed} reduced={}", b.bytes >> 20, b.reduced)); +} + +/// The line [`memory_use_ui`] shows for a budget of `budget` bytes of `installed` bytes of RAM. +pub(crate) fn memory_use_line(budget: u64, installed: Option) -> String { + let gb = |b: u64| format!("{:.1} GB", b as f64 / (1u64 << 30) as f64); + match installed { + Some(i) => tr_args("EffectCraft may use: {} of {}", &[&gb(budget), &gb(i)]), + None => tr_args("EffectCraft may use: {} (installed RAM unknown)", &[&gb(budget)]), + } +} + /// Settings ▸ Disk, under Maximum Disk Cache Size: the limit in effect, and why it is lower when /// free disk space holds the cache below the setting (it never fills the disk). Automation id /// `settings.disk.cacheLimit`, labelled `limitMb=… maxMb=… reserveMb=… spaceLimited=… writes=…` @@ -1272,6 +1346,29 @@ mod tests { assert!(actions.is_empty()); } + /// Settings ▸ Memory & CPU shows what EffectCraft's caches may use, of the installed RAM + /// (#3298: one budget instead of three cache sizes), machine-readable for agents. + #[test] + fn the_memory_page_shows_what_the_caches_may_use() { + assert_eq!(memory_use_line((464u64 << 30) / 10, Some(64 << 30)), "EffectCraft may use: 46.4 GB of 64.0 GB"); + assert_eq!(memory_use_line(5 << 30, None), "EffectCraft may use: 5.0 GB (installed RAM unknown)"); + let mut app = EffectcraftApp::new(effectcraft_engine::Session::default()); + app.session.sys_memory = Some(effectcraft_engine::sysinfo::SysMemory { total: 64 << 30, available: 60 << 30 }); + let page = pages().into_iter().find(|p| p.id == "memory").unwrap(); + let ctx = egui::Context::default(); + let tokens = app.tokens; + let cur = serde_json::to_value(&app.session.prefs).unwrap(); + let mut actions = vec![]; + let mut output = ctx + .run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(900.0, 900.0))), ..Default::default() }, |ui| { + page_ui(&mut app, ui, &page, &cur, &tokens, &mut actions) + }); + output.textures_delta.clear(); + let budget = (58u64 << 30) * 80 / 100; + assert_eq!(app.auto.find("settings.memory.use").unwrap().label, format!("budgetMb={} installedMb=65536 reduced=false", budget >> 20)); + assert!(actions.is_empty()); + } + /// Settings ▸ Disk shows the disk cache's limit in effect under Maximum Disk Cache Size, and /// says when free disk space holds it lower (a 20 GB cache held at 0 showed nothing). #[test] @@ -1328,4 +1425,14 @@ mod tests { drop(dc); let _ = std::fs::remove_dir_all(&dir); } + + /// #3271 review: the localizer's status is drawn again while files are queued or copied, + /// and not while it is idle. + #[test] + fn the_localizer_status_repaints_only_while_busy() { + use effectcraft_engine::render::LocalizeReport; + assert_eq!(super::localize_repaint(&LocalizeReport::default()), None, "idle"); + assert!(super::localize_repaint(&LocalizeReport { queued: 2, ..Default::default() }).is_some(), "queued"); + assert!(super::localize_repaint(&LocalizeReport { copying: Some("x.exr".into()), ..Default::default() }).is_some(), "copying"); + } } diff --git a/crates/ui-egui/src/panels/viewer_tools.rs b/crates/ui-egui/src/panels/viewer_tools.rs index ded5fbdb3..52e19e999 100644 --- a/crates/ui-egui/src/panels/viewer_tools.rs +++ b/crates/ui-egui/src/panels/viewer_tools.rs @@ -969,12 +969,16 @@ fn bottom_bar_contents(app: &mut EffectcraftApp, ui: &mut egui::Ui, bar: Rect, z let _ = app.session.execute("view.set3DView", json!({"view": View3D::ALL[i].id()})); } x = r.max.x + 4.0; + x = layout_switch(app, ui, x, cy, &t); // Extended Viewer (Settings ▸ 3D): custom views and Draft 3D show past the comp frame. let on = app.session.prefs.three_d.extended_viewer; if tog(ui, &mut app.auto, &mut x, Icon::ExtendedViewer, on, "extendedViewer", "Extended Viewer").0 { let _ = app.session.execute("view.extendedViewer", json!({})); } x += 2.0; + } else { + // A 2D comp has no 3D View menu, but it can still be in a 2/4-view layout: keep the way back. + x = layout_switch(app, ui, x, cy, &t); } // Current time. let tc = crate::panels::timecode(&app.session, comp, time); @@ -1005,6 +1009,34 @@ fn go_to_time_on_click(app: &mut EffectcraftApp, resp: &egui::Response) { } } +/// The "Views: 1 | 2 | 4" switch (#3391): a label and three text buttons, the current layout +/// highlighted; a click runs `view.layout`. Returns the x after it. +fn layout_switch(app: &mut EffectcraftApp, ui: &mut egui::Ui, mut x: f32, cy: f32, t: &Tokens) -> f32 { + let label = crate::i18n::tr("Views:"); + let g = ui.painter().layout_no_wrap(label.to_string(), Tokens::ui(11.0), t.text_dim); + ui.painter().galley(pos2(x, cy - g.size().y / 2.0), g.clone(), t.text_dim); + x += g.size().x + 4.0; + let current = app.session.state.view_layout; + for (n, text, tip) in [(1u8, "1", "1 View"), (2, "2", "2 Views"), (4, "4", "4 Views")] { + let r = Rect::from_min_size(pos2(x, cy - 10.0), vec2(26.0, 20.0)); + let resp = widgets::text_button(ui, r, text, current == n, t, egui::Id::unique(("vw-layout", n))); + // The drawn text is just "1" / "2" / "4": the accessible name is the full "N View(s)", the group + // label ("Views") is its description, and the current layout is exposed as pressed. + let name = crate::i18n::command_label("view.layout", tip); + crate::a11y::choice_button(&resp, name, label.trim_end_matches([':', ':', ' ', '\u{a0}']), current == n); + let resp = resp.on_hover_text(name); + app.auto.add_response(&format!("viewer.layout.{n}"), &resp, tip); + if resp.clicked() + && current != n + && let Err(e) = app.session.execute("view.layout", json!({"views": n})) + { + app.ui.status = e.to_string(); + } + x = r.max.x + 2.0; + } + x + 4.0 +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 8b156cb51..f80611a9b 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -112,6 +112,7 @@ mod ui_toolbar_gradient; mod ui_tracker; mod ui_unreadable_footage; mod ui_video_preview_off; +mod ui_view_layout; mod ui_viewer; mod ui_viewer_trackpad; mod ui_viewers; diff --git a/crates/ui-egui/tests/it/ui_crypto_pick.rs b/crates/ui-egui/tests/it/ui_crypto_pick.rs index c9ed63ef3..28d1b97c2 100644 --- a/crates/ui-egui/tests/it/ui_crypto_pick.rs +++ b/crates/ui-egui/tests/it/ui_crypto_pick.rs @@ -199,17 +199,12 @@ fn lit(h: &mut Harness<'_, EffectcraftApp>, name: &str, p: [f64; 2], scale: f64) img.get((p[0] * scale).floor() as i64, (p[1] * scale).floor() as i64)[0] } -/// Whether ID `got` (a cell name) has the largest coverage of the shown pixel at comp point `p` -/// (a downsampled or scaled layer blends the cells around it). +/// Whether ID `got` (a cell name) lights the shown pixel at comp point `p`. Below one buffer pixel +/// per layer pixel (a reduced resolution, a smaller proxy) the effect shows the matte +/// box-filtered over the layer pixels a shown pixel covers (#3334), so at a cell edge the ID the +/// hover reads under the cursor lights it partly, and need not be the one covering most of it. fn largest(h: &mut Harness<'_, EffectcraftApp>, got: &str, p: [f64; 2], scale: f64) -> bool { - let v = lit(h, got, p, scale); - if v >= 0.5 { - return true; - } - let (cx, cy) = ((p[0] / 37.0).floor() as i64, (p[1] / 29.0).floor() as i64); - let others: Vec = - (-2..=2).flat_map(|dx| (-2..=2).map(move |dy| (cx + dx, cy + dy))).filter(|c| c.0 >= 0 && c.1 >= 0).map(|c| format!("c{}_{}", c.0, c.1)).collect(); - v > 0.0 && others.iter().filter(|o| *o != got).all(|o| lit(h, o, p, scale) <= v + 1e-4) + lit(h, got, p, scale) > 0.0 } #[test] @@ -675,7 +670,10 @@ fn picks_on_the_gpu_viewer() { let sp = comp_to_screen(&h.ctx, [p[0] as f32, p[1] as f32]).unwrap(); let got = hover(&mut h, sp).trim_end_matches(" (selected)").to_string(); let q = to_comp(&h, sp); - assert!(got.starts_with('c') && lit(&mut h, &got, q, scale) >= 0.5, "{res:?}: at {q:?} hover {got:?} is not lit there"); + // (below Full the matte is box-filtered: an edge pixel is lit partly, #3334) + let lit_at = lit(&mut h, &got, q, scale); + let ok = if res == Resolution::Full { lit_at >= 0.5 } else { lit_at > 0.0 }; + assert!(got.starts_with('c') && ok, "{res:?}: at {q:?} hover {got:?} is not lit there ({lit_at})"); checked += 1; } } diff --git a/crates/ui-egui/tests/it/ui_large_project.rs b/crates/ui-egui/tests/it/ui_large_project.rs index 2310087e3..1b41371db 100644 --- a/crates/ui-egui/tests/it/ui_large_project.rs +++ b/crates/ui-egui/tests/it/ui_large_project.rs @@ -73,6 +73,53 @@ fn comp_thumbnail_renders_off_the_ui_thread() { assert!(landed, "thumbnail texture"); } +/// #3271 review: a footage reload that leaves the project's revision as it was (File ▸ Reload +/// Footage, a watched file that changed) gives the Project panel's thumbnail a new key. +#[test] +fn a_footage_reload_gives_the_panel_thumbnail_a_new_key() { + let mut h = harness(large()); + let main = h.state().session.active_comp_id().unwrap(); + h.state_mut().session.execute("project.select", json!({"items": [main.0]})).unwrap(); + h.state_mut().show_panel(PanelKind::Project); + let id = egui::Id::unique(("proj-thumb-key", main.0)); + let shown = |h: &egui_kittest::Harness<'_, EffectcraftApp>| h.ctx.data(|d| d.get_temp::<(u64, u64, u64, i64, u128, f64)>(id)).map(|k| k.4); + let want = |h: &egui_kittest::Harness<'_, EffectcraftApp>| h.state().session.thumbnail_key(main, effectcraft_engine::time::Tick::ZERO, 192); + h.run_steps(2); + let before = shown(&h); + assert!(before.is_some() && before == want(&h)); + let rev = h.state().session.revision; + h.state().session.footage_reloads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + assert_eq!(h.state().session.revision, rev); + let mut now = before; + for _ in 0..100 { + h.step(); + now = shown(&h); + if now != before { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert_ne!(now, before, "a new key after the reload"); + assert_eq!(now, want(&h)); + // A preference that changes what a comp shows (Switches Affect Nested Comps) does too; the + // project's revision stays. + let before = now; + let rev = h.state().session.revision; + let on = h.state().session.prefs.general.switches_affect_nested_comps; + h.state_mut().session.execute("prefs.set", json!({"key": "general.switchesAffectNestedComps", "value": !on})).unwrap(); + assert_eq!(h.state().session.revision, rev); + for _ in 0..100 { + h.step(); + now = shown(&h); + if now != before { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert_ne!(now, before, "a new key after the preference changed"); + assert_eq!(now, want(&h)); +} + #[test] fn timeline_reaches_the_last_of_many_layers() { let mut h = harness(large()); diff --git a/crates/ui-egui/tests/it/ui_view_layout.rs b/crates/ui-egui/tests/it/ui_view_layout.rs new file mode 100644 index 000000000..a6af5c688 --- /dev/null +++ b/crates/ui-egui/tests/it/ui_view_layout.rs @@ -0,0 +1,70 @@ +//! #3391: the Composition viewer's control row has a "Views: 1 | 2 | 4" switch (egui_kittest). + +use effectcraft_engine::Session; +use effectcraft_ui_egui::EffectcraftApp; +use egui_kittest::Harness; +use serde_json::json; + +fn harness(comp: Option<&str>) -> Harness<'static, EffectcraftApp> { + let mut s = Session::default(); + s.execute("file.openDemoProject", json!({})).unwrap(); + if let Some(comp) = comp { + s.execute("comp.open", json!({"comp": comp})).unwrap(); + } + Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|_| EffectcraftApp::new(s)) +} + +/// Click the centre of the automation element `id`. +fn click_id(h: &mut Harness<'_, EffectcraftApp>, id: &str) { + h.run_steps(3); + let [x, y, w, hh] = h.state().auto.find(id).unwrap_or_else(|| panic!("{id} is registered")).rect; + let p = egui::pos2(x + w / 2.0, y + hh / 2.0); + h.input_mut().events.push(egui::Event::PointerMoved(p)); + h.input_mut().events.push(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.step(); + h.input_mut().events.push(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(3); +} + +#[test] +fn the_layout_buttons_switch_between_one_two_and_four_views_in_a_3d_comp() { + let mut h = harness(Some("3D Showcase")); + h.run_steps(3); + assert!(h.state().auto.find("viewer.view3d").is_some(), "this is a 3D comp"); + for (id, want) in [("viewer.layout.4", 4), ("viewer.layout.2", 2), ("viewer.layout.1", 1)] { + click_id(&mut h, id); + assert_eq!(h.state().session.state.view_layout, want, "{id}"); + } +} + +#[test] +fn the_layout_buttons_are_there_in_a_2d_comp_too() { + let mut h = harness(None); + h.run_steps(3); + assert!(h.state().auto.find("viewer.view3d").is_none(), "this is a 2D comp"); + for id in ["viewer.layout.1", "viewer.layout.2", "viewer.layout.4"] { + assert!(h.state().auto.find(id).is_some(), "{id} is registered"); + } + click_id(&mut h, "viewer.layout.4"); + assert_eq!(h.state().session.state.view_layout, 4); +} + +#[test] +fn the_layout_buttons_are_named_in_full_and_expose_the_current_layout() { + use egui::accesskit::{Role, Toggled}; + use egui_kittest::kittest::{NodeT, Queryable}; + let mut h = harness(None); + h.run_steps(3); + let state = |h: &Harness<'_, EffectcraftApp>, name: &str| { + let node = h.query_by_label(name).unwrap_or_else(|| panic!("a button named {name:?}")); + let node = node.accesskit_node(); + assert_eq!(node.role(), Role::Button, "{name}"); + node.toggled() + }; + assert_eq!(state(&h, "1 View"), Some(Toggled::True)); + assert_eq!(state(&h, "2 Views"), Some(Toggled::False)); + assert_eq!(state(&h, "4 Views"), Some(Toggled::False)); + click_id(&mut h, "viewer.layout.2"); + assert_eq!(state(&h, "1 View"), Some(Toggled::False)); + assert_eq!(state(&h, "2 Views"), Some(Toggled::True)); +} diff --git a/crates/ui-egui/tests/it/viewer_geometry.rs b/crates/ui-egui/tests/it/viewer_geometry.rs index 8a212cc35..72ee46013 100644 --- a/crates/ui-egui/tests/it/viewer_geometry.rs +++ b/crates/ui-egui/tests/it/viewer_geometry.rs @@ -19,14 +19,22 @@ fn harness(width: f32, kind: ThemeKind) -> Harness<'static, EffectcraftApp> { fn harness_at_scale(width: f32, kind: ThemeKind, scale: f32) -> Harness<'static, EffectcraftApp> { let mut session = Session::default(); session.execute("comp.new", json!({"name":"Geometry validation", "width":640, "height":360, "duration":4})).unwrap(); - let mut h = Harness::builder().with_size(vec2(width, 360.0)).with_pixels_per_point(scale).build_ui_state( - |ui, app: &mut EffectcraftApp| { - app.auto.begin_frame(); - *app.frames.last_ms.lock().unwrap() = 0.0; - viewer::show(app, ui, ui.max_rect()); - }, - EffectcraftApp::new(session), - ); + let app = EffectcraftApp::new(session); + // Install the fonts the real app installs at startup *before* the harness's first pass: the control + // row draws `widgets::text_button` text in the "medium" family, which has no fonts until then. + let tokens = app.tokens; + let mut h = Harness::builder() + .with_size(vec2(width, 360.0)) + .with_pixels_per_point(scale) + .with_context_setup(move |ctx| theme::install(ctx, &tokens, "en")) + .build_ui_state( + |ui, app: &mut EffectcraftApp| { + app.auto.begin_frame(); + *app.frames.last_ms.lock().unwrap() = 0.0; + viewer::show(app, ui, ui.max_rect()); + }, + app, + ); let ctx = h.ctx.clone(); h.state_mut().set_theme(&ctx, kind); theme::install(&ctx, &h.state().tokens, "en"); @@ -107,7 +115,24 @@ fn compact_control_row_scrolls_and_preserves_interactions() { let timecode = rect(&h, "viewer.timecode"); let row = rect(&h, "viewer.controls"); assert!(timecode.left() >= row.left() && timecode.right() <= row.right(), "last viewer control must scroll into view: {timecode:?}"); + // The Views switch (#3391) widened the row, so the exposure reset is no longer in view at the far + // end: scroll back until it is, then check the scrolled controls as before. + for _ in 0..40 { + let e = rect(&h, "viewer.resetExposure"); + if e.left() >= row.left() && e.right() <= row.right() { + break; + } + h.event(Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(40.0, 0.0), + modifiers: Default::default(), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + }); + h.run_steps(4); + } let exposure = rect(&h, "viewer.resetExposure"); + // The convergence check for the scroll-back loop above: it must have brought the control into view. assert!(exposure.left() >= row.left() && exposure.right() <= row.right()); h.state_mut().session.execute("view.exposure", json!({"stops":2.0})).unwrap(); h.run_steps(2); diff --git a/docs/agents.md b/docs/agents.md index aff59e00a..a83432f04 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -340,8 +340,9 @@ build real projects through these interfaces; they are worked examples of everyt * **OCIO effects**: with Configuration ▸ Custom, `configFile` is a `.ocio` path or the config's text; `effect.warning {layer, effect}` says what Effect Controls warns about (a config it can't read, a colour space it lacks, transforms that pass colours through) or `null`. -* **Multi-layer OpenEXR**: the footage shows the beauty pass (an unnamed RGBA layer, else - Combined / Beauty / Image / RGBA…, never Cryptomatte or depth). `layer.channels {layer}` +* **Multi-layer OpenEXR**: the footage shows the main picture as After Effects does (the + unprefixed `R`, `G`, `B` (`A`) of the first part with them, else `Y` as grey; a file of named + layers only, such as Blender's `ViewLayer.Combined.R`, is black). `layer.channels {layer}` lists a footage layer's EXR layers and channels (`{"layers":[{"name":"diffuse","rgba":["diffuse.R","diffuse.G","diffuse.B",""]}]}`); EXtractoR shows them when its `red` / `green` / `blue` / `alpha` are set to those names diff --git a/docs/architecture.md b/docs/architecture.md index 5caaba19b..1ac306174 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -242,8 +242,9 @@ and undo can reuse earlier content. During rapid edits at the same time and view shows the newest completed revision while the exact requested revision renders; out-of-order completions cannot move it backwards. This avoids freezing until a slider or layer drag stops. Frames at other times or with other render options are never substituted. Obsolete queued jobs -are dropped; running jobs finish into the cache. When the budget (Settings ▸ Memory & CPU) is -full the least recently shown frames go first. The timeline's green bar counts cached frames +are dropped; running jobs finish into the cache. The frames share one memory budget with +the other big caches (Settings ▸ Memory & CPU); when it is full the memory accountant frees the +least valuable data first, by cost to make again per byte and time since last use. The timeline's green bar counts cached frames of the current content and viewer settings. Resolution Auto renders the pixels the magnification needs, as in After Effects (Full above 50 %, Half down to 33.3 %, Third down to 25 %, then Quarter). The Resolution is the comp's diff --git a/docs/footage.md b/docs/footage.md index 7a0639c02..abab92161 100644 --- a/docs/footage.md +++ b/docs/footage.md @@ -117,20 +117,32 @@ false` goes back to Use Source File Timecode). Cineon Settings: `{"logConversion Float OpenEXR renders hold linear light; EffectCraft sRGB-encodes them as they are read, like After Effects with Interpret As Linear Light for 32 bpc, unless the item preserves RGB (above). -A multi-layer file shows its main RGBA channels, as in After Effects. Renders that keep every -pass in named layers (Blender's `ViewLayer.Combined`, its compositor's File Output `Image`, -Nuke's `beauty`) show the beauty pass: the layer named Combined, Beauty, Image, RGBA, RGB or -Color, else the first colour layer that isn't a data pass. Cryptomatte, depth, mist, normals, -vectors, positions and IDs are never the picture. EXtractoR reads every other layer and channel. +A multi-layer file shows its main picture, as in After Effects: the channels without a layer +prefix, `R`, `G`, `B` (and `A`) of the first part that has all three, else the first part that +has a `Y` (its `Y` and `A`) as grey. Renders that keep every pass in named layers (Blender's +`ViewLayer.Combined`, its compositor's File Output `Image`, Nuke's `beauty.R`) have no main +picture and show black at the file's size, as After Effects shows them; EXtractoR (and +Cryptomatte and the 3D Channel effects) read every layer and channel by name. Footage on its own keeps only the channels of its picture (a single-part file still decompresses all of its pixels to read them). Once an effect reads an item's channels (EXtractoR, Cryptomatte, the 3D Channel effects), each frame, the first included, is decoded -once for the picture and the effects together, and kept for a while: about 1 GB of decoded -channels (512 MB in the browser), a soft bound, as the newest file and files still in use -stay whatever their size. Several frames asking for the same file at once wait for one -decode. Once no enabled effect reads the item any more, its frames go back to the picture's -channels alone. +once for the picture and the effects together, and only the channels the effects pick are +read (EXtractoR's channel names, Cryptomatte's layer, the 3D Channel effects' channel popups). +The decoded channels are kept for a while, in the one memory budget the caches share +(Settings ▸ Memory & CPU, see [preferences.md](preferences.md)): the least valuable item goes +first, whichever cache holds it, and among channel sets and frames that cost the same to decode +again, the least recently used; in the browser the channels take at most 256 MB, the footage +frames' cap there. Files still in +use stay whatever their size. The picture is kept once, converted: its own R, G, B and A planes are +not kept beside it, unless an effect names one of them. Several frames asking for the same +file at once wait for one decode. Once no enabled effect reads the item any more, its frames +go back to the picture's channels alone. + +The parameters that pick channels (EXtractoR's Red, Green, Blue and Alpha, Cryptomatte's Layer +and Layer Name, 3D Channel Extract's 3D Channel, ID Matte's Aux. Channel, IDentifier's Channel Type) can't be animated, as in After Effects, where they have no +stopwatch either: they take no keyframes and no expression. A document that animated one +opens with its first value. The Cryptomatte effect keys objects by their Cryptomatte ID passes, with the names from the file's manifest. Pick them with the eyedropper next to its Selection, then click in the diff --git a/docs/preferences.md b/docs/preferences.md index c35d2c793..04f1415f1 100644 --- a/docs/preferences.md +++ b/docs/preferences.md @@ -90,9 +90,6 @@ Commands (CLI, MCP, control channel): - `audio.outputDevice`: Default Output (device list from the desktop host) - `audio.outputLeft`: Left (Audio Output Mapping) - `audio.outputRight`: Right (Audio Output Mapping) -- `memory.layerCacheMb`: Layer Cache (in the browser at most 512 MB, see [web.md](web.md)) -- `memory.mediaCacheMb`: Footage Frame Cache (in the browser at most 256 MB) -- `memory.previewCacheMb`: Preview (RAM) Cache - `memory.gpuFramesInFlight`: GPU Frames Rendered at Once (`auto`, `1`, `2`, `3`): how many frames the Render Queue renders on the GPU at once. Auto measures the GPU memory after the job's first GPU frame and fits up to 3 frames into the GPU memory cap (by default a @@ -185,9 +182,53 @@ Commands (CLI, MCP, control channel): - `disk.mediaCacheFolder`: audio waveform summaries kept between sessions (`Peaks/`) - `disk.conformedMediaFolder`: decoded (conformed) footage audio, written once per file and sample rate and read back instead of decoding again -- `memory.ramReservedGb`: the cache budgets together leave this much physical memory free -- `memory.reduceCacheWhenLow`: cache budgets halve while the system is low on memory (checked - every 30 s by the desktop app, on a background thread) +- `disk.localizeFootage` (off by default), `disk.localizeMaxGb` (20), `disk.localizeFolder`, + `disk.networkFootageLocations`: OpenEXR footage on network shares is copied, one file at a + time on a background thread, to a local folder (by default beside the disk cache's folder), + and read from the copy once it is complete and the source still has the size and modification + time it had when copied. Network footage is UNC paths (`\\server\share\…`) and the locations + listed in `disk.networkFootageLocations` (`;`-separated path prefixes, such as a drive letter + mapped to a share: `P:\`). The copies take at most `disk.localizeMaxGb` and leave the disk + cache's reserve free on their disk; earlier sessions' copies are adopted. The Disk page shows + the local copies, what is queued and being copied, and the network locations +- `memory.ramReservedGb`: RAM Reserved for Other Applications, the one memory setting (After + Effects has a setting of this name too). EffectCraft's big caches (processed layers, also those + of exports and Render Queue runs, decoded footage frames, decoded OpenEXR planes, RAM preview + frames, and the disk cache's write queue) share one budget: 80 % of the installed RAM left + after the reserve. The command-line tool and its MCP server read the installed RAM once at start + (with the default reserve: they don't read the app's settings). The other 20 % is room for + EffectCraft's own working memory (decoders, render buffers, undo, GPU staging, the interface). + With the default 6 GB reserved that is 8.0 GB on a 16 GB machine, 46.4 GB on 64 GB and 97.6 GB + on 128 GB. The budget is at least 192 MB for all caches together; while the installed RAM is + unknown (a sandbox, or the desktop before its first reading) it is 5 GB, in the browser 3.5 GB + (with the RAM preview at most 3 GB there). No cache has a share of its own: when they + hold more than the budget together, the memory accountant frees the least valuable data first, + whichever cache holds it, down to 90 % of the budget. An item's value is what it would cost to + make again (its measured render or decode time; when not measured, a typical 4 ms per MB for a + layer, 8 ms for a preview frame, 2 ms for footage frames and planes) per byte, divided by + `ln(seconds unused + 1) + 1`: a slow decay (about a fifth after a minute unused, a seventh after + ten), so a costly frame unused for minutes still outlives a cheap one; a copy of data another + cache holds (a queued disk write) is worth nothing, and a cache that had to make again what it + let go of shortly before is protected for a while. The frames a playing RAM preview shows next + go last: they may keep the caches over the budget by a tenth of it (at most 1 GB) while other + items can go instead. Besides the bytes the caches count, the process's measured memory is + watched (its resident size, read with each balance and at most every 250 ms): above 95 % of the + installed RAM left after the reserve the caches give way by what it is over even within their + budget (memory nobody counts: GPU staging, effect buffers, the allocator's fragmentation), at + most once per reading unless it grows; above all of it also the preview frames that would + play next. A frame or plane set is written to the disk cache only when making it again costs + more than reading it back (the measured read rate, 10 ms per MB until reads are measured); a + RAM eviction keeps the disk copy, and the disk cache drops its oldest entries first. At most + 256 movie and audio files are kept open, the least recently used closed beyond that (image + sequences, OpenEXR included, keep no file open between decodes). In the browser the layer cache also stays within 512 MB and the footage frames within + 256 MB (see [web.md](web.md)). The Memory & CPU page shows what EffectCraft may use, of the + installed RAM. Settings saved before this (version 4 and earlier) had Layer Cache, Footage + Frame Cache and Preview (RAM) Cache budgets (`memory.layerCacheMb`, `memory.mediaCacheMb`, + `memory.previewCacheMb`); they are dropped when the settings are read +- `memory.reduceCacheWhenLow`: the budget halves while the system is low on memory (less than + 10 % of the RAM, or less than 1 GB, available; checked every 30 s by the desktop app, on a + background thread). It stays halved until twice that much is available again, so freeing the + caches doesn't end the episode at once, and the toast saying so shows once per episode - `video.enableOutput`, `video.device`, `video.outputDuringPlayback`, `video.mirrorOnMonitor`, `video.disableWhenBackground`: Video Preview, a second window (or full screen on the display it is on) showing the composition frame, Mercury Transmit-style diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 09f9df6bc..4abfadb74 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -454,7 +454,7 @@ Mocha and Cineware are third-party and not counted. | Category | Effects | Notes | |---|---|---| -| 3D Channel | 3D Channel Extract, Cryptomatte, Depth Matte, Depth of Field, EXtractoR, Fog 3D, ID Matte, IDentifier | Read auxiliary channels: multi-layer OpenEXR (any `layer.channel`, Cryptomatte manifests from the header; EXtractoR picks a layer and channels from popups of the footage's layers and channels, `layer.channels`, #295; the footage itself shows the beauty pass, never Cryptomatte or depth, #412) or the compositor's own depth / layer-ID / normal / UV / Cryptomatte pass for precomps of 3D comps. | +| 3D Channel | 3D Channel Extract, Cryptomatte, Depth Matte, Depth of Field, EXtractoR, Fog 3D, ID Matte, IDentifier | Read auxiliary channels: multi-layer OpenEXR (any `layer.channel`, Cryptomatte manifests from the header; EXtractoR picks a layer and channels from popups of the footage's layers and channels, `layer.channels`, #295; the footage itself shows After Effects' main picture: the unprefixed RGB(A), else Y, else black) or the compositor's own depth / layer-ID / normal / UV / Cryptomatte pass for precomps of 3D comps. | | Immersive Video | VR Blur, VR Chromatic Aberrations, VR Color Gradients, VR Converter, VR De-Noise, VR Digital Glitch, VR Fractal Noise, VR Glow, VR Plane to Sphere, VR Rotate Sphere, VR Sharpen, VR Sphere to Plane | Seam-aware equirectangular processing (wrap-around, pole continuation, latitude-scaled filters), mono / over-under / side-by-side layouts; VR Converter between equirectangular, cube maps (4:3, 3:2, 6:1), sphere map and 2D. | | Color Correction | OCIO CDL / Color Space / Display / File / Look Transform, Color Stabilizer | Built-in minimal OCIO-style config (ACES2065-1, ACEScg, ACEScct, sRGB, Rec.709, Rec.2020, Display P3, linear variants, XYZ) from published matrices and transfer functions; `.cube` / `.3dl` / `.csp` / `.spi1d` / `.spi3d` / `.spimtx` LUTs and ASC `.cc` / `.ccc` / `.cdl`. Custom `.ocio` config files are read from the OCIO v2 documentation (Configuration ▸ Custom: colorspaces and display colorspaces with the scene / display reference spaces joined by the default view transform, roles, displays with v1 and v2 views, view transforms, looks; Matrix, File, Exponent, ExponentWithLinear, Log, LogAffine, CDL, Range, Allocation, ColorSpace, Look, DisplayView, Builtin (matrices and display curves) and Group transforms), so Blender 4.x / 5.x configs give the Standard, AgX, Filmic and False Color views (#410). Grading Primary / Tone transforms, the ACES output and gamut-compression builtins and HLG pass colours through, and the effect shows a warning naming them (`effect.warning`). | | Distort | CC Flo Motion, Liquify, Rolling Shutter Repair | Liquify strokes are effect data replayed into a displacement mesh (`liquify.stroke` / `liquify.clear` commands; no interactive viewer brush yet). Rolling Shutter Repair uses the KLT tracker. | diff --git a/docs/web.md b/docs/web.md index f4eb882a8..00dc8c977 100644 --- a/docs/web.md +++ b/docs/web.md @@ -61,7 +61,7 @@ device of their own), `?nosw` (don't register the service worker). | config directory: settings, shortcut presets, recent projects, the recovery sentinel | `store::WebConfig` in browser storage | | auto-save folder | `/EffectCraft Auto-Save/` in browser storage (`ConfigStore::files`) | | media reads (`MediaPool`, `probe`) | `files::WebImporter`: bytes from the file table, handed to `MediaPool::add_bytes` / `probe_bytes` | -| Memory & CPU cache budgets, scaled to the system's RAM | the page's memory, at most 4 GiB (wasm32), which the caches share with the decoders' own decoded frames (FilmCraft keeps up to 384 MB per open movie): the Layer Cache stays within 512 MB and the Footage Frame Cache within 256 MB (`Prefs::cache_budgets`) | +| One cache budget from the system's RAM | the page's memory, at most 4 GiB (wasm32), which the caches share with the decoders' own decoded frames (FilmCraft keeps up to 384 MB per open movie): the installed RAM is unknown, so the caches share 3.5 GB, and within that the RAM preview stays within 3 GB, the layer cache within 512 MB and the footage frames within 256 MB (`Prefs::memory_budget`, `MemoryBudget::caps`) | | export writes (`effectcraft-export`) | the job's `sink` (`effectcraft_host::FileExporter { sink }`): files land in the table and download after the render; several files (an image sequence) download as one stored `.zip` | | rfd file dialogs | `` for File ▸ Open / Import; drop files anywhere on the page (`.ecproj` opens, everything else imports); "Save As" / "Output To" pick a download name | | Media Browser on the file system | browser storage and folders opened with the File System Access API (below) |