Merge main into feat/import-photocraft

This commit is contained in:
dotCooCoo committed 2026-11-19 07:28:11 -08:00
commit f5bbbd2d64
111 files changed
+14340 -1922

No files matched your search

Generated
+17 -3
View File
@@ -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]]
+4 -2
View File
@@ -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"
+4 -3
View File
@@ -470,10 +470,11 @@ fn backend(args: &Args, default_demo: bool) -> Result<Backend, Failure> {
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<effectcraft_engine::Session, Failure> {
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
+15
View File
@@ -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"]);
+4
View File
@@ -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)?))
}
+5
View File
@@ -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
+9
View File
@@ -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));
}
+32
View File
@@ -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<Arc<Image>> {
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<Arc<Image>> {
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<Arc<effectcraft_engine::render::disk_cache::Frame8>> {
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<Arc<AuxChannels>> {
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<Arc<AuxChannels>> {
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<Arc<AuxChannels>> {
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<effectcraft_engine::render::LocalizeConfig>) {
self.inner.set_localizer(config)
}
/// The inner source's localizer state.
fn localize_status(&self) -> Option<effectcraft_engine::render::LocalizeReport> {
self.inner.localize_status()
}
/// Forwards the disk cache to the inner source.
fn set_disk_cache(&self, cache: Option<Arc<effectcraft_engine::render::disk_cache::DiskCache>>) {
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<Arc<effectcraft_model::Model>> {
self.readable(footage).then(|| self.inner.model(item, footage)).flatten()
+384 -112
View File
@@ -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(&param))
}
/// 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<Vec<AuxLookup>> {
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<f64> {
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<Arc<AuxChannels>> {
ctx.env.host?.aux()
}
@@ -409,67 +488,9 @@ pub fn selection_hashes(sel: &str, manifest: Option<&[(String, u32)]>) -> Vec<u3
out
}
/// 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<String>) {
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<String> {
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<String> {
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<f32>,
}
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<usize> {
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::<f32>())
}
/// 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<usize>, 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<f64> {
(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<Vec<(usize, f64)>> {
(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<BoxSize> {
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<Option<usize>> {
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<EffectSpec> {
#[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", &params);
params.values.insert("useCoverage".into(), effectcraft_keyframe::Value::Bool(true));
let on = super::aux_needs("ec.3d.idmatte", &params);
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, &params).is_some(), "{id}");
}
}
}
+248 -10
View File
@@ -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<f32>> = 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: &params,
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::<Vec<f32>>();
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::<Vec<f32>>();
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::<Vec<_>>();
for (id, vals) in cases {
let need = aux_needs(id, &params_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");
}
+5 -3
View File
@@ -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()),
+47
View File
@@ -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<String> {
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;
+1
View File
@@ -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 }
+1 -1
View File
@@ -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;
+20 -1
View File
@@ -262,6 +262,8 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
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<String> = 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<Value> {
};
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<Value> {
};
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<Value> {
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`
+4 -8
View File
@@ -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}") });
+2 -1
View File
@@ -553,7 +553,8 @@ fn paste_links(s: &mut Session, clip: LinkClip) -> Result<Value> {
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;
}
+13 -5
View File
@@ -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, &params),
_ => 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<Uid>) -> bool {
pub(crate) fn moves(g: &PropGroup, skip: Option<Uid>) -> 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<Value> {
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<std::sync::Arc<effectcraft_raster::AuxChannels>> {
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()))
}
}
+3 -1
View File
@@ -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))
}
+6 -1
View File
@@ -61,7 +61,8 @@ fn root_comps(project: &Project) -> Vec<ItemId> {
fn import_project(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
.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));
}
+49 -4
View File
@@ -505,7 +505,7 @@ fn toggle_key_selected(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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<Value> {
fn toggle_key(s: &mut Session, p: &Value) -> Result<Value> {
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<String>, enabled: Option<bool>, 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<String>, enabled: Option<bool>, 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<Value> {
@@ -766,14 +787,31 @@ fn set_expr(s: &mut Session, p: &Value) -> Result<Value> {
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(&times) {
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<Value> {
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![];
+1
View File
@@ -867,6 +867,7 @@ fn save_current_preview(s: &mut Session, p: &Value) -> Result<Value> {
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));
+4
View File
@@ -107,6 +107,8 @@ struct PrerenderCx {
expr: Option<Arc<dyn effectcraft_render::ExprHost>>,
accel: Option<Arc<dyn effectcraft_render::Accelerator>>,
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<Value> {
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).
+4
View File
@@ -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<Value, String> {
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": []}),
@@ -341,6 +341,8 @@ pub(crate) fn forget_media(s: &mut Session, paths: &BTreeSet<String>) {
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);
}
+12
View File
@@ -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<sysinfo::SysMemory>,
/// 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<KeyMove>,
/// 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<String, footage_reload::Stamp>,
/// 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<Vec<String>>,
/// 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<Vec<(String, effectcraft_raster::channels3d::AuxNeed)>>,
/// 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(),
}
}
+25 -9
View File
@@ -43,20 +43,31 @@ pub struct ExportJob<'a> {
pub renderer: Option<&'a Mutex<Option<effectcraft_render::Backend>>>,
/// Settings ▸ Memory & CPU ▸ GPU Frames Rendered at Once: 1 to 3, `None` for Auto.
pub gpu_frames: Option<usize>,
/// 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<usize>,
}
/// 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<effectcraft_render::LayerCache>,
pub cpu: std::sync::Arc<effectcraft_render::LayerCache>,
}
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<dyn effectcraft_render::memory::MemoryHolder> = 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<usize>,
/// 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 {
+32
View File
@@ -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<usize>);
struct Budgets(Mutex<Vec<Seen>>);
impl Exporter for Budgets {
fn formats(&self) -> Vec<OutputFormat> {
OutputFormat::ALL.to_vec()
}
fn export(&self, job: &ExportJob, _: &mut dyn FnMut(u64, u64) -> bool) -> Result<ExportResult, String> {
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.
+18 -3
View File
@@ -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<String> {
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
}
+75
View File
@@ -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<u128> {
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<u8>)> {
@@ -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<String, AuxNeed> = 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, &params);
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
+5 -2
View File
@@ -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";
+10 -4
View File
@@ -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<Page> {
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<Page> {
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) => {
+21 -4
View File
@@ -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);
+91 -55
View File
@@ -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<crate::sysinfo::SysMemory>) -> 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<crate::sysinfo::SysMemory>) -> 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<crate::sysinfo::SysMemory>, 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<crate::sysinfo::SysMemory>, 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<u64>,
/// 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] {
+10 -6
View File
@@ -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.
+109 -10
View File
@@ -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<effectcraft_render::LocalizeConfig> {
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<effectcraft_render::LocalizeReport> {
self.footage.localize_status()
}
/// Settings ▸ Disk ▸ Conformed Audio Folder (decoded footage audio, see
/// `MediaPool::set_conform_folder`).
pub fn conformed_audio_folder(&self) -> Option<std::path::PathBuf> {
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<dyn effectcraft_render::memory::MemoryHolder> = 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::sysinfo::SysMemory>) -> 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<dyn effectcraft_render::memory::MemoryHolder> = 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<dyn effectcraft_effects::roto::SegStore> = 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<std::path::PathBuf> {
setting.split([';', '\n']).map(str::trim).filter(|s| !s.is_empty()).map(std::path::PathBuf::from).collect()
}
+28 -1
View File
@@ -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<SysMemory> {
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<u64> {
#[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<SysMemory> {
#[cfg(target_os = "linux")]
+1
View File
@@ -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;
+204
View File
@@ -18,6 +18,7 @@ use crate::render::{FootageSource, RenderOpts};
struct Recorder {
sets: Mutex<Vec<Vec<String>>>,
at_first_frame: Mutex<Option<Option<Vec<String>>>>,
needs: Mutex<Vec<(String, effectcraft_raster::channels3d::AuxNeed)>>,
}
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<Recorder>, 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);
}
+18 -8
View File
@@ -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<Item = f64> + 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}"));
}
}
+33
View File
@@ -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<Vec<Option<usize>>>);
impl Exporter for Budgets {
fn formats(&self) -> Vec<OutputFormat> {
OutputFormat::ALL.to_vec()
}
fn export(&self, job: &ExportJob, _: &mut dyn FnMut(u64, u64) -> bool) -> Result<ExportResult, String> {
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();
+146 -30
View File
@@ -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]
+13 -6
View File
@@ -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<usize>);
impl effectcraft_render::FootageSource for Src {
fn frame(&self, _: effectcraft_project::ItemId, _: &effectcraft_project::Footage, _: effectcraft_time::Tick) -> Option<Arc<effectcraft_raster::Image>> {
@@ -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]
+67
View File
@@ -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<effectcraft_project::Footage, String> {
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);
}
+2 -1
View File
@@ -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 }
+37 -70
View File
@@ -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: Write + Seek>(
(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<usize>| -> [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<usize>| {
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<usize>| {
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<f32> {
@@ -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);
}
}
+5
View File
@@ -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<u64> + 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<usize>,
}
/// The layer caches of a Render Queue run (see [`JobOptions::caches`]): one per compositor,
+44 -4
View File
@@ -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<LayerCache>, cpu: Box<LayerCache> },
Own { gpu: std::sync::Arc<LayerCache>, cpu: std::sync::Arc<LayerCache> },
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<dyn effectcraft_render::memory::MemoryHolder> = 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]
+72 -25
View File
@@ -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<GpuImage> = 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<GpuImage> {
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<GBuf> {
@@ -236,7 +241,7 @@ fn id_matte(e: &mut Enc, ctx: &EffectCtx, b: GBuf, a: &AuxChannels) -> Option<GB
let Some(ids) = id_plane(a, pr.e("auxChannel")) else { return Some(b) };
let cov = if pr.b("useCoverage") { a.coverage() } else { None };
let tex = aux_texture(e, a, [Some(ids), cov, 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 (w, h) = (b.img.width, b.img.height);
let mut p = op(4);
p.u[0][1] = cov.is_some() as u32;
@@ -257,7 +262,7 @@ fn identifier(e: &mut Enc, ctx: &EffectCtx, b: GBuf, a: &AuxChannels) -> 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<GBuf> {
fn cryptomatte(e: &mut Enc, ctx: &EffectCtx, b: GBuf, a: &Arc<AuxChannels>) -> Option<GBuf> {
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<GpuImage> {
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<Vec<(CryptoOutput, u32, u32, usize)>> = std::sync::Mutex::new(Vec::new());
// ---------------------------------------------------------------- EXtractoR
fn extractor(e: &mut Enc, ctx: &EffectCtx, b: GBuf, a: Option<&AuxChannels>) -> Option<GBuf> {
@@ -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,
};
+195
View File
@@ -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<u32>,
output: CryptoOutput,
/// The render scale the plane is box-filtered to (its bits), `None` at source resolution.
scale: Option<u64>,
}
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<AuxChannels>,
key: Key,
plane: Arc<CryptoPlane>,
/// Last use ([`memory::tick`]) and what making it took (µs).
used: u64,
cost_us: u64,
}
impl Entry {
fn of(&self, a: &Arc<AuxChannels>) -> 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<Entry>,
/// Planes made so far (tests).
made: u64,
}
static CACHE: Mutex<Cache> = 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<Arc<dyn MemoryHolder>> = OnceLock::new();
HOLDER.get_or_init(|| {
let h: Arc<dyn MemoryHolder> = 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<AuxChannels>, layer: &str, sel: &[u32], output: CryptoOutput, render_scale: f64) -> Arc<CryptoPlane> {
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<AuxChannels>, layer: &str, sel: &[u32], output: CryptoOutput, render_scale: f64, max_bytes: usize, budget: usize) -> Arc<CryptoPlane> {
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<usize> = 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<usize> {
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<Candidate> {
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<AuxChannels>, layer: &str, sel: &[u32], output: CryptoOutput, max_bytes: usize, budget: usize) -> Arc<CryptoPlane> {
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<CryptoPlane>) -> 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<dyn MemoryHolder> {
Arc::new(Holder)
}
+7 -5
View File
@@ -198,15 +198,17 @@ fn fxd_point(@builtin(global_invocation_id) gid: vec3<u32>) {
}
}
}
// 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<f32>(m, m, m, 1.0), vec4<f32>(m), P.u[0].w != 0u);
} else if (P.u[0].y == 0u) {
o = vec4<f32>(q.xyz * (1.0 - 0.5 * m) + 0.5 * m, 1.0);
o = vec4<f32>(q.xyz, 1.0);
} else if (P.u[0].y == 1u) {
o = px * m;
} else {
+1
View File
@@ -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;
+85
View File
@@ -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<f32> = 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: &params,
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<f64> = (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]);
}
}
}
+184 -1
View File
@@ -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: &params,
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))]);
+26
View File
@@ -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<usize> {
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<effectcraft_engine::HelperHooks> {
+6 -3
View File
@@ -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");
+3 -2
View File
@@ -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();
+1
View File
@@ -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;
+31
View File
@@ -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");
}
+2
View File
@@ -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 }
File diff suppressed because it is too large. Load diff
+373
View File
@@ -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<usize>,
/// 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<usize>)> {
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<IndexChannel>,
/// 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<MainPicture>,
/// 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<AuxChannels>,
}
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<usize> {
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<usize> {
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<Item = &'a str>) -> Vec<usize> {
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::<usize>()).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<seek::Index, seek::Error> {
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<ExrIndex, IndexError> {
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/<key>/name` and `…/manifest`, in any
/// part), sorted.
fn manifests(parts: &[PartInfo]) -> Vec<(String, Vec<(String, u32)>)> {
let mut crypto: HashMap<String, (Option<String>, Option<String>)> = 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<MainPicture> {
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::<Option<Vec<usize>>>()?;
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<String, Arc<ExrIndex>>,
order: VecDeque<String>,
bytes: usize,
}
fn indexes() -> &'static Mutex<Indexes> {
static INDEXES: std::sync::OnceLock<Mutex<Indexes>> = 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<ExrIndex>) {
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<Arc<ExrIndex>, 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<ExrIndex>, Option<Opened>), 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<Arc<ExrIndex>> {
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);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+333
View File
@@ -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<T: Read + Seek + Send> 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<dyn ReadSeek>,
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<std::path::PathBuf, (FileStamp, std::time::Instant)>;
#[cfg(not(target_arch = "wasm32"))]
fn stamps() -> std::sync::MutexGuard<'static, Stamps> {
static STAMPS: std::sync::OnceLock<std::sync::Mutex<Stamps>> = 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<FileStamp> {
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<FileStamp> {
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<FileStamp> {
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<Opened> {
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<Opened> {
#[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<usize>,
/// Rows of the display window (full resolution); `None`: all.
pub(crate) rows: Option<Range<i64>>,
/// 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<usize>) -> 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<usize>,
/// 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<Vec<Vec<f32>>, 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::<f32>());
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<Vec<f32>>, 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::<f32>());
// (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))
}
+20 -1
View File
@@ -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<Vec<std::path::PathBuf>> = 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()
}
+954
View File
@@ -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<LocalizeConfig>,
copies: HashMap<PathBuf, Copy>,
queue: VecDeque<PathBuf>,
queued: HashSet<PathBuf>,
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<PathBuf>,
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<State>, Condvar) {
static STATE: std::sync::OnceLock<(Mutex<State>, 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<LocalizeConfig>) {
// (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<String> {
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<PathBuf> = 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<LocalizeReport> {
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<Vec<PathBuf>> = 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<PathBuf> {
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<Evicted>, epoch: u64) -> Vec<PathBuf> {
let stuck: Vec<Evicted> = 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<PathBuf>) -> Vec<Evicted> {
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<u64> {
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<Vec<PathBuf>> = Mutex::new(Vec::new());
/// Runs before each copy, with the source's path (tests).
#[cfg(test)]
type CopyHook = std::sync::Arc<dyn Fn(&Path) + Send + Sync>;
#[cfg(test)]
static BEFORE_COPY: Mutex<Option<CopyHook>> = Mutex::new(None);
/// Runs before a folder is adopted, with the folder (tests).
#[cfg(test)]
static BEFORE_ADOPT: Mutex<Option<CopyHook>> = 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<Option<CopyHook>> = 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<PathBuf>) -> Option<LocalizeConfig> {
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(&copy).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<dyn Fn() -> 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<dyn Fn() -> 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);
}
}
+1396 -85
View File
File diff suppressed because it is too large. Load diff
+13 -4
View File
@@ -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))
+54 -51
View File
@@ -248,8 +248,9 @@ fn files() -> Vec<(&'static str, Vec<u8>, 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),
+135 -27
View File
@@ -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<Vec<(Tick, Tick)>> {
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));
+272
View File
@@ -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<Vec<(Tick, Tick)>> {
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::Property>) -> 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);
}
+2 -2
View File
@@ -127,7 +127,7 @@ pub fn read_descriptor(r: &mut Reader) -> Result<Descriptor> {
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),
+61 -66
View File
@@ -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<VectorMask> {
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<f64> { 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<Node> {
+6
View File
@@ -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()
+70
View File
@@ -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<u8>), key: [u8; 4], expected: Vec<u8>) {
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);
}
}
+40
View File
@@ -0,0 +1,40 @@
use super::*;
fn scalars(blocks: Vec<([u8; 4], Vec<u8>)>) -> (Option<u32>, 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));
}
}
}
+53
View File
@@ -0,0 +1,53 @@
use super::*;
fn parse_section_blocks(blocks: Vec<([u8; 4], Vec<u8>)>) -> (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"));
}
}
}
@@ -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<u8> {
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<u8>)>) -> (Option<descriptor::Descriptor>, Option<[f64; 3]>, Option<Adjustment>) {
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)]));
}
}
+115
View File
@@ -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<u8> {
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<Vec<u8>>) -> Option<TextInfo> {
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));
}
+85
View File
@@ -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<u8> {
let mut out = selector.to_be_bytes().to_vec();
out.extend_from_slice(&data);
out
}
fn length(selector: u16, count: u16) -> Vec<u8> {
let mut data = [0; 24];
data[..2].copy_from_slice(&count.to_be_bytes());
record(selector, data)
}
fn knot(selector: u16) -> Vec<u8> {
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<u8>) -> Option<VectorMask> {
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<u8> {
[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());
}
}
}
+8 -32
View File
@@ -434,30 +434,14 @@ pub fn solid_color_block(rgb: [f64; 3]) -> ([u8; 4], Vec<u8>) {
/// `hue2`: Hue/Saturation (master).
pub fn hue_sat_block(hue: i16, sat: i16, light: i16) -> ([u8; 4], Vec<u8>) {
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<u8>) {
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<u8>) {
@@ -465,21 +449,13 @@ pub fn invert_block() -> ([u8; 4], Vec<u8>) {
}
pub fn brightness_block(brightness: i16, contrast: i16) -> ([u8; 4], Vec<u8>) {
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<u8>) {
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.
+309 -28
View File
@@ -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<f32>)>,
/// 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<String>,
}
/// 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<String>),
/// 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<AuxLookup>),
}
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<Vec<String>> {
let AuxNeed::Lookups(lookups) = self else { return None };
let mut picked = vec![false; names.channels.len()];
let mut mark = |i: Option<usize>| {
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<usize> {
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<usize> {
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<String> {
let mut v: Vec<String> =
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<String> = 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<usize> {
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<String> {
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<String>) {
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<String> {
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<String> {
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));
}
}
+1
View File
@@ -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 }
+31 -1
View File
@@ -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<Arc<effectcraft_raster::AuxChannels>> {
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<Arc<effectcraft_raster::AuxChannels>> {
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<AuxNeed> = 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, &params);
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<EvalCtx<'a>> {
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<Arc<Buf>> {
// 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);
+197 -46
View File
@@ -54,10 +54,17 @@ struct Entry {
files: Arc<ReadFiles>,
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<u64, Entry>,
/// 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<u64, u64>,
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<u64, web_time::Instant>,
/// 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<u64>,
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<u64> {
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<u64> {
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<Entry> {
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<Buf>, files: Arc<ReadFiles>) -> (Arc<Buf>, Arc<ReadFiles>) {
/// `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<Buf>, files: Arc<ReadFiles>, took: Option<std::time::Duration>) -> (Arc<Buf>, Arc<ReadFiles>) {
let bytes = buf.img.data.len() * std::mem::size_of::<effectcraft_raster::Px>();
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<usize>) -> 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<crate::memory::Candidate> {
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() {
File diff suppressed because it is too large. Load diff
+113 -1
View File
@@ -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<Arc<Image>> {
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<Arc<effectcraft_raster::AuxChannels>> {
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<Arc<effectcraft_raster::AuxChannels>> {
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<Arc<effectcraft_raster::AuxChannels>> {
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<Arc<crate::disk_cache::DiskCache>>) {}
/// 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<LocalizeConfig>) {}
/// What the localizer is doing (`None`: off or not supported).
fn localize_status(&self) -> Option<LocalizeReport> {
None
}
/// The parsed 3D model of a [`effectcraft_project::FootageKind::Model`] item (Advanced 3D).
fn model(&self, _item: ItemId, _footage: &Footage) -> Option<Arc<effectcraft_model::Model>> {
None
@@ -180,12 +230,37 @@ impl FootageSource for CancellableFootage<'_> {
fn audio(&self, item: ItemId, footage: &Footage, t: Tick, frames: usize, rate: u32) -> Option<Vec<f32>> {
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<Arc<effectcraft_raster::AuxChannels>> {
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<Arc<effectcraft_raster::AuxChannels>> {
self.read(|| self.inner.aux_for(item, footage, t, need))
}
fn aux_names(&self, item: ItemId, footage: &Footage, t: Tick) -> Option<Arc<effectcraft_raster::AuxChannels>> {
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<Arc<crate::disk_cache::DiskCache>>) {
self.inner.set_disk_cache(cache)
}
fn set_localizer(&self, config: Option<LocalizeConfig>) {
self.inner.set_localizer(config)
}
fn localize_status(&self) -> Option<LocalizeReport> {
self.inner.localize_status()
}
fn model(&self, item: ItemId, footage: &Footage) -> Option<Arc<effectcraft_model::Model>> {
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<Arc<Image>> {
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<Arc<Image>> {
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<Arc<crate::disk_cache::Frame8>> {
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<std::path::PathBuf>,
/// The copies' disk: `(total, available)` bytes, `None` unknown.
pub disk_space: Option<Arc<dyn Fn() -> 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<String>,
/// The locations that count as network besides UNC paths.
pub network: Vec<String>,
/// Free disk space holds the copies below the size limit.
pub reserve_limited: bool,
}
+4 -1
View File
@@ -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,
File diff suppressed because it is too large. Load diff
+126 -2
View File
@@ -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<Arc<Image>> {
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<f64> = [[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<Arc<Image>> {
// 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<Arc<Buf>> {
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<f64> {
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, &params)?);
}
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 {
+200
View File
@@ -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<Vec<Option<(i64, i64)>>>,
by_rows: bool,
}
impl FootageSource for Counting {
fn frame(&self, item: ItemId, f: &Footage, t: Tick) -> Option<Arc<Image>> {
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<Arc<Image>> {
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<Arc<Image>> {
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<Arc<Image>> {
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<Arc<Image>> {
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<Arc<Image>> {
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<bool> = const { std::cell::Cell::new(false) };
}
#[derive(Default)]
struct Channels {
reads: Mutex<Vec<bool>>,
}
impl FootageSource for Channels {
fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option<Arc<Image>> {
None
}
fn cancellable(&self, _: &Arc<AtomicBool>, 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<Arc<effectcraft_raster::AuxChannels>> {
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,
+11
View File
@@ -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| {
+3 -1
View File
@@ -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).
+108 -6
View File
@@ -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<DiskSince>,
/// 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<Arc<ReadFiles>>, since: Option<DiskSince>) {
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<Arc<ReadFiles>>, since: Option<DiskSince>, took: Option<std::time::Duration>) {
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<usize> {
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<usize> {
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<usize> {
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<Mutex<Cache>>);
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<effectcraft_engine::render::memory::Candidate> {
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<Mutex<Cache>>,
/// The preview frames in the common memory budget (#3271), held here (registered weakly).
_memory: Arc<dyn effectcraft_engine::render::memory::MemoryHolder>,
/// Keys queued or rendering.
inflight: Arc<Mutex<HashSet<FrameKey>>>,
/// 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<dyn effectcraft_engine::render::memory::MemoryHolder> = 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);
}
+171
View File
@@ -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<Project>, 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<Vec<Candidate>>);
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<Candidate> {
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<dyn MemoryHolder> = 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<dyn MemoryHolder> = 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() {
+115 -32
View File
@@ -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"),
+85 -13
View File
@@ -120,13 +120,13 @@ pub fn drop_folder(project: &effectcraft_engine::project::Project, row: Option<I
if it.is_folder() { Some(it.id) } else { it.parent }
}
/// A Project panel thumbnail: (the revision it shows, its texture).
/// A Project panel thumbnail: (the content key it shows, its texture).
#[derive(Clone)]
struct Thumb(u64, egui::TextureHandle);
struct Thumb(u128, egui::TextureHandle);
/// A thumbnail being rendered off the UI thread: (revision, result slot).
/// A thumbnail being rendered off the UI thread: (content key, result slot).
#[derive(Clone)]
struct PendingThumb(u64, Arc<Mutex<Option<Option<(u32, u32, Vec<u8>)>>>>);
struct PendingThumb(u128, Arc<Mutex<Option<Option<(u32, u32, Vec<u8>)>>>>);
/// The Project panel's thumbnail texture of `item`, once its render has landed.
pub fn cached_thumbnail(ctx: &egui::Context, item: ItemId) -> Option<egui::TextureHandle> {
@@ -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::<ThumbKey>(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::<ThumbKey>(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<egui::TextureHandle> {
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<Thumb> = 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<egu
}
}
}
if have == Some(rev) {
// (a key held back is of an earlier state: a render of the state now must not be kept under
// it, so the thumbnail shown stays until the key is worked out again)
if have == Some(rev) || !current {
return tex;
}
let t = app.session.state.times.get(&it.id).copied().unwrap_or_default();
let job = app.session.thumbnail_job(it.id, t, 192)?;
let job = app.session.thumbnail_job(it.id, t, THUMB_SIDE)?;
let slot: Arc<Mutex<Option<Option<(u32, u32, Vec<u8>)>>>> = 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::<PendingThumb>(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::<ThumbKey>(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::<PendingThumb>(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::<ThumbKey>(kkey));
thumbnail(&app, &ctx, &it);
assert!(ctx.data(|d| d.get_temp::<PendingThumb>(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.
+109 -2
View File
@@ -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<egui::Response> = 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<std::time::Duration> {
(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<u64>) -> 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");
}
}
+32
View File
@@ -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::*;
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff. Show more