mirror of
https://github.com/storytold/effectcraft.git
synced 2026-11-28 17:19:14 +01:00
Preserve frozen Object Matte data on project import (#4126)
* Preserve frozen Object Matte data on project import * Discard frozen mattes when import changes a nested source * Verify frozen matte media and layer inputs on import --------- Co-authored-by: ViktorBystrov72 <18964918+ViktorBystrov72@users.noreply.github.com> Co-authored-by: Fredrik Hallin <fredrik.hallin@guidelinegeo.com>
This commit is contained in:
11 files changed
+763
-24
No files matched your search
Generated
+1
@@ -2605,6 +2605,7 @@ dependencies = [
|
||||
"same-file",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tempfile",
|
||||
"thiserror 2.0.21",
|
||||
"web-time",
|
||||
|
||||
@@ -607,6 +607,10 @@ impl Services for ConfinedServices {
|
||||
self.confinement.check(path, Access::Read).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e.to_string()))?;
|
||||
self.inner.read_file(path)
|
||||
}
|
||||
fn file_fingerprint(&self, path: &str) -> std::io::Result<[u8; 32]> {
|
||||
self.confinement.check(path, Access::Read).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e.to_string()))?;
|
||||
self.inner.file_fingerprint(path)
|
||||
}
|
||||
fn write_file(&self, path: &str, data: &[u8]) -> std::io::Result<()> {
|
||||
self.inner.write_file(path, data)
|
||||
}
|
||||
|
||||
@@ -191,14 +191,14 @@ pub fn roto_data(params: &Params, layer_size: [f64; 2], f: i64, with_model: bool
|
||||
/// Seed of the chain keys: what the frames are (the Input Key), the layer size, the frame rate,
|
||||
/// the mode and the model. The prompt is in each frame's key.
|
||||
pub fn seed(params: &Params, layer_size: [f64; 2], fps: f64, model: Option<&dyn MaskModel>) -> u64 {
|
||||
seed_of(params, layer_size, fps, model.map_or(effectcraft_segment::CLASSICAL, |m| m.info().id))
|
||||
seed_of(params, layer_size, fps, model.map_or(effectcraft_segment::CLASSICAL, |m| m.info().id), s(params, INPUT_KEY))
|
||||
}
|
||||
|
||||
/// [`seed`] for the model with id `model` ([`effectcraft_segment::CLASSICAL`]: no model).
|
||||
fn seed_of(params: &Params, layer_size: [f64; 2], fps: f64, model: &str) -> u64 {
|
||||
fn seed_of(params: &Params, layer_size: [f64; 2], fps: f64, model: &str, input_key: &str) -> u64 {
|
||||
let mut h = 0xcbf2_9ce4_8422_2325;
|
||||
fnv(&mut h, ID.as_bytes());
|
||||
fnv(&mut h, s(params, INPUT_KEY).as_bytes());
|
||||
fnv(&mut h, input_key.as_bytes());
|
||||
for v in [layer_size[0], layer_size[1], fps] {
|
||||
fnv(&mut h, &v.to_bits().to_le_bytes());
|
||||
}
|
||||
@@ -260,12 +260,12 @@ pub fn frame_keys(params: &Params, layer_size: [f64; 2], fps: f64, frames: &[i64
|
||||
/// What frozen mattes depend on: what the frames are (the seed: Input Key, size, rate, mode,
|
||||
/// model), the prompt, the tracked span and the matte settings.
|
||||
pub fn frozen_key(params: &Params, layer_size: [f64; 2], fps: f64, model: Option<&dyn MaskModel>) -> String {
|
||||
frozen_key_of(params, layer_size, fps, model.map_or(effectcraft_segment::CLASSICAL, |m| m.info().id))
|
||||
frozen_key_of(params, layer_size, fps, model.map_or(effectcraft_segment::CLASSICAL, |m| m.info().id), s(params, INPUT_KEY))
|
||||
}
|
||||
|
||||
/// [`frozen_key`] for the model with id `model` ([`effectcraft_segment::CLASSICAL`]: no model).
|
||||
fn frozen_key_of(params: &Params, layer_size: [f64; 2], fps: f64, model: &str) -> String {
|
||||
let mut h = seed_of(params, layer_size, fps, model);
|
||||
fn frozen_key_of(params: &Params, layer_size: [f64; 2], fps: f64, model: &str, input_key: &str) -> String {
|
||||
let mut h = seed_of(params, layer_size, fps, model, input_key);
|
||||
let base = reference_frame(params);
|
||||
if let Some(st) = prompt_strokes(params, layer_size, base, model != effectcraft_segment::CLASSICAL) {
|
||||
fnv(&mut h, serde_json::to_string(&st).unwrap_or_default().as_bytes());
|
||||
@@ -277,6 +277,23 @@ fn frozen_key_of(params: &Params, layer_size: [f64; 2], fps: f64, model: &str) -
|
||||
format!("{h:016x}")
|
||||
}
|
||||
|
||||
fn known_models() -> impl Iterator<Item = &'static str> {
|
||||
std::iter::once(effectcraft_segment::CLASSICAL).chain(effectcraft_segment::MODELS.iter().map(|m| m.id))
|
||||
}
|
||||
|
||||
/// Reassign the Input Key of a freeze whose matte settings and original key still match.
|
||||
/// The native-project importer does this after reassigning the IDs of otherwise unchanged inputs.
|
||||
pub fn rekey_frozen_input(params: &Params, layer_size: [f64; 2], fps: f64, input_key: &str, media_fingerprint: &str) -> Option<String> {
|
||||
let mut cache = FrozenCache::from_json(s(params, FROZEN))?;
|
||||
if cache.media_fingerprint.as_deref().unwrap_or_default() != media_fingerprint {
|
||||
return None;
|
||||
}
|
||||
let old_input = s(params, INPUT_KEY);
|
||||
let model = known_models().find(|id| cache.key == frozen_key_of(params, layer_size, fps, id, old_input))?;
|
||||
cache.key = frozen_key_of(params, layer_size, fps, model, input_key);
|
||||
Some(cache.to_json())
|
||||
}
|
||||
|
||||
/// Whether the instance is frozen (has frozen mattes).
|
||||
pub fn is_frozen(params: &Params) -> bool {
|
||||
!s(params, FROZEN).is_empty()
|
||||
@@ -292,11 +309,10 @@ pub fn frozen_alpha(params: &Params, layer_size: [f64; 2], fps: f64, f: i64, w:
|
||||
return None;
|
||||
}
|
||||
let fc = frozen_cache(j)?;
|
||||
if fc.key != frozen_key(params, layer_size, fps, model) {
|
||||
let ids = std::iter::once(effectcraft_segment::CLASSICAL).chain(effectcraft_segment::MODELS.iter().map(|m| m.id));
|
||||
if !ids.into_iter().any(|id| fc.key == frozen_key_of(params, layer_size, fps, id)) {
|
||||
return None;
|
||||
}
|
||||
if fc.key != frozen_key(params, layer_size, fps, model)
|
||||
&& !known_models().any(|id| fc.key == frozen_key_of(params, layer_size, fps, id, s(params, INPUT_KEY)))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let fr = fc.frames.get(&f)?;
|
||||
let [fw, fh] = fc.size;
|
||||
|
||||
@@ -953,6 +953,9 @@ fn needs_neighbours(mp: &MatteParams) -> bool {
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct FrozenCache {
|
||||
pub key: String,
|
||||
/// Object Matte's external media at Freeze time. Older caches omit this field.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub media_fingerprint: Option<String>,
|
||||
pub size: [usize; 2],
|
||||
pub frames: BTreeMap<i64, FrozenFrame>,
|
||||
}
|
||||
@@ -1429,8 +1432,12 @@ mod tests {
|
||||
let mut d = RotoData::default();
|
||||
d.add(Stroke { kind: StrokeKind::Fg, frame: 0, radius: 3.0, points: vec![[35.0, 40.0], [45.0, 40.0]], object: 0 }, 20, [0, 24]);
|
||||
let mut params = params_with(&d);
|
||||
let fc =
|
||||
FrozenCache { key: frozen_key(¶ms, [100.0, 80.0], 25.0), size: [10, 8], frames: BTreeMap::from([(5, freeze_frame(&[1.0; 80], &[0; 80]))]) };
|
||||
let fc = FrozenCache {
|
||||
key: frozen_key(¶ms, [100.0, 80.0], 25.0),
|
||||
size: [10, 8],
|
||||
frames: BTreeMap::from([(5, freeze_frame(&[1.0; 80], &[0; 80]))]),
|
||||
..Default::default()
|
||||
};
|
||||
let host = Seq;
|
||||
let render = |params: &Params| {
|
||||
let ctx = EffectCtx {
|
||||
|
||||
@@ -34,6 +34,7 @@ effectcraft-svg = { workspace = true }
|
||||
effectcraft-pdf = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
sha2 = "0.10"
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
//! to an instance's frames or prompt queues it for background tracking like a Roto Brush.
|
||||
|
||||
use crate::offload::JobKind;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
@@ -33,7 +33,10 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::analysis::frames_key::{self, Era};
|
||||
use crate::tracking::lock;
|
||||
use crate::{Event, Session};
|
||||
use crate::{Event, Services, Session, doc_path::StoredPaths};
|
||||
|
||||
mod freeze_inputs;
|
||||
use freeze_inputs::{EffectId, FreezeInputs, comps_with_unverified_image_reads};
|
||||
|
||||
/// Roto Brush / Refine Edge tool options (serde: `roto.options`).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -214,6 +217,127 @@ pub fn input_key(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> String {
|
||||
frames_key::input_key(p, comp, layer, uid)
|
||||
}
|
||||
|
||||
fn saved_input_matches(p: &Project, comp: ItemId, layer: &Layer, uid: Uid, saved: &str) -> bool {
|
||||
frames_key::key_matches(p, comp, layer, saved, |signature, era| match era {
|
||||
Era::Current => frames_key::input_key_of(signature, layer, uid),
|
||||
Era::Legacy => frames_key::legacy::input_key_of(signature, layer, uid),
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the imported freeze still matches the final effect stack after input sync.
|
||||
pub(crate) fn imported_freeze_matches(p: &Project, comp: ItemId, layer: LayerId, uid: Uid) -> bool {
|
||||
let Some(layer) = p.comp(comp).and_then(|c| c.layer(layer)) else { return false };
|
||||
layer.props.find_group(uid).is_some_and(|g| has_frozen_matte(g) && saved_input_matches(p, comp, layer, uid, &str_of(g, INPUT_KEY)))
|
||||
}
|
||||
|
||||
fn has_frozen_matte(g: &PropGroup) -> bool {
|
||||
matches!(g.get(FROZEN).map(|p| &p.value), Some(Value::Str(frozen)) if !frozen.is_empty())
|
||||
}
|
||||
|
||||
/// Object Matte freezes whose inputs are valid in the source project before IDs are shifted.
|
||||
pub(crate) fn imported_object_matte_freezes(p: &Project) -> HashSet<EffectId> {
|
||||
let mut freezes = HashSet::new();
|
||||
for (&cid, comp) in p.comps() {
|
||||
for l in &comp.layers {
|
||||
let Some(effects) = l.effects() else { continue };
|
||||
for g in effects.groups().filter(|g| is_object_matte(g) && has_frozen_matte(g)) {
|
||||
if saved_input_matches(p, cid, l, g.uid, &str_of(g, INPUT_KEY)) {
|
||||
freezes.insert((cid, l.id, g.uid));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
freezes
|
||||
}
|
||||
|
||||
/// Re-key the still-valid freezes after shifting IDs in the imported project.
|
||||
pub(crate) fn rekey_imported_object_mattes(
|
||||
p: &mut Project,
|
||||
offset: u64,
|
||||
freezes: HashSet<EffectId>,
|
||||
expr: Option<&dyn ExprHost>,
|
||||
services: &dyn Services,
|
||||
paths: &StoredPaths,
|
||||
) -> HashSet<EffectId> {
|
||||
let shifted: HashSet<_> = freezes
|
||||
.into_iter()
|
||||
.map(|(cid, lid, uid)| (ItemId(cid.0.saturating_add(offset)), LayerId(lid.0.saturating_add(offset)), uid.saturating_add(offset)))
|
||||
.collect();
|
||||
// Settle upstream effects first: clearing a Roto Brush freeze changes the frames a lower
|
||||
// Object Matte was frozen from. A remapped ID alone leaves those frames unchanged.
|
||||
let mut stacks = Vec::new();
|
||||
for (&cid, comp) in p.comps() {
|
||||
for layer in &comp.layers {
|
||||
let Some(effects) = layer.effects() else { continue };
|
||||
let groups = effects.groups().filter(|g| is_roto(g) || is_object_matte(g)).map(|g| g.uid).collect::<Vec<_>>();
|
||||
if !groups.is_empty() {
|
||||
stacks.push((cid, layer.id, groups));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut preserved = HashMap::new();
|
||||
let mut changed = HashSet::new();
|
||||
let mut files = HashMap::new();
|
||||
let unverified_image_reads = if shifted.is_empty() { HashSet::new() } else { comps_with_unverified_image_reads(p) };
|
||||
for (cid, lid, groups) in stacks {
|
||||
let mut input_changed = false;
|
||||
for uid in groups {
|
||||
let Some(c) = p.comp(cid) else { continue };
|
||||
let Some(l) = c.layer(lid) else { continue };
|
||||
let Some(g) = l.props.find_group(uid) else { continue };
|
||||
let saved = str_of(g, INPUT_KEY);
|
||||
let next = input_key(p, cid, l, uid);
|
||||
let id = (cid, lid, uid);
|
||||
let candidate = shifted.contains(&id);
|
||||
let inputs = (candidate && !input_changed).then(|| FreezeInputs::collect(p, id, &unverified_image_reads));
|
||||
let frozen = inputs.as_ref().and_then(|inputs| {
|
||||
let media = inputs.media_fingerprint(services, paths, &mut files)?;
|
||||
// Use the same reference time as Freeze, including animated parameters.
|
||||
let t = comp_time_of(c, l, om::reference_frame(¶ms_static(g)));
|
||||
let params = params_at(p, cid, l, g, t, expr);
|
||||
om::rekey_frozen_input(¶ms, layer_size(p, c, l), c.frame_rate.as_f64(), &next, &media)
|
||||
});
|
||||
let inputs = inputs.map(|inputs| inputs.effects);
|
||||
let matches = next == saved || saved_input_matches(p, cid, l, uid, &saved);
|
||||
let clear = frozen.is_none() && ((is_object_matte(g) && has_frozen_matte(g)) || (!matches && !saved.is_empty()));
|
||||
// The renderer skips disabled effects, including when another layer reads this one.
|
||||
if clear && l.switches.effects && g.enabled && (has_frozen_matte(g) || !str_of(g, TRACKED).is_empty()) {
|
||||
input_changed = true;
|
||||
changed.insert(id);
|
||||
}
|
||||
if let Some(g) = p.comp_mut(cid).and_then(|c| c.layer_mut(lid)).and_then(|l| l.props.find_group_mut(uid)) {
|
||||
if let Some((frozen, inputs)) = frozen.zip(inputs) {
|
||||
set_str(g, INPUT_KEY, next);
|
||||
set_str(g, FROZEN, frozen);
|
||||
preserved.insert(id, inputs);
|
||||
} else if clear || !matches {
|
||||
set_str(g, INPUT_KEY, next);
|
||||
if clear {
|
||||
set_str(g, FROZEN, String::new());
|
||||
set_str(g, TRACKED, String::new());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// A discarded freeze can change another effect's input through a precomp or a layer
|
||||
// parameter. Repeat until the invalidation has reached every dependent matte.
|
||||
while !changed.is_empty() {
|
||||
let stale: Vec<_> = preserved.iter().filter_map(|(&id, inputs)| (!inputs.is_disjoint(&changed)).then_some(id)).collect();
|
||||
changed.clear();
|
||||
for (cid, lid, uid) in stale {
|
||||
preserved.remove(&(cid, lid, uid));
|
||||
if let Some(g) = p.comp_mut(cid).and_then(|c| c.layer_mut(lid)).and_then(|l| l.props.find_group_mut(uid)) {
|
||||
set_str(g, FROZEN, String::new());
|
||||
set_str(g, TRACKED, String::new());
|
||||
changed.insert((cid, lid, uid));
|
||||
}
|
||||
}
|
||||
}
|
||||
preserved.into_keys().collect()
|
||||
}
|
||||
|
||||
/// After an edit: refresh Input Keys (Roto Brush and Object Matte); frozen mattes made from
|
||||
/// other frames are dropped. Returns the instances whose segmentation changed (to propagate
|
||||
/// again): new frames, strokes (Roto Brush) or prompt (Object Matte).
|
||||
@@ -229,11 +353,7 @@ pub(crate) fn sync(before: &Project, after: &mut Project) -> Vec<(ItemId, LayerI
|
||||
let old = before.comp(*cid).and_then(|bc| bc.layer(l.id)).and_then(|ol| ol.props.find_group(g.uid));
|
||||
let saved_key = str_of(g, INPUT_KEY);
|
||||
// Keep a matching old key: the frozen cache itself also hashes that key.
|
||||
let key_of = |s, era| match era {
|
||||
Era::Current => frames_key::input_key_of(s, l, g.uid),
|
||||
Era::Legacy => frames_key::legacy::input_key_of(s, l, g.uid),
|
||||
};
|
||||
if !frames_key::key_matches(after, *cid, l, &saved_key, key_of) {
|
||||
if !saved_input_matches(after, *cid, l, g.uid, &saved_key) {
|
||||
set.push((*cid, l.id, g.uid, key));
|
||||
todo.push((*cid, l.id, g.uid));
|
||||
} else if old.is_none_or(|o| guard_of(o) != guard_of(g)) {
|
||||
@@ -302,10 +422,14 @@ pub(crate) fn comp_time_of(comp: &effectcraft_project::Comp, layer: &Layer, f: i
|
||||
struct Work {
|
||||
project: Arc<Project>,
|
||||
footage: Arc<dyn FootageSource>,
|
||||
services: Arc<dyn Services>,
|
||||
stored_paths: StoredPaths,
|
||||
expr: Option<Arc<dyn ExprHost>>,
|
||||
cache: Arc<LayerCache>,
|
||||
disk_cache: Option<Arc<effectcraft_render::disk_cache::DiskCache>>,
|
||||
comp: ItemId,
|
||||
layer: LayerId,
|
||||
effect: Uid,
|
||||
effect_index: usize,
|
||||
params: Params,
|
||||
size: [f64; 2],
|
||||
@@ -412,7 +536,7 @@ impl<'a> FrameSource<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_work(w: Work, shared: &RotoShared) {
|
||||
async fn run_work(mut w: Work, shared: &RotoShared) {
|
||||
let t0 = web_time::Instant::now();
|
||||
// A browser job worker's GPU (deferred readbacks): input frames render in passes.
|
||||
let accel = crate::offload::job_accel();
|
||||
@@ -423,8 +547,6 @@ async fn run_work(w: Work, shared: &RotoShared) {
|
||||
};
|
||||
let Some(comp) = w.project.comp(w.comp) else { return fail("composition missing") };
|
||||
let Some(layer) = comp.layer(w.layer) else { return fail("layer missing") };
|
||||
let mut src =
|
||||
FrameSource::new(&w.project, w.footage.as_ref(), w.expr.as_deref(), &w.cache, w.comp, comp, layer, w.effect_index, w.size).with_accel(accel.as_deref());
|
||||
{
|
||||
let mut s = lock(&shared.state);
|
||||
s.task = Some(w.task);
|
||||
@@ -438,7 +560,37 @@ async fn run_work(w: Work, shared: &RotoShared) {
|
||||
}
|
||||
let model = fx::installed_model();
|
||||
let key = if w.object_matte { om::frozen_key(&w.params, w.size, w.fps, model.as_deref()) } else { fx::frozen_key(&w.params, w.size, w.fps) };
|
||||
let mut frozen = FrozenCache { key, ..Default::default() };
|
||||
let mut files = HashMap::new();
|
||||
let media_fingerprint = if w.object_matte && w.task == RotoTask::Freeze {
|
||||
let unverified = comps_with_unverified_image_reads(&w.project);
|
||||
let inputs = FreezeInputs::collect(&w.project, (w.comp, w.layer, w.effect), &unverified);
|
||||
inputs.media_fingerprint(w.services.as_ref(), &w.stored_paths, &mut files)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let verified_media = media_fingerprint.as_deref().filter(|fp| !fp.is_empty());
|
||||
if let Some(media) = verified_media
|
||||
&& let Some(Value::Str(input)) = w.params.values.get_mut(INPUT_KEY)
|
||||
{
|
||||
// Segmentation for this freeze must not reuse entries keyed only by saved metadata.
|
||||
// The stored matte key above still matches the instance's ordinary Input Key.
|
||||
input.push(':');
|
||||
input.push_str(media);
|
||||
}
|
||||
let fresh_frames = verified_media.map(|_| {
|
||||
// Metadata-only decoders and layer caches can also still hold the old pixels.
|
||||
for path in files.keys() {
|
||||
w.footage.forget(path);
|
||||
}
|
||||
if let Some(disk) = &w.disk_cache {
|
||||
disk.drop_files(files.keys().map(String::as_str));
|
||||
}
|
||||
LayerCache::default()
|
||||
});
|
||||
let cache = fresh_frames.as_ref().unwrap_or(&w.cache);
|
||||
let mut src =
|
||||
FrameSource::new(&w.project, w.footage.as_ref(), w.expr.as_deref(), cache, w.comp, comp, layer, w.effect_index, w.size).with_accel(accel.as_deref());
|
||||
let mut frozen = FrozenCache { key, media_fingerprint, ..Default::default() };
|
||||
// A tracking model (SAM 2) follows the object through the whole span in one pass; the loop
|
||||
// below then finds every frame cached. Without one (or if it fails) nothing changes: the
|
||||
// classic engine runs frame by frame.
|
||||
@@ -715,10 +867,14 @@ impl Session {
|
||||
let work = Work {
|
||||
project: self.project.clone(),
|
||||
footage: self.footage.clone(),
|
||||
services: self.services.clone(),
|
||||
stored_paths: self.stored_paths.clone(),
|
||||
expr: self.expr.clone(),
|
||||
cache: self.layer_cache.clone(),
|
||||
disk_cache: self.disk_cache.clone(),
|
||||
comp,
|
||||
layer,
|
||||
effect,
|
||||
effect_index: index,
|
||||
params,
|
||||
size,
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
|
||||
use effectcraft_effects::layer_source_id;
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::{Comp, Footage, ItemId, ItemKind, Layer, LayerId, Node, Project, PropGroup, Uid, essential};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::{Services, doc_path::StoredPaths};
|
||||
|
||||
pub(super) type EffectId = (ItemId, LayerId, Uid);
|
||||
|
||||
/// An expression can select pixel reads through a computed method name, parent transform,
|
||||
/// control layer or another composition. A composition with active expressions cannot provide
|
||||
/// a complete file provenance from the Layers and effect properties alone.
|
||||
pub(super) fn comps_with_unverified_image_reads(p: &Project) -> HashSet<ItemId> {
|
||||
let mut expression_comps = HashSet::new();
|
||||
for (&cid, comp) in p.comps() {
|
||||
for layer in &comp.layers {
|
||||
layer.props.walk("", &mut |_, prop| {
|
||||
if prop.has_expression() {
|
||||
expression_comps.insert(cid);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
expression_comps
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
enum Effects {
|
||||
Before(Uid),
|
||||
All,
|
||||
None,
|
||||
}
|
||||
|
||||
/// Dependencies of an Object Matte input across its span. The owning effect sees its own source
|
||||
/// and only the stack above it. A referenced layer may be read with or without its effects.
|
||||
pub(super) struct FreezeInputs<'a> {
|
||||
pub(super) effects: HashSet<EffectId>,
|
||||
// ID order is stable when import offsets IDs. Neither the IDs nor the paths enter the digest.
|
||||
footage: BTreeMap<ItemId, &'a Footage>,
|
||||
complete: bool,
|
||||
}
|
||||
|
||||
impl<'a> FreezeInputs<'a> {
|
||||
pub(super) fn collect(p: &'a Project, (comp, layer, effect): EffectId, unverified_image_reads: &HashSet<ItemId>) -> Self {
|
||||
let mut inputs = Self { effects: HashSet::new(), footage: BTreeMap::new(), complete: true };
|
||||
let mut pending = vec![(comp, layer, Effects::Before(effect))];
|
||||
let mut visited = HashSet::new();
|
||||
while let Some((cid, lid, scope)) = pending.pop() {
|
||||
if !visited.insert((cid, lid, scope)) {
|
||||
continue;
|
||||
}
|
||||
let Some(l) = p.comp(cid).and_then(|c| c.layer(lid)) else { continue };
|
||||
inputs.complete &= !unverified_image_reads.contains(&cid);
|
||||
if let Some(item_id) = l.source.item()
|
||||
&& let Some(item) = p.item(item_id)
|
||||
{
|
||||
if let Some(proxy) = item.proxy.as_ref().filter(|proxy| proxy.enabled && proxy.footage.has_video) {
|
||||
inputs.footage.insert(item_id, &proxy.footage);
|
||||
} else {
|
||||
match &item.kind {
|
||||
ItemKind::Footage(f) => {
|
||||
inputs.footage.insert(item_id, f);
|
||||
}
|
||||
ItemKind::Comp(nested) => {
|
||||
inputs.include_media_replacements(p, l, nested);
|
||||
let solo = nested.any_solo();
|
||||
for child in nested.layers.iter().filter(|l| l.has_video() && !l.environment && !l.switches.guide && (!solo || l.switches.solo)) {
|
||||
pending.push((item_id, child.id, Effects::All));
|
||||
if let Some(matte) = child.track_matte {
|
||||
pending.push((item_id, matte.layer, Effects::All));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
if scope != Effects::None
|
||||
&& l.switches.effects
|
||||
&& let Some(fx) = l.effects()
|
||||
{
|
||||
for group in fx.groups() {
|
||||
if scope == Effects::Before(group.uid) {
|
||||
break;
|
||||
}
|
||||
if group.enabled {
|
||||
inputs.effects.insert((cid, lid, group.uid));
|
||||
inputs.complete &= layer_reads(group, cid, lid, &mut pending);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
inputs
|
||||
}
|
||||
|
||||
/// Instance overrides can replace a nested layer's file. Include those files in addition
|
||||
/// to the originals, since the same comp may be read by different instances.
|
||||
fn include_media_replacements(&mut self, p: &'a Project, layer: &Layer, nested: &Comp) {
|
||||
let Some(controls) = nested.essential.as_ref() else { return };
|
||||
let Some(group) = essential::group(layer) else { return };
|
||||
let overridden = essential::overridden(layer);
|
||||
group.walk("", &mut |_, prop| {
|
||||
if !overridden.contains(&prop.uid) {
|
||||
return;
|
||||
}
|
||||
let Some(control) = essential::control_of(&prop.match_id).and_then(|id| controls.resolve(id)) else { return };
|
||||
match control.kind {
|
||||
essential::EgKind::Media { .. } => {
|
||||
if prop.has_expression() || !prop.keys.is_empty() {
|
||||
self.complete = false;
|
||||
} else {
|
||||
let id = ItemId(prop.value.as_f64().max(0.0) as u64);
|
||||
if let Some(item) = p.item(id)
|
||||
&& let ItemKind::Footage(footage) = &item.kind
|
||||
{
|
||||
let active = item.proxy.as_ref().filter(|proxy| proxy.enabled && proxy.footage.has_video).map_or(footage, |proxy| &proxy.footage);
|
||||
self.footage.insert(id, active);
|
||||
}
|
||||
}
|
||||
}
|
||||
essential::EgKind::Property { .. } if matches!(prop.value, Value::Layer(_)) => self.complete = false,
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Some empty fingerprint means no external files. None means at least one file could
|
||||
/// not be verified. The digest includes the files of an image sequence in playback order.
|
||||
pub(super) fn media_fingerprint(&self, services: &dyn Services, paths: &StoredPaths, files: &mut HashMap<String, Option<[u8; 32]>>) -> Option<String> {
|
||||
if !self.complete {
|
||||
return None;
|
||||
}
|
||||
let mut fingerprint = Sha256::new();
|
||||
let mut external = false;
|
||||
for f in self.footage.values() {
|
||||
let sources = if f.sequence.is_empty() { std::slice::from_ref(&f.path) } else { f.sequence.as_slice() };
|
||||
if sources.iter().all(String::is_empty) {
|
||||
continue;
|
||||
}
|
||||
if f.missing {
|
||||
return None;
|
||||
}
|
||||
external = true;
|
||||
fingerprint.update((sources.len() as u64).to_le_bytes());
|
||||
for path in sources {
|
||||
let resolved = paths.follow(path).ok()?;
|
||||
let resolved = resolved.to_str()?;
|
||||
let digest = files.entry(resolved.to_owned()).or_insert_with(|| services.file_fingerprint(resolved).ok());
|
||||
fingerprint.update((*digest)?);
|
||||
}
|
||||
}
|
||||
Some(if external { format!("{:x}", fingerprint.finalize()) } else { String::new() })
|
||||
}
|
||||
}
|
||||
|
||||
fn layer_reads(group: &PropGroup, comp: ItemId, owner: LayerId, out: &mut Vec<(ItemId, LayerId, Effects)>) -> bool {
|
||||
let mut complete = true;
|
||||
for node in &group.children {
|
||||
match node {
|
||||
Node::Prop(p) => {
|
||||
if !matches!(p.value, Value::Layer(_)) {
|
||||
continue;
|
||||
}
|
||||
complete &= !p.has_expression();
|
||||
let include_effects = group
|
||||
.get(&layer_source_id(&p.match_id))
|
||||
.is_none_or(|mode| mode.value.as_enum() >= 2 || mode.has_expression() || mode.keys.iter().any(|k| k.value.as_enum() >= 2));
|
||||
let scope = if include_effects { Effects::All } else { Effects::None };
|
||||
for id in std::iter::once(&p.value).chain(p.keys.iter().map(|key| &key.value)).filter_map(Value::as_layer).map(LayerId) {
|
||||
if id != owner {
|
||||
out.push((comp, id, scope));
|
||||
}
|
||||
}
|
||||
}
|
||||
Node::Group(child) if child.enabled => complete &= layer_reads(child, comp, owner, out),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
complete
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Session;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn media_replacement_changes_the_instance_fingerprint() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let original = dir.path().join("original.png");
|
||||
let replacement = dir.path().join("replacement.png");
|
||||
std::fs::write(&original, b"old file").unwrap();
|
||||
std::fs::write(&replacement, b"new file").unwrap();
|
||||
|
||||
let mut s = Session::default();
|
||||
s.execute("comp.new", json!({"name": "Inner", "width": 16, "height": 16})).unwrap();
|
||||
let inner = s.active_comp_id().unwrap();
|
||||
let (original_item, replacement_item) = s
|
||||
.edit("import media", None, |p, _| {
|
||||
let mut add = |path: &std::path::Path| {
|
||||
let footage = Footage { path: path.to_string_lossy().into_owned(), width: 16, height: 16, has_video: true, ..Default::default() };
|
||||
p.add_item(&footage.path.clone(), Default::default(), None, ItemKind::Footage(footage))
|
||||
};
|
||||
Ok((add(&original), add(&replacement)))
|
||||
})
|
||||
.unwrap();
|
||||
let child = s.execute("layer.addItem", json!({"item": original_item.0})).unwrap()["layer"].as_u64().unwrap();
|
||||
let control = s.execute("essential.addMedia", json!({"layer": child})).unwrap()["control"].as_u64().unwrap();
|
||||
s.execute("comp.new", json!({"name": "Outer", "width": 16, "height": 16})).unwrap();
|
||||
let outer = s.active_comp_id().unwrap();
|
||||
let instance = s.execute("layer.addItem", json!({"item": inner.0})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("essential.set", json!({"layer": instance, "control": control, "item": replacement_item.0})).unwrap();
|
||||
let matte = s.execute("objectMatte.apply", json!({"layer": instance, "point": [8, 8]})).unwrap()["effect"].as_u64().unwrap();
|
||||
let inputs = FreezeInputs::collect(&s.project, (outer, LayerId(instance), matte), &comps_with_unverified_image_reads(&s.project));
|
||||
let fingerprint = || inputs.media_fingerprint(s.services.as_ref(), &s.stored_paths, &mut HashMap::new()).unwrap();
|
||||
let before = fingerprint();
|
||||
std::fs::write(&replacement, b"bad file").unwrap();
|
||||
assert_ne!(before, fingerprint());
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,8 @@ fn import_project(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// (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);
|
||||
// Existing freezes can have been created with the stored path or its resolved form.
|
||||
let mut freezes = crate::roto::imported_object_matte_freezes(&sub);
|
||||
let missing = resolve_footage(s, &mut sub, &path);
|
||||
s.stored_paths.add(&sub, Some(&path));
|
||||
// The imported project's own render queue stays behind (as for templates).
|
||||
@@ -71,7 +73,9 @@ fn import_project(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if sub.next_id.checked_add(base).is_none() {
|
||||
return Err(bad(C, format!("{path} has ids out of range")));
|
||||
}
|
||||
freezes.extend(crate::roto::imported_object_matte_freezes(&sub));
|
||||
essential::offset_ids(&mut sub, base);
|
||||
let preserved = crate::roto::rekey_imported_object_mattes(&mut sub, base, freezes, s.expr.as_deref(), s.services.as_ref(), &s.stored_paths);
|
||||
let roots: Vec<ItemId> = root_comps(&sub);
|
||||
let folder_name = file.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "Imported Project".into());
|
||||
let (folder, items) = s.edit("Import Project", None, |proj, st| {
|
||||
@@ -89,6 +93,9 @@ fn import_project(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.project_selection = vec![folder];
|
||||
Ok((folder, items))
|
||||
})?;
|
||||
// The edit queues newly added effects. A still-valid imported freeze already has its mattes.
|
||||
s.roto_pending
|
||||
.retain(|&(comp, layer, uid)| !preserved.contains(&(comp, layer, uid)) || !crate::roto::imported_freeze_matches(&s.project, comp, layer, uid));
|
||||
let comps: Vec<Value> = s
|
||||
.project
|
||||
.comps()
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::config;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
/// The largest PhotoCraft bundle [`Services::read_pcraft`] reads.
|
||||
pub use effectcraft_project::PCRAFT_MAX_INPUT;
|
||||
@@ -11,6 +12,10 @@ pub fn pcraft_too_large() -> std::io::Error {
|
||||
/// Host services (file access) injected by the frontend.
|
||||
pub trait Services: Send + Sync {
|
||||
fn read_file(&self, path: &str) -> std::io::Result<Vec<u8>>;
|
||||
/// Content identity for media, independent of its stored path.
|
||||
fn file_fingerprint(&self, path: &str) -> std::io::Result<[u8; 32]> {
|
||||
Ok(Sha256::digest(self.read_file(path)?).into())
|
||||
}
|
||||
/// A PhotoCraft bundle's bytes: like [`Services::read_file`], but a file over
|
||||
/// [`PCRAFT_MAX_INPUT`] is an error. Other files read with `read_file` have no such limit.
|
||||
fn read_pcraft(&self, path: &str) -> std::io::Result<Vec<u8>> {
|
||||
@@ -81,6 +86,24 @@ pub trait Services: Send + Sync {
|
||||
pub struct FsServices;
|
||||
|
||||
impl Services for FsServices {
|
||||
fn file_fingerprint(&self, path: &str) -> std::io::Result<[u8; 32]> {
|
||||
use std::io::{Error, ErrorKind, Read};
|
||||
if !std::fs::metadata(path)?.is_file() {
|
||||
return Err(Error::new(ErrorKind::InvalidInput, "not a regular media file"));
|
||||
}
|
||||
let file = std::fs::File::open(path)?;
|
||||
let before = file.metadata()?;
|
||||
if !before.is_file() {
|
||||
return Err(Error::new(ErrorKind::InvalidInput, "not a regular media file"));
|
||||
}
|
||||
let mut digest = Sha256::new();
|
||||
let read = std::io::copy(&mut (&file).take(before.len().saturating_add(1)), &mut digest)?;
|
||||
if read != before.len() || file.metadata()?.modified()? != before.modified()? {
|
||||
return Err(Error::new(ErrorKind::InvalidData, "media changed while being read"));
|
||||
}
|
||||
Ok(digest.finalize().into())
|
||||
}
|
||||
|
||||
/// Refuses what isn't a regular file: a project can name `/dev/zero` or a FIFO, and reading
|
||||
/// those never ends (#2134).
|
||||
fn read_file(&self, path: &str) -> std::io::Result<Vec<u8>> {
|
||||
|
||||
@@ -65,6 +65,236 @@ fn source_project(dir: &std::path::Path) -> String {
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_project_preserves_a_frozen_object_matte_across_new_ids_and_reopen() {
|
||||
check_imported_object_matte("identical", false, false, false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_project_clears_the_object_matte_when_the_input_roto_freeze_is_discarded() {
|
||||
check_imported_object_matte("discarded-roto", true, false, false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_project_discards_a_footage_matte_when_media_identity_cannot_be_verified() {
|
||||
check_imported_object_matte("replaced", false, true, false);
|
||||
check_imported_object_matte("legacy", false, false, true);
|
||||
}
|
||||
|
||||
fn check_imported_object_matte(case: &str, with_roto_brush: bool, replaced_media: bool, legacy: bool) {
|
||||
use effectcraft_effects::{
|
||||
object_matte as om,
|
||||
roto::{self, FROZEN, FrozenCache, INPUT_KEY},
|
||||
};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::LayerId;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
let dir = out_dir(&format!("import-project-frozen-object-matte-{case}"));
|
||||
let width = 18;
|
||||
let height = 12;
|
||||
let mut s = Session::default();
|
||||
s.execute("comp.new", json!({"name": "Matte template", "width": width, "height": height, "frameRate": 25, "duration": 1})).unwrap();
|
||||
let comp = s.active_comp_id().unwrap();
|
||||
let footage = [1u8; 32];
|
||||
std::fs::write(dir.join("clip.mov"), footage).unwrap();
|
||||
let item = std::sync::Arc::make_mut(&mut s.project).add_item(
|
||||
"Source",
|
||||
Default::default(),
|
||||
None,
|
||||
ItemKind::Footage(Footage { path: "clip.mov".into(), kind: FootageKind::Video, width: width as u32, height: height as u32, ..Default::default() }),
|
||||
);
|
||||
let layer = LayerId(s.execute("layer.addItem", json!({"item": item.0, "time": 0.0})).unwrap()["layer"].as_u64().unwrap());
|
||||
if with_roto_brush {
|
||||
s.execute("roto.stroke", json!({"layer": layer.0, "points": [[7, 6]], "radius": 3})).unwrap();
|
||||
let c = s.project.comp(comp).unwrap();
|
||||
let l = c.layer(layer).unwrap();
|
||||
let brush = l.effects().unwrap().groups().find(|g| crate::roto::is_roto(g)).unwrap();
|
||||
let uid = brush.uid;
|
||||
let params = crate::roto::params_static(brush);
|
||||
let key = roto::frozen_key(¶ms, crate::roto::layer_size(&s.project, c, l), c.frame_rate.as_f64());
|
||||
let mut cache = FrozenCache { key, size: [width, height], ..Default::default() };
|
||||
cache.frames.insert(0, roto::freeze_frame(&vec![1.0; width * height], &[]));
|
||||
let brush = std::sync::Arc::make_mut(&mut s.project).comp_mut(comp).unwrap().layer_mut(layer).unwrap().props.find_group_mut(uid).unwrap();
|
||||
brush.get_mut(FROZEN).unwrap().value = Value::Str(cache.to_json());
|
||||
}
|
||||
let effect = s.execute("objectMatte.apply", json!({"layer": layer.0, "point": [7, 6]})).unwrap()["effect"].as_u64().unwrap();
|
||||
let c = s.project.comp(comp).unwrap();
|
||||
let l = c.layer(layer).unwrap();
|
||||
let g = l.props.find_group(effect).unwrap();
|
||||
let params = crate::roto::params_static(g);
|
||||
let old_input = params.get(INPUT_KEY).unwrap().clone();
|
||||
let old_source = l.source.item().unwrap();
|
||||
let layer_size = crate::roto::layer_size(&s.project, c, l);
|
||||
let fps = c.frame_rate.as_f64();
|
||||
let alpha: Vec<_> = (0..width * height).map(|i| if i % width < width / 2 { 1.0 } else { 0.0 }).collect();
|
||||
let mut frozen = FrozenCache { key: om::frozen_key(¶ms, layer_size, fps, None), size: [width, height], ..Default::default() };
|
||||
if !legacy {
|
||||
let mut media = Sha256::new();
|
||||
media.update(1u64.to_le_bytes()); // One file in this source.
|
||||
media.update(Sha256::digest(footage));
|
||||
frozen.media_fingerprint = Some(format!("{:x}", media.finalize()));
|
||||
}
|
||||
frozen.frames.insert(0, roto::freeze_frame(&alpha, &[]));
|
||||
let group = std::sync::Arc::make_mut(&mut s.project).comp_mut(comp).unwrap().layer_mut(layer).unwrap().props.find_group_mut(effect).unwrap();
|
||||
group.get_mut(FROZEN).unwrap().value = Value::Str(frozen.to_json());
|
||||
let source_params = crate::roto::params_static(group);
|
||||
assert_eq!(om::frozen_alpha(&source_params, layer_size, fps, 0, width, height, None), Some(alpha.clone()));
|
||||
let source = dir.join("Source.ecproj").to_string_lossy().into_owned();
|
||||
s.execute("file.saveAs", json!({"path": source})).unwrap();
|
||||
if replaced_media {
|
||||
// Same length, same path, same saved metadata, different bytes.
|
||||
std::fs::write(dir.join("clip.mov"), [2u8; 32]).unwrap();
|
||||
}
|
||||
|
||||
let mut destination = Session::default();
|
||||
destination.execute("comp.new", json!({"name": "Destination"})).unwrap();
|
||||
let imported = destination.execute("file.importProject", json!({"path": source})).unwrap();
|
||||
let comp = ItemId(imported["primaryComp"].as_u64().unwrap());
|
||||
assert_eq!(imported["missingMedia"], json!([]));
|
||||
if with_roto_brush || replaced_media || legacy {
|
||||
let l = &destination.project.comp(comp).unwrap().layers[0];
|
||||
let matte = l.effects().unwrap().groups().find(|g| g.match_id == om::ID).unwrap();
|
||||
assert_eq!(matte.get(FROZEN).unwrap().value, Value::Str(String::new()));
|
||||
assert_eq!(matte.get(INPUT_KEY).unwrap().value, Value::Str(crate::roto::input_key(&destination.project, comp, l, matte.uid)));
|
||||
assert!(destination.roto_pending.contains(&(comp, l.id, matte.uid)));
|
||||
return;
|
||||
}
|
||||
assert!(destination.roto_pending.is_empty(), "the imported freeze needs no propagation");
|
||||
let path = dir.join("Destination.ecproj").to_string_lossy().into_owned();
|
||||
destination.execute("file.saveAs", json!({"path": path})).unwrap();
|
||||
|
||||
let mut reopened = Session::default();
|
||||
reopened.execute("file.open", json!({"path": path})).unwrap();
|
||||
let c = reopened.project.comp(comp).unwrap();
|
||||
let l = &c.layers[0];
|
||||
assert_ne!(l.id, layer);
|
||||
assert_ne!(l.source.item(), Some(old_source));
|
||||
let effect = l.effects().unwrap().groups().find(|g| g.match_id == om::ID).unwrap();
|
||||
let params = crate::roto::params_static(effect);
|
||||
assert_ne!(params.get(INPUT_KEY), Some(&old_input));
|
||||
assert_eq!(om::frozen_alpha(¶ms, layer_size, fps, 0, width, height, None), Some(alpha));
|
||||
|
||||
let (layer, effect) = (l.id, effect.uid);
|
||||
assert!(crate::roto::imported_freeze_matches(&reopened.project, comp, layer, effect));
|
||||
// A payload can still be present when an earlier sync changes its input. It must stay queued.
|
||||
let mut changed = (*reopened.project).clone();
|
||||
changed.comp_mut(comp).unwrap().layer_mut(layer).unwrap().stretch = 200.0;
|
||||
assert!(!crate::roto::imported_freeze_matches(&changed, comp, layer, effect));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_discards_a_frozen_object_matte_if_its_nested_input_changes() {
|
||||
use effectcraft_effects::{
|
||||
object_matte as om,
|
||||
roto::{self, FROZEN, FrozenCache},
|
||||
};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::LayerId;
|
||||
|
||||
let (width, height) = (18, 12);
|
||||
let alpha: Vec<_> = (0..width * height).map(|i| if i % width < width / 2 { 1.0 } else { 0.0 }).collect();
|
||||
for (case, switches, through_effect, guide, changes_nested_input) in [
|
||||
("unchanged", None, false, false, false),
|
||||
("changed", Some((true, true)), false, false, true),
|
||||
("effects-off", Some((false, true)), false, false, false),
|
||||
("effect-disabled", Some((true, false)), false, false, false),
|
||||
("read-by-set-channels", Some((true, true)), true, false, true),
|
||||
("ignored-guide", Some((true, true)), true, true, false),
|
||||
("sample-image-guide", Some((true, true)), true, true, true),
|
||||
("sample-image-parent", Some((true, true)), true, true, true),
|
||||
] {
|
||||
let dir = out_dir(&format!("import-frozen-{case}-precomp"));
|
||||
let mut s = Session::default();
|
||||
let mut make_comp = |name: &str| {
|
||||
s.execute("comp.new", json!({"name": name, "width": width, "height": height, "frameRate": 25, "duration": 1})).unwrap();
|
||||
s.active_comp_id().unwrap()
|
||||
};
|
||||
// The frozen outer layer's comp comes before its sources in ID order.
|
||||
let outer = make_comp("Outer");
|
||||
let middle = make_comp("Middle");
|
||||
let inner = make_comp("Inner");
|
||||
let solid = LayerId(s.execute("layer.newSolid", json!({"name": "Solid", "color": "#ff0000"})).unwrap()["layer"].as_u64().unwrap());
|
||||
if let Some((effects_on, brush_enabled)) = switches {
|
||||
s.execute("roto.stroke", json!({"layer": solid.0, "points": [[7, 6]], "radius": 3})).unwrap();
|
||||
let comp = s.project.comp(inner).unwrap();
|
||||
let layer = comp.layer(solid).unwrap();
|
||||
let brush = layer.effects().unwrap().groups().find(|g| crate::roto::is_roto(g)).unwrap();
|
||||
let uid = brush.uid;
|
||||
let key = roto::frozen_key(&crate::roto::params_static(brush), [width as f64, height as f64], 25.0);
|
||||
let mut cache = FrozenCache { key, size: [width, height], ..Default::default() };
|
||||
cache.frames.insert(0, roto::freeze_frame(&alpha, &[]));
|
||||
let layer = std::sync::Arc::make_mut(&mut s.project).comp_mut(inner).unwrap().layer_mut(solid).unwrap();
|
||||
layer.switches.effects = effects_on;
|
||||
layer.switches.guide = guide;
|
||||
let brush = layer.props.find_group_mut(uid).unwrap();
|
||||
brush.enabled = brush_enabled;
|
||||
brush.get_mut(FROZEN).unwrap().value = Value::Str(cache.to_json());
|
||||
}
|
||||
if case.starts_with("sample-image-") {
|
||||
let reader = LayerId(s.execute("layer.newSolid", json!({"name": "Reads guide"})).unwrap()["layer"].as_u64().unwrap());
|
||||
let (reads, prop, text) = if case == "sample-image-parent" {
|
||||
let parent = s.execute("layer.newNull", json!({"name": "Parent"})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("layer.setParent", json!({"layers": [reader.0], "parent": parent})).unwrap();
|
||||
(LayerId(parent), "transform/position", "[thisComp.layer('Solid')['sample' + 'Image']([7, 6])[3] * 10, 0, 0]")
|
||||
} else {
|
||||
(reader, "transform/opacity", "thisComp.layer('Solid').sampleImage([7, 6])[3] * 100")
|
||||
};
|
||||
let reads = std::sync::Arc::make_mut(&mut s.project).comp_mut(inner).unwrap().layer_mut(reads).unwrap();
|
||||
reads.props.prop_mut(prop).unwrap().expr = Some(effectcraft_project::Expression { text: text.into(), enabled: true });
|
||||
}
|
||||
s.open_comp(middle);
|
||||
s.execute("layer.addItem", json!({"item": inner.0, "time": 0.0})).unwrap();
|
||||
s.open_comp(outer);
|
||||
let source_layer = LayerId(s.execute("layer.addItem", json!({"item": middle.0, "time": 0.0})).unwrap()["layer"].as_u64().unwrap());
|
||||
let layer = if through_effect {
|
||||
let target = LayerId(s.execute("layer.newSolid", json!({"name": "Receives new alpha"})).unwrap()["layer"].as_u64().unwrap());
|
||||
let set_channels = s.execute("effect.apply", json!({"layer": target.0, "effect": "Set Channels"})).unwrap()["effects"][0].as_u64().unwrap();
|
||||
let layer = std::sync::Arc::make_mut(&mut s.project).comp_mut(outer).unwrap().layer_mut(target).unwrap();
|
||||
let group = layer.props.find_group_mut(set_channels).unwrap();
|
||||
group.get_mut("sourceLayer4").unwrap().value = Value::Layer(Some(source_layer.0));
|
||||
group.get_mut("sourceLayer4Source").unwrap().value = Value::Enum(2);
|
||||
target
|
||||
} else {
|
||||
source_layer
|
||||
};
|
||||
let effect = s.execute("objectMatte.apply", json!({"layer": layer.0, "point": [7, 6]})).unwrap()["effect"].as_u64().unwrap();
|
||||
let g = s.project.comp(outer).unwrap().layer(layer).unwrap().props.find_group(effect).unwrap();
|
||||
let key = om::frozen_key(&crate::roto::params_static(g), [width as f64, height as f64], 25.0, None);
|
||||
let mut cache = FrozenCache { key, size: [width, height], ..Default::default() };
|
||||
cache.frames.insert(0, roto::freeze_frame(&alpha, &[]));
|
||||
let g = std::sync::Arc::make_mut(&mut s.project).comp_mut(outer).unwrap().layer_mut(layer).unwrap().props.find_group_mut(effect).unwrap();
|
||||
g.get_mut(FROZEN).unwrap().value = Value::Str(cache.to_json());
|
||||
let path = dir.join("Source.ecproj");
|
||||
s.execute("file.saveAs", json!({"path": path})).unwrap();
|
||||
|
||||
let mut destination = Session::default();
|
||||
destination.execute("comp.new", json!({"name": "Destination"})).unwrap();
|
||||
let imported = destination.execute("file.importProject", json!({"path": path})).unwrap();
|
||||
let comp = ItemId(imported["primaryComp"].as_u64().unwrap());
|
||||
let outer = destination.project.comp(comp).unwrap();
|
||||
let (layer, matte) = outer.layers.iter().find_map(|l| l.effects()?.groups().find(|g| g.match_id == om::ID).map(|g| (l, g))).unwrap();
|
||||
if switches.is_some() {
|
||||
let nested = outer
|
||||
.layers
|
||||
.iter()
|
||||
.find_map(|l| match l.source {
|
||||
LayerSource::Comp { item } => Some(item),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let middle = destination.project.comp(nested).unwrap();
|
||||
let inner = destination.project.comp(middle.layers[0].source.item().unwrap()).unwrap();
|
||||
let brush = inner.layers.iter().filter_map(|l| l.effects()).flat_map(|fx| fx.groups()).find(|g| crate::roto::is_roto(g)).unwrap();
|
||||
assert_eq!(brush.get(FROZEN).unwrap().value, Value::Str(String::new()), "{case}: the inner freeze is cleared on import");
|
||||
}
|
||||
let params = crate::roto::params_static(matte);
|
||||
let actual = om::frozen_alpha(¶ms, [width as f64, height as f64], 25.0, 0, width, height, None);
|
||||
assert_eq!(destination.roto_pending.contains(&(comp, layer.id, matte.uid)), changes_nested_input);
|
||||
assert_eq!(actual, (!changes_nested_input).then(|| alpha.clone()), "only a freeze whose precomp changed is discarded");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_project_merges_with_fresh_ids_and_one_undo() {
|
||||
let dir = out_dir("import-project");
|
||||
|
||||
@@ -603,6 +603,77 @@ fn object_matte_background_job_cancel_and_freeze() {
|
||||
assert_eq!(status(&mut s)["frozen"], true);
|
||||
}
|
||||
|
||||
/// A clip replacement with the same project metadata must not acquire the previous
|
||||
/// segmentation. The metadata-only cache is deliberately primed with an empty result.
|
||||
#[test]
|
||||
fn object_matte_freeze_uses_the_current_media_fingerprint() {
|
||||
use effectcraft_effects::roto::{self, FROZEN, FrameSeg, FrozenCache};
|
||||
use effectcraft_project::{Footage, ItemId, ItemKind};
|
||||
use effectcraft_render::FootageSource;
|
||||
use effectcraft_time::Tick;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed};
|
||||
|
||||
struct CachedDecoder {
|
||||
inner: Arc<dyn FootageSource>,
|
||||
reopened: AtomicBool,
|
||||
reads: AtomicUsize,
|
||||
}
|
||||
impl FootageSource for CachedDecoder {
|
||||
fn frame(&self, item: ItemId, footage: &Footage, time: Tick) -> Option<Arc<Image>> {
|
||||
if self.reopened.load(Relaxed) {
|
||||
self.reads.fetch_add(1, Relaxed);
|
||||
self.inner.frame(item, footage, time)
|
||||
} else {
|
||||
Some(Arc::new(Image::new(W, H)))
|
||||
}
|
||||
}
|
||||
fn forget(&self, _: &str) {
|
||||
self.reopened.store(true, Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
hold_roto_cache_test_lock();
|
||||
let media = tempfile::NamedTempFile::new().unwrap();
|
||||
std::fs::write(media.path(), b"replacement clip data").unwrap();
|
||||
let (mut s, clip, solid) = setup(|_| draw(center(0)));
|
||||
let decoder = Arc::new(CachedDecoder { inner: s.footage.clone(), reopened: AtomicBool::new(false), reads: AtomicUsize::new(0) });
|
||||
s.footage = decoder.clone();
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
s.edit("use replacement footage", None, |p, _| {
|
||||
p.comp_mut(cid).unwrap().layers.retain(|l| l.id != solid);
|
||||
let item = p.comp(cid).unwrap().layer(clip).unwrap().source.item().unwrap();
|
||||
if let ItemKind::Footage(f) = &mut p.item_mut(item).unwrap().kind {
|
||||
f.path = media.path().to_string_lossy().into_owned();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let point = center(0);
|
||||
let uid = s.execute_checked("objectMatte.apply", json!({"layer": clip.0, "point": point, "before": 0, "after": 0, "frame": 0})).unwrap()["effect"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let comp = s.project.comp(cid).unwrap();
|
||||
let layer = comp.layer(clip).unwrap();
|
||||
let mut warm = crate::roto::FrameSource::new(&s.project, decoder.as_ref(), None, &s.layer_cache, cid, comp, layer, 0, [W as f64, H as f64]);
|
||||
assert_eq!(warm.get(0).unwrap().get(90, 110)[3], 0.0);
|
||||
let key = s.roto_keys(cid, clip, uid).unwrap().into_iter().find(|(f, _)| *f == 0).unwrap().1;
|
||||
let size = W as usize * H as usize;
|
||||
let stale = FrameSeg { w: W as usize, h: H as usize, matte: vec![0; size], refine: vec![0; size], ..Default::default() };
|
||||
roto::store(key, 1.0, Arc::new(stale));
|
||||
let result = s.execute_checked("objectMatte.freeze", json!({"layer": clip.0, "effect": uid, "wait": true})).unwrap();
|
||||
assert_eq!(result["frozen"], true, "{result}");
|
||||
assert!(decoder.reads.load(Relaxed) > 0, "Freeze decoded fresh pixels");
|
||||
let g = s.project.comp(cid).unwrap().layer(clip).unwrap().props.find_group(uid).unwrap();
|
||||
let params = crate::roto::params_static(g);
|
||||
let effectcraft_keyframe::Value::Str(payload) = params.get(FROZEN).unwrap() else { panic!("expected a frozen matte") };
|
||||
let cache = FrozenCache::from_json(payload).unwrap();
|
||||
assert!(cache.media_fingerprint.is_some_and(|fingerprint| !fingerprint.is_empty()));
|
||||
let center = point[1] as usize * W as usize + point[0] as usize;
|
||||
assert!(alpha_at(&s, 0)[center] > 0.9, "the frozen matte was computed from the replacement");
|
||||
roto::forget([key]);
|
||||
}
|
||||
|
||||
/// A queue edit preserves a frozen matte made before the footage signature gained placed_page.
|
||||
#[test]
|
||||
fn render_queue_keeps_frozen_object_matte_with_legacy_footage_key() {
|
||||
|
||||
Reference in new issue
Block a user