Merge pull request #384 from storytold/feat/297-image-sequences

Import: image sequences with a Sequence option, ranges, folders and missing frames (#297)

# Conflicts:
#	docs/parity.md
This commit is contained in:
Brandon Thomas
2026-10-09 09:31:51 -04:00
27 changed files with 1304 additions and 238 deletions
+45 -65
View File
@@ -5,6 +5,7 @@ use effectcraft_project::{FootageKind, ItemId, ItemKind, LayerSource, Project};
use serde_json::{Value, json};
use super::{CommandSpec, always, b_p, bad, str_p};
use crate::sequence::{SequenceOptions, Source};
use crate::{EngineError, Result, Session, cmd};
fn has_path(s: &Session) -> std::result::Result<(), String> {
@@ -111,23 +112,22 @@ fn revert(s: &mut Session, _: &Value) -> Result<Value> {
fn import_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let target = s.active_comp_id();
let mut pending = prepare_import(s, p)?;
if b_p(p, "background").unwrap_or(false) && !pending.paths.is_empty() {
let paths = std::mem::take(&mut pending.paths);
let total = paths.len();
let label = match paths.first() {
Some(one) if total == 1 => format!("Importing {}", file_name(one)),
if b_p(p, "background").unwrap_or(false) && !pending.sources.is_empty() {
let sources = std::mem::take(&mut pending.sources);
let total = sources.len();
let label = match sources.first() {
Some(one) if total == 1 => format!("Importing {}", one.name()),
_ => format!("Importing {total} files"),
};
let p = p.clone();
return s.spawn_task("import", label, false, move |ctl| {
let mut probed = Vec::with_capacity(total);
for (k, path) in paths.into_iter().enumerate() {
ctl.message(format!("{} ({} of {total})", file_name(&path), k + 1));
for (k, src) in sources.iter().enumerate() {
ctl.message(format!("{} ({} of {total})", src.name(), k + 1));
if !ctl.progress(k as u64, total as u64) {
return Err(crate::render_queue::CANCELLED.into());
}
let r = pending.prober.probe(&path);
probed.push(r);
probed.push(pending.prober.probe(src));
}
ctl.progress(total as u64, total as u64);
let apply: crate::jobs::Apply = Box::new(move |s: &mut Session| {
@@ -147,17 +147,12 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result<Value> {
Ok(apply)
});
}
let probed = pending.paths.iter().map(|path| pending.prober.probe(path)).collect();
let probed = pending.sources.iter().map(|src| pending.prober.probe(src)).collect();
let mut r = add_footage(s, pending, probed)?;
finish_import(s, &mut r, target, p);
Ok(r)
}
/// The file name of a path, for labels.
fn file_name(path: &str) -> String {
std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string())
}
/// After an import (its result `r`): with `addToComp`, the new items become layers of `target`;
/// what couldn't be added joins the result's errors.
fn finish_import(s: &mut Session, r: &mut Value, target: Option<ItemId>, p: &Value) {
@@ -206,14 +201,14 @@ pub(crate) fn add_to_comp(s: &mut Session, r: &Value, target: Option<ItemId>, p:
/// File ▸ Import, all in one go (scripts and commands built on it); see [`import_cmd`].
pub(crate) fn import(s: &mut Session, p: &Value) -> Result<Value> {
let pending = prepare_import(s, p)?;
let probed = pending.paths.iter().map(|path| pending.prober.probe(path)).collect();
let probed = pending.sources.iter().map(|src| pending.prober.probe(src)).collect();
add_footage(s, pending, probed)
}
/// An import whose layered files are already compositions: the files left to probe as footage,
/// how, and what the import made so far.
/// An import whose layered files are already compositions: the files and image sequences left
/// to probe as footage, how, and what the import made so far.
struct PendingImport {
paths: Vec<String>,
sources: Vec<Source>,
prober: Prober,
comps: Vec<u64>,
items: Vec<u64>,
@@ -229,7 +224,8 @@ struct Prober {
/// Settings ▸ Import ▸ Interpret Unlabeled Alpha As, for stills and for movies.
still_alpha: Option<effectcraft_project::AlphaMode>,
movie_alpha: Option<effectcraft_project::AlphaMode>,
/// Settings ▸ Import ▸ Sequence Footage frames per second.
/// Image sequences' frames per second: the import's `frameRate`, or Settings ▸ Import ▸
/// Sequence Footage.
sequence_rate: effectcraft_time::FrameRate,
/// PDF / Illustrator page (0-based).
page: u32,
@@ -237,9 +233,10 @@ struct Prober {
psd_layer: Option<Value>,
}
/// A file probed as footage.
/// A file (or image sequence) probed as footage.
struct Probed {
path: String,
/// The Project panel name.
name: String,
footage: effectcraft_project::Footage,
/// Its alpha is unlabeled and Settings say Ask User: open Interpret Footage.
ask_alpha: bool,
@@ -247,22 +244,27 @@ struct Probed {
}
impl Prober {
/// Probe `path` as footage; the error names the file.
fn probe(&self, path: &str) -> std::result::Result<Probed, String> {
/// Probe a file or image sequence as footage; the error names the file.
fn probe(&self, src: &Source) -> std::result::Result<Probed, String> {
let path = src.path();
let name = src.name();
let fail = |e: String| format!("{path}: {e}");
// Data files (JSON, CSV, TSV) for data-driven animation: kept as text in the project.
if let Some(f) = data_footage(self.services.as_ref(), path) {
return f.map(|footage| Probed { path: path.to_string(), footage, ask_alpha: false, warning: None }).map_err(fail);
if let Source::File(_) = src
&& let Some(f) = data_footage(self.services.as_ref(), path)
{
return f.map(|footage| Probed { name, footage, ask_alpha: false, warning: None }).map_err(fail);
}
let importer = self.importer.as_ref().ok_or_else(|| fail("media import is not available in this build".into()))?;
let mut f = importer.probe(path).map_err(fail)?;
let mut f = crate::sequence::probe(importer.as_ref(), src, self.sequence_rate).map_err(fail)?;
let mut warning = None;
// Settings ▸ Import ▸ Report Missing Frames.
// Settings ▸ Import ▸ Report Missing Frames (numbered sequences).
if f.kind == FootageKind::Sequence
&& !f.alphabetical
&& self.report_missing_frames
&& let Some(gaps) = missing_frames(&f.sequence)
&& let Some(gaps) = crate::sequence::missing_report(&f.sequence)
{
warning = Some(format!("{path}: {gaps}"));
warning = Some(format!("{name}: {gaps} (shown as placeholders)"));
}
// Settings ▸ Import ▸ Interpret Unlabeled Alpha As: images only (a 3D model renders its
// own alpha, and audio and data have none).
@@ -277,13 +279,6 @@ impl Prober {
None => ask_alpha = true,
}
}
// Settings ▸ Import ▸ Sequence Footage frames per second.
if f.kind == FootageKind::Sequence {
let r = self.sequence_rate;
let frames = f.frame_rate.frame_at(f.duration);
f.frame_rate = r;
f.duration = r.tick_of(frames.max(1));
}
// Page: another page of a PDF / Illustrator file.
if self.page > 0 && matches!(f.codec.as_str(), "PDF" | "AI") {
let doc = self
@@ -308,7 +303,7 @@ impl Prober {
.ok_or_else(|| fail(format!("no layer {sel}")))?;
f.layer = Some(effectcraft_project::SourceLayer { index: index as u32, name, layer_size: false, embedded: None, placed: false });
}
Ok(Probed { path: path.to_string(), footage: f, ask_alpha, warning })
Ok(Probed { name, footage: f, ask_alpha, warning })
}
}
@@ -379,17 +374,25 @@ fn prepare_import(s: &mut Session, p: &Value) -> Result<PendingImport> {
}
paths = rest;
}
// Numbered stills as image sequences (the Import dialog's "<format> Sequence" and Force
// Alphabetical Order), at `frameRate` or Settings ▸ Import ▸ Sequence Footage.
let opts = SequenceOptions::from_params(p);
let fps = match p.get("frameRate") {
None | Some(Value::Null) => s.prefs.import.sequence_fps,
Some(v) => v.as_f64().filter(|x| *x > 0.0 && *x <= 999.0).ok_or_else(|| bad("file.import", "frameRate: frames per second, up to 999"))?,
};
let sources = crate::sequence::group(s.services.as_ref(), &paths, opts);
let prober = Prober {
importer: s.importer.clone(),
services: s.services.clone(),
report_missing_frames: s.prefs.import.report_missing_frames,
still_alpha: s.prefs.unlabeled_alpha(false),
movie_alpha: s.prefs.unlabeled_alpha(true),
sequence_rate: effectcraft_time::FrameRate::from_f64(s.prefs.import.sequence_fps),
sequence_rate: effectcraft_time::FrameRate::from_f64(fps),
page,
psd_layer: p.get("layer").cloned(),
};
Ok(PendingImport { paths, prober, comps, items, errors })
Ok(PendingImport { sources, prober, comps, items, errors })
}
/// The last part of an import: add the probed files to the project (one undo step) and select
@@ -413,7 +416,7 @@ fn add_footage(s: &mut Session, pending: PendingImport, probed: Vec<std::result:
s.edit("Import", None, |proj, st| {
let mut selection = made;
for f in found {
let name = file_name(&f.path);
let name = f.name;
let footage = f.footage;
let name = match &footage.layer {
Some(l) => format!("{}/{name}", l.name),
@@ -457,29 +460,6 @@ fn alpha_is_labeled(path: &str, codec: &str) -> bool {
matches!(ext.as_str(), "png" | "gif" | "webp" | "psd" | "psb" | "exr" | "svg" | "jpg" | "jpeg" | "ai" | "pdf" | "eps") || codec.eq_ignore_ascii_case("PSD")
}
/// Gaps in an image sequence's frame numbers ("missing frames 4–6, 9"), from the digit run at the
/// end of each file name. `None` when the numbering is continuous (or there is none).
pub(crate) fn missing_frames(files: &[String]) -> Option<String> {
let num = |f: &String| -> Option<i64> {
let stem = std::path::Path::new(f).file_stem()?.to_string_lossy().to_string();
let digits: String = stem.chars().rev().take_while(char::is_ascii_digit).collect::<Vec<_>>().into_iter().rev().collect();
digits.parse().ok()
};
let mut ns: Vec<i64> = files.iter().filter_map(num).collect();
ns.sort_unstable();
ns.dedup();
let mut gaps = vec![];
let mut total = 0;
for w in ns.windows(2) {
if w[1] - w[0] > 1 {
let (a, b) = (w[0] + 1, w[1] - 1);
total += b - a + 1;
gaps.push(if a == b { a.to_string() } else { format!("{a}–{b}") });
}
}
(!gaps.is_empty()).then(|| format!("{total} missing frame{} ({})", if total == 1 { "" } else { "s" }, gaps.join(", ")))
}
/// A Photoshop layer by index or name (pixel layers only).
fn find_psd_layer(d: &effectcraft_psd::Psd, sel: &Value) -> Option<(usize, String)> {
let l = match sel {
@@ -700,7 +680,7 @@ pub fn specs() -> Vec<CommandSpec> {
"File...",
["File", "Import"],
Some("Cmd+I"),
"{paths: [string], importAs?: footage|composition|compositionLayerSizes (Photoshop, PDF, Illustrator and EPS files), layer?: name|index (footage of one Photoshop layer), page?: number from 1 (PDF / Illustrator page), drag?: bool (dropped files: Settings ▸ Import ▸ Default Drag Import As), addToComp?: bool (also add them to the active comp, at time?, index?, position? as in layer.addItem), background?: bool (probe the files in a background job, jobs.list / jobs.wait; returns {job})}",
"{paths: [string] (files or folders), sequence?: bool (default true: numbered stills of one run import as one image sequence; one picked file brings its whole run, several picked files that range), alphabetical?: bool (Force Alphabetical Order: every image of that type in the folder, by name), frameRate?: fps (image sequences; default Settings ▸ Import ▸ Sequence Footage), importAs?: footage|composition|compositionLayerSizes (Photoshop, PDF, Illustrator and EPS files), layer?: name|index (footage of one Photoshop layer), page?: number from 1 (PDF / Illustrator page), drag?: bool (dropped files: Settings ▸ Import ▸ Default Drag Import As), addToComp?: bool (also add them to the active comp, at time?, index?, position? as in layer.addItem), background?: bool (probe the files in a background job, jobs.list / jobs.wait; returns {job})}",
always,
import_cmd
),
+55 -7
View File
@@ -10,6 +10,7 @@ use effectcraft_time::{FrameRate, Tick};
use serde_json::{Value, json};
use super::{CommandSpec, always, b_p, bad, f_p, has_comp, has_project_selection, str_p};
use crate::sequence::SequenceOptions;
use crate::{EngineError, Result, Session, cmd};
fn has_footage_selection(s: &Session) -> std::result::Result<(), String> {
@@ -552,6 +553,8 @@ pub(crate) struct Interpretation {
fields: Option<effectcraft_project::FieldOrder>,
profile: Option<Option<effectcraft_project::ColorSpace>>,
linear: Option<bool>,
/// Image sequences: Start Frame (`Some(None)` = the first file's number).
start: Option<Option<i64>>,
}
impl Interpretation {
@@ -598,12 +601,28 @@ impl Interpretation {
None => None,
};
it.linear = super::b_p(p, "linearLight");
// Start Frame: a frame number, or "file" for the first file's.
it.start = match p.get("startFrame") {
None | Some(Value::Null) => None,
Some(Value::String(f)) if f == "file" => Some(None),
Some(v) => Some(Some(
v.as_f64()
.filter(|x| x.is_finite() && x.abs() <= 1.0e9)
.map(|x| x.round() as i64)
.ok_or_else(|| bad(cmd, "startFrame: a frame number (up to 1e9), or \"file\""))?,
)),
};
Ok(it)
}
pub(crate) fn apply(&self, f: &mut Footage, guessed: Option<(AlphaMode, [f32; 3])>) {
let before = f.frame_rate;
self.apply_settings(f, guessed);
// A sequence's length is its frames (Start Frame decides how many).
if f.kind == FootageKind::Sequence && !f.sequence.is_empty() {
f.sync_sequence_duration();
return;
}
// Conforming keeps the frames and changes how long they last (12 frames at 30 fps are
// 0.4 s; conformed to 12 fps, 1 s). Stills have no frame rate of their own.
let (old, new) = (before.as_f64(), f.frame_rate.as_f64());
@@ -652,6 +671,13 @@ impl Interpretation {
if let Some(v) = self.linear {
f.linear_light = v;
}
if f.kind == FootageKind::Sequence
&& let Some(start) = self.start
{
// The first file's own number needn't be stored (it follows the files).
let first = f.sequence.first().and_then(|p| effectcraft_project::sequence::frame_number(p));
f.start_frame = start.filter(|n| Some(*n) != first);
}
}
}
@@ -728,7 +754,8 @@ fn interpret(s: &mut Session, p: &Value) -> Result<Value> {
Some(ItemKind::Footage(f)) => Some(json!({
"item": i.0, "alpha": format!("{:?}", f.alpha), "matteColor": f.premul_color, "invertAlpha": f.invert_alpha,
"fields": f.fields.label(), "pixelAspect": f.pixel_aspect, "loop": f.loop_count, "frameRate": f.frame_rate.as_f64(),
"linearLight": f.linear_light,
"linearLight": f.linear_light, "startFrame": f.first_frame_number(),
"frames": f.sequence_frames(),
})),
_ => None,
})
@@ -775,8 +802,11 @@ fn replace_footage(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_p(p, "path").ok_or_else(|| bad("file.replaceFootage", "missing `path`"))?.to_string();
let item = *items_p(s, p).first().ok_or_else(|| bad("file.replaceFootage", "select footage"))?;
let importer = s.importer.clone().ok_or_else(|| EngineError::Other("media import is not available in this build".into()))?;
let f = importer.probe(&path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
let name = std::path::Path::new(&path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or(path.clone());
// A numbered still brings its image sequence, as on import (`sequence: false` for one frame).
let opts = SequenceOptions::from_params(p);
let src = crate::sequence::source_of(s.services.as_ref(), &path, opts);
let f = crate::sequence::probe(importer.as_ref(), &src, s.sequence_rate()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
let name = src.name();
s.edit("Replace Footage", None, |proj, _| {
let it = proj.item_mut(item).ok_or_else(|| bad("file.replaceFootage", "no such item"))?;
it.name = name;
@@ -843,11 +873,14 @@ fn replace_with_solid(s: &mut Session, p: &Value) -> Result<Value> {
fn reload(s: &mut Session, p: &Value) -> Result<Value> {
let items = items_p(s, p);
let Some(importer) = s.importer.clone() else { return Err(EngineError::Other("media import is not available in this build".into())) };
if s.importer.is_none() {
return Err(EngineError::Other("media import is not available in this build".into()));
}
let mut updates = vec![];
for i in &items {
if let Some(ItemKind::Footage(f)) = s.project.item(*i).map(|x| &x.kind) {
let mut nf = match importer.probe(&f.path) {
// An image sequence picks up frames added to (or removed from) its run.
let mut nf = match s.probe_footage(&f.path) {
Ok(n) => n,
Err(_) => Footage { missing: true, ..f.clone() },
};
@@ -855,6 +888,13 @@ fn reload(s: &mut Session, p: &Value) -> Result<Value> {
nf.alpha = f.alpha;
nf.loop_count = f.loop_count;
nf.pixel_aspect = f.pixel_aspect;
if nf.kind == FootageKind::Sequence && f.kind == FootageKind::Sequence {
nf.frame_rate = f.frame_rate;
nf.native_rate = f.native_rate;
nf.alphabetical = f.alphabetical;
nf.start_frame = f.start_frame;
nf.sync_sequence_duration();
}
updates.push((*i, nf));
}
}
@@ -954,7 +994,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Main...",
["File", "Interpret Footage"],
Some("Cmd+Alt+G"),
"{items?, frameRate?: fps|\"file\", alpha?: straight|premultiplied|ignore|guess, guessAlpha?, matteColor?, invertAlpha?, loop?, pixelAspect?, fields?: off|upper|lower, colorProfile?: srgb|rec709|rec2020|p3|auto, linearLight?}",
"{items?, frameRate?: fps|\"file\", alpha?: straight|premultiplied|ignore|guess, guessAlpha?, matteColor?, invertAlpha?, loop?, pixelAspect?, fields?: off|upper|lower, colorProfile?: srgb|rec709|rec2020|p3|auto, linearLight?, startFrame?: number|\"file\" (image sequences: the frame number at the footage's first frame)}",
has_footage_selection,
interpret
),
@@ -976,7 +1016,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_interpretation,
apply_interpretation
),
cmd!("file.replaceFootage", "File...", ["File", "Replace Footage"], Some("Cmd+H"), "{path, item?}", has_footage_selection, replace_footage),
cmd!(
"file.replaceFootage",
"File...",
["File", "Replace Footage"],
Some("Cmd+H"),
"{path, item?, sequence?: bool (default true: a numbered still brings its image sequence), alphabetical?: bool}",
has_footage_selection,
replace_footage
),
cmd!(
"file.replaceWithPlaceholder",
"Placeholder...",
-2
View File
@@ -74,8 +74,6 @@ pub(crate) mod watch_folder;
pub(crate) use app_more::report_text as report_text_for_tests;
pub(crate) use app_more::view_command;
#[cfg(test)]
pub(crate) use file::missing_frames as missing_frames_for_tests;
#[cfg(test)]
pub(crate) use keys_more::amplitudes as amplitudes_for_tests;
#[cfg(test)]
pub(crate) use mask::split_segment as split_segment_for_tests;
+2 -3
View File
@@ -120,9 +120,8 @@ fn file_info(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_p(p, "path").ok_or_else(|| bad("mediaBrowser.fileInfo", "missing `path`"))?;
let (created, modified, size) = mb::file_dates(path);
let mut v = json!({"path": path, "kind": mb::kind_of(path), "size": size, "created": created.map(mb::iso_date), "modified": modified.map(mb::iso_date)});
if let Some(imp) = s.importer.clone()
&& matches!(mb::kind_of(path), Some("video" | "image" | "audio" | "model"))
&& let Ok(f) = imp.probe(path)
if matches!(mb::kind_of(path), Some("video" | "image" | "audio" | "model"))
&& let Ok(f) = s.probe_footage(path)
{
v["footage"] = mb::footage_metadata(&f);
}
+5 -2
View File
@@ -40,8 +40,11 @@ fn has_proxy(s: &Session) -> std::result::Result<(), String> {
/// Probe a proxy file through the importer.
fn probe(s: &Session, path: &str, cmd: &str) -> Result<Footage> {
let importer = s.importer.clone().ok_or_else(|| EngineError::Other("media import is not available in this build".into()))?;
let f = importer.probe(path).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
if s.importer.is_none() {
return Err(EngineError::Other("media import is not available in this build".into()));
}
// The first frame of a proxy sequence (Create Proxy ▸ Movie renders one) brings the rest.
let f = s.probe_footage(path).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
if !f.has_video {
return Err(bad(cmd, format!("{path} has no video to use as a proxy")));
}
+2 -1
View File
@@ -40,11 +40,12 @@ fn import_timeline(s: &mut Session, p: &Value) -> Result<Value> {
};
let importer = s.importer.clone();
let services = s.services.clone();
let rate = s.sequence_rate();
let mut probe = move |m: &str| -> Option<effectcraft_project::Footage> {
if !services.exists(m) {
return None;
}
importer.as_ref()?.probe(m).ok()
crate::sequence::probe_path(importer.as_deref()?, services.as_ref(), m, rate).ok()
};
let res = s.edit("Import Timeline", None, |proj, st| {
let r = effectcraft_interchange::import(proj, &bytes, format, &opts, &mut probe).map_err(|e| EngineError::Other(e.to_string()))?;
+18 -1
View File
@@ -51,6 +51,7 @@ pub fn start(s: &mut Session, items: Option<Vec<ItemId>>, wait: bool) -> crate::
}
let services = s.services.clone();
let importer = s.importer.clone();
let rate = s.sequence_rate();
let n = jobs.len();
s.spawn_task("footageCheck", format!("Checking footage ({n} items)"), wait, move |ctl| {
let mut found: Vec<(ItemId, Found)> = Vec::with_capacity(jobs.len());
@@ -69,7 +70,23 @@ pub fn start(s: &mut Session, items: Option<Vec<ItemId>>, wait: bool) -> crate::
};
// Saved without metadata (a hand-written or converted project): probe it now.
let needs_probe = present && f.width == 0 && f.height == 0 && f.kind != FootageKind::Audio;
match importer.as_ref().filter(|_| needs_probe).map(|imp| imp.probe(&f.path)) {
let probed = importer.as_ref().filter(|_| needs_probe).map(|imp| match f.kind {
// A sequence keeps its files; its first one gives the metadata.
FootageKind::Sequence if !f.sequence.is_empty() => imp.probe(&f.path).map(|one| {
let mut nf = Footage {
width: one.width,
height: one.height,
pixel_aspect: one.pixel_aspect,
has_video: one.has_video,
codec: one.codec,
..f.clone()
};
nf.sync_sequence_duration();
nf
}),
_ => crate::sequence::probe_path(imp.as_ref(), services.as_ref(), &f.path, rate),
});
match probed {
Some(Ok(mut nf)) => {
nf.alpha = f.alpha;
nf.loop_count = f.loop_count;
+21 -1
View File
@@ -37,6 +37,7 @@ pub mod remote;
pub mod render_queue;
pub mod roto;
pub mod scriptui;
pub mod sequence;
mod session_settings;
pub mod shortcuts;
pub mod storage;
@@ -110,6 +111,19 @@ pub trait Services: Send + Sync {
}
self.write_file(path, data)
}
/// The files in folder `dir` (full paths; no folders, no hidden files), for image-sequence
/// detection on import. Empty when it can't be read.
fn list_dir(&self, dir: &str) -> Vec<String> {
let Ok(rd) = std::fs::read_dir(if dir.is_empty() { "." } else { dir }) else { return vec![] };
rd.filter_map(|e| e.ok())
.filter(|e| e.file_type().is_ok_and(|t| t.is_file()) && !e.file_name().to_string_lossy().starts_with('.'))
.map(|e| e.path().to_string_lossy().to_string())
.collect()
}
/// Whether `path` is a folder (dropped or picked folders import their files).
fn is_dir(&self, path: &str) -> bool {
std::path::Path::new(path).is_dir()
}
}
/// Native filesystem.
@@ -125,11 +139,15 @@ impl Services for FsServices {
/// Imports media files into the project (implemented by the media layer).
pub trait Importer: Send + Sync {
/// Probe a file and return footage metadata.
/// Probe one file and return footage metadata. Image sequences are the engine's
/// ([`sequence`]): it groups numbered stills and probes their first file here.
fn probe(&self, path: &str) -> std::result::Result<effectcraft_project::Footage, String>;
/// A footage file's bytes are now at `path` (extracted from a template): hosts whose media
/// layer reads from memory (the browser) register them; file-based ones need nothing.
fn register(&self, _path: &str, _data: &[u8]) {}
/// An image sequence's other frames (its first was probed) are footage now: hosts whose
/// media layer reads from memory (the browser) register them; file-based ones need nothing.
fn add_frames(&self, _paths: &[String]) {}
}
/// A keyframe reference: layer, property uid, key time (layer time).
@@ -1013,6 +1031,8 @@ mod tests_proxy;
#[cfg(test)]
mod tests_rig3d;
#[cfg(test)]
mod tests_sequence;
#[cfg(test)]
mod tests_settings;
#[cfg(test)]
mod tests_stubs;
+2 -2
View File
@@ -624,8 +624,8 @@ impl Session {
if item.post_render.is_none() {
return Ok(None);
}
let importer = self.importer.clone().ok_or("media import is not available in this build")?;
let footage = importer.probe(path)?;
// A rendered image sequence's first file brings the sequence.
let footage = self.probe_footage(path)?;
if item.post_render == PostRenderAction::SetProxy {
crate::commands::proxy_set(self, item.comp, footage).map_err(|e| e.to_string())?;
self.toast(format!("Proxy set from {path}"));
+310
View File
@@ -0,0 +1,310 @@
//! Image sequences on import (File ▸ Import ▸ File…, dropped files and folders, Replace
//! Footage, Reload, proxies): numbered stills of one run (`shot_0001.png`, `shot_0002.png`, …)
//! become one footage item, as with After Effects' "PNG Sequence" import option.
//!
//! - One picked numbered file brings its whole run from its folder ([`crate::Services::list_dir`]).
//! - Several picked files of one run import as one sequence of just those files (a range).
//! - A picked or dropped folder imports its files; each run in it becomes a sequence.
//! - Force Alphabetical Order: every image of the same type in the folder, in name order,
//! whatever the numbering (gaps don't count).
//!
//! The browser has no folders: its file table lists the files picked or dropped so far, so
//! picking every frame of a sequence imports it there too.
use effectcraft_project::sequence::{frame_number, missing_frame_ranges, sequence_name, split_frame_number};
use effectcraft_project::{Footage, FootageKind};
use effectcraft_time::FrameRate;
use crate::{Importer, Services};
/// How an import treats numbered stills.
#[derive(Clone, Copy, Debug)]
pub struct SequenceOptions {
/// The "<format> Sequence" checkbox: numbered stills of one run import as a sequence.
pub sequence: bool,
/// Force Alphabetical Order.
pub alphabetical: bool,
}
impl Default for SequenceOptions {
fn default() -> Self {
SequenceOptions { sequence: true, alphabetical: false }
}
}
impl SequenceOptions {
/// From command parameters `sequence?` (default on) and `alphabetical?`.
pub fn from_params(p: &serde_json::Value) -> SequenceOptions {
let flag = |k: &str| p.get(k).and_then(serde_json::Value::as_bool);
SequenceOptions { sequence: flag("sequence").unwrap_or(true), alphabetical: flag("alphabetical").unwrap_or(false) }
}
}
/// What one import unit makes: a file's footage, or an image sequence of files (in order).
#[derive(Clone, Debug, PartialEq)]
pub enum Source {
File(String),
Sequence { files: Vec<String>, alphabetical: bool },
}
impl Source {
/// The path naming it (a sequence's first file).
pub fn path(&self) -> &str {
match self {
Source::File(p) => p,
Source::Sequence { files, .. } => files.first().map_or("", String::as_str),
}
}
/// The Project panel name: the file name, or a sequence's `shot_[0001-0250].png`.
pub fn name(&self) -> String {
match self {
Source::Sequence { files, alphabetical: false } => sequence_name(files).unwrap_or_else(|| file_name(self.path())),
_ => file_name(self.path()),
}
}
}
/// The file name of a path (either separator).
pub fn file_name(path: &str) -> String {
path.rsplit(['/', '\\']).find(|n| !n.is_empty()).unwrap_or(path).to_string()
}
/// The folder of a path (`""` for a bare name).
fn folder(path: &str) -> &str {
path.rfind(['/', '\\']).map_or("", |i| path.get(..i.max(1)).unwrap_or(""))
}
fn extension(path: &str) -> String {
let name = file_name(path);
name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default()
}
/// Stills that can form a sequence (not layered or vector documents, which import as comps).
fn sequenceable(path: &str) -> bool {
crate::media_browser::kind_of(path) == Some("image") && !matches!(extension(path).as_str(), "svg" | "psd" | "psb")
}
/// The run a still belongs to: (folder, name prefix, extension); alphabetical runs ignore the
/// name. `None` for files that can't be part of one.
fn run_key(path: &str, alphabetical: bool) -> Option<(String, String, String)> {
if !sequenceable(path) {
return None;
}
let ext = extension(path);
if alphabetical {
return Some((folder(path).to_string(), String::new(), ext));
}
let name = file_name(path);
let stem = name.get(..name.len().saturating_sub(ext.len() + usize::from(!ext.is_empty()))).unwrap_or("");
let (prefix, _) = split_frame_number(stem)?;
Some((folder(path).to_string(), prefix.to_string(), ext))
}
/// Put a run's files in order: by frame number, or by name (Force Alphabetical Order).
fn sort_run(files: &mut Vec<String>, alphabetical: bool) {
if alphabetical {
files.sort_by_key(|p| file_name(p).to_lowercase());
} else {
files.sort_by_key(|p| (frame_number(p), p.clone()));
}
files.dedup();
}
/// The files of the run `path` belongs to, from its folder.
fn run_files(services: &dyn Services, path: &str, alphabetical: bool) -> Vec<String> {
let Some(key) = run_key(path, alphabetical) else { return vec![] };
let mut files: Vec<String> = services.list_dir(&key.0).into_iter().filter(|p| run_key(p, alphabetical).as_ref() == Some(&key)).collect();
sort_run(&mut files, alphabetical);
files
}
/// What importing `paths` makes, in the order picked: folders become their importable files,
/// and (with the Sequence option) numbered stills of one run one [`Source::Sequence`].
pub fn group(services: &dyn Services, paths: &[String], opts: SequenceOptions) -> Vec<Source> {
let mut files: Vec<String> = vec![];
for p in paths {
if services.is_dir(p) {
let mut inside: Vec<String> =
services.list_dir(p).into_iter().filter(|f| matches!(crate::media_browser::kind_of(f), Some(k) if k != "project")).collect();
inside.sort_by_key(|f| file_name(f).to_lowercase());
files.extend(inside);
} else {
files.push(p.clone());
}
}
if !opts.sequence {
return files.into_iter().map(Source::File).collect();
}
// Runs in the order their first file was picked.
let mut runs: Vec<((String, String, String), Vec<String>)> = vec![];
let mut out: Vec<Option<Source>> = vec![];
let mut slot: Vec<usize> = vec![];
for f in files {
match run_key(&f, opts.alphabetical) {
Some(key) => match runs.iter_mut().find(|(k, _)| *k == key) {
Some((_, run)) => run.push(f),
None => {
runs.push((key, vec![f]));
slot.push(out.len());
out.push(None);
}
},
None => out.push(Some(Source::File(f))),
}
}
for ((_, mut picked), at) in runs.into_iter().zip(slot) {
sort_run(&mut picked, opts.alphabetical);
// One file: its whole run from the folder.
if let [one] = picked.as_slice() {
let all = run_files(services, one, opts.alphabetical);
if all.len() >= 2 {
picked = all;
}
}
let src = match picked.len() {
0 => None,
1 => picked.pop().map(Source::File),
_ => Some(Source::Sequence { files: picked, alphabetical: opts.alphabetical }),
};
if let Some(o) = out.get_mut(at) {
*o = src;
}
}
out.into_iter().flatten().collect()
}
/// The image sequences importing `paths` would make (the Import dialog asks about them).
pub fn sequences(services: &dyn Services, paths: &[String], alphabetical: bool) -> Vec<Vec<String>> {
group(services, paths, SequenceOptions { sequence: true, alphabetical })
.into_iter()
.filter_map(|s| match s {
Source::Sequence { files, .. } => Some(files),
Source::File(_) => None,
})
.collect()
}
/// Probe what a [`Source`] makes. A sequence is its first file's footage with every file, at
/// `rate`, showing gaps in its numbering as placeholders, as in After Effects (in Force
/// Alphabetical Order the files play one after another).
pub fn probe(importer: &dyn Importer, src: &Source, rate: FrameRate) -> Result<Footage, String> {
let Source::Sequence { files, alphabetical } = src else { return importer.probe(src.path()) };
let mut f = importer.probe(src.path())?;
if f.kind != FootageKind::Still {
return Ok(f);
}
f.kind = FootageKind::Sequence;
f.sequence = files.clone();
f.alphabetical = *alphabetical;
f.start_frame = None;
f.frame_rate = rate;
f.native_rate = None;
f.sync_sequence_duration();
importer.add_frames(files.get(1..).unwrap_or_default());
Ok(f)
}
/// Probe one path the way it imports by default: a numbered still with numbered siblings
/// brings its run as a sequence (Replace Footage, Reload, proxies, render outputs).
pub fn probe_path(importer: &dyn Importer, services: &dyn Services, path: &str, rate: FrameRate) -> Result<Footage, String> {
probe(importer, &source_of(services, path, SequenceOptions::default()), rate)
}
/// What importing the one file `path` makes.
pub fn source_of(services: &dyn Services, path: &str, opts: SequenceOptions) -> Source {
group(services, &[path.to_string()], opts).into_iter().next().unwrap_or_else(|| Source::File(path.to_string()))
}
impl crate::Session {
/// Image sequences' frame rate on import: Settings ▸ Import ▸ Sequence Footage.
pub fn sequence_rate(&self) -> FrameRate {
FrameRate::from_f64(self.prefs.import.sequence_fps)
}
/// Probe `path` as footage the way it imports by default ([`probe_path`]).
pub(crate) fn probe_footage(&self, path: &str) -> Result<Footage, String> {
let importer = self.importer.as_ref().ok_or("media import is not available in this build")?;
probe_path(importer.as_ref(), self.services.as_ref(), path, self.sequence_rate())
}
}
/// Settings ▸ Import ▸ Report Missing Frames: "3 missing frames (3–4, 6)". `None` when the
/// numbering is continuous.
pub fn missing_report(files: &[String]) -> Option<String> {
let gaps = missing_frame_ranges(files);
let total: i64 = gaps.iter().map(|(a, b)| b.saturating_sub(*a).saturating_add(1)).fold(0, i64::saturating_add);
let list: Vec<String> = gaps.iter().map(|(a, b)| if a == b { a.to_string() } else { format!("{a}–{b}") }).collect();
(!gaps.is_empty()).then(|| format!("{total} missing frame{} ({})", if total == 1 { "" } else { "s" }, list.join(", ")))
}
#[cfg(test)]
mod tests {
use super::*;
/// A file table: listed folders and their files.
struct Table(Vec<&'static str>);
impl Services for Table {
fn read_file(&self, path: &str) -> std::io::Result<Vec<u8>> {
Err(std::io::Error::other(path.to_string()))
}
fn write_file(&self, _: &str, _: &[u8]) -> std::io::Result<()> {
Ok(())
}
fn list_dir(&self, dir: &str) -> Vec<String> {
self.0.iter().filter(|p| folder(p) == dir).map(|p| p.to_string()).collect()
}
fn is_dir(&self, path: &str) -> bool {
self.0.iter().any(|p| folder(p) == path)
}
}
fn strs(v: &[&str]) -> Vec<String> {
v.iter().map(|s| s.to_string()).collect()
}
#[test]
fn groups_runs_ranges_folders_and_alphabetical() {
let t = Table(vec!["/s/a_0002.png", "/s/a_0001.png", "/s/a_0010.png", "/s/b_1.png", "/s/notes.txt", "/s/c.png", "/s/a_0003.jpg", "/x/one_1.png"]);
let on = SequenceOptions::default();
// One picked file: its run from the folder, in frame order.
assert_eq!(
group(&t, &strs(&["/s/a_0010.png"]), on),
[Source::Sequence { files: strs(&["/s/a_0001.png", "/s/a_0002.png", "/s/a_0010.png"]), alphabetical: false }]
);
// A picked range stays that range; other files import as they are.
assert_eq!(
group(&t, &strs(&["/s/c.png", "/s/a_0010.png", "/s/a_0002.png", "/s/b_1.png", "/x/one_1.png"]), on),
[
Source::File("/s/c.png".into()),
Source::Sequence { files: strs(&["/s/a_0002.png", "/s/a_0010.png"]), alphabetical: false },
Source::File("/s/b_1.png".into()),
Source::File("/x/one_1.png".into()),
]
);
// Sequence off: every file on its own.
assert_eq!(group(&t, &strs(&["/s/a_0001.png"]), SequenceOptions { sequence: false, alphabetical: false }), [Source::File("/s/a_0001.png".into())]);
// A folder: its media files, runs as sequences.
let g = group(&t, &strs(&["/s"]), on);
assert_eq!(g.len(), 4, "{g:?}");
assert_eq!(g[0], Source::Sequence { files: strs(&["/s/a_0001.png", "/s/a_0002.png", "/s/a_0010.png"]), alphabetical: false });
assert_eq!(g[0].name(), "a_[0001-0010].png");
assert!(!g.iter().any(|s| s.path().ends_with(".txt")));
// Force Alphabetical Order: every PNG in the folder, by name.
let a = group(&t, &strs(&["/s/c.png"]), SequenceOptions { sequence: true, alphabetical: true });
assert_eq!(a, [Source::Sequence { files: strs(&["/s/a_0001.png", "/s/a_0002.png", "/s/a_0010.png", "/s/b_1.png", "/s/c.png"]), alphabetical: true }]);
assert_eq!(a[0].name(), "a_0001.png");
assert_eq!(sequences(&t, &strs(&["/s/a_0001.png", "/s/c.png"]), false).len(), 1);
}
#[test]
fn windows_paths_and_reports() {
let t = Table(vec!["C:\\r\\f_01.exr", "C:\\r\\f_02.exr", "C:\\r\\f_05.exr"]);
let g = group(&t, &strs(&["C:\\r\\f_02.exr"]), SequenceOptions::default());
assert_eq!(g, [Source::Sequence { files: strs(&["C:\\r\\f_01.exr", "C:\\r\\f_02.exr", "C:\\r\\f_05.exr"]), alphabetical: false }]);
assert_eq!(missing_report(&strs(&["a_001.png", "a_002.png", "a_005.png", "a_007.png"])).as_deref(), Some("3 missing frames (3–4, 6)"));
assert_eq!(missing_report(&strs(&["a1.png", "a2.png"])), None);
assert_eq!(folder("/x.png"), "/");
assert_eq!(file_name("C:\\r\\f_01.exr"), "f_01.exr");
}
}
+2 -2
View File
@@ -237,10 +237,10 @@ fn import_export_helpers() {
p.import.drag_import_as = "compLayerSizes".into();
assert_eq!(p.drag_import_as(), "compositionLayerSizes");
assert_eq!(
super::commands::missing_frames_for_tests(&["a_001.png".into(), "a_002.png".into(), "a_005.png".into(), "a_007.png".into()]).unwrap(),
crate::sequence::missing_report(&["a_001.png".into(), "a_002.png".into(), "a_005.png".into(), "a_007.png".into()]).unwrap(),
"3 missing frames (3–4, 6)"
);
assert!(super::commands::missing_frames_for_tests(&["a1.png".into(), "a2.png".into()]).is_none());
assert!(crate::sequence::missing_report(&["a1.png".into(), "a2.png".into()]).is_none());
// Append Bit Depth to File Name.
assert_eq!(p.output_name("/out/Comp 1.png", 16), "/out/Comp 1.png");
p.export.append_bits_to_name = true;
+177
View File
@@ -0,0 +1,177 @@
//! Image sequences (#297): File ▸ Import with the "<format> Sequence" option, picked ranges,
//! folders, Force Alphabetical Order, the import frame rate, Replace Footage, missing frames
//! (placeholders, as in After Effects) and Interpret Footage ▸ Start Frame.
use effectcraft_project::{Footage, FootageKind, ItemId, ItemKind};
use effectcraft_time::{FrameRate, Tick};
use serde_json::{Value, json};
use crate::Session;
/// Probes every file as a 64×32 still (the media layer's single-file probe).
struct Stills;
impl crate::Importer for Stills {
fn probe(&self, path: &str) -> Result<Footage, String> {
if !std::path::Path::new(path).is_file() {
return Err(format!("{path}: no such file"));
}
Ok(Footage { path: path.into(), kind: FootageKind::Still, width: 64, height: 32, has_video: true, codec: "PNG".into(), ..Default::default() })
}
}
/// A fresh folder with empty files of these names; returns its path.
fn folder(names: &[&str]) -> String {
use std::sync::atomic::{AtomicU32, Ordering};
static N: AtomicU32 = AtomicU32::new(0);
let d = std::env::temp_dir().join(format!("ec-seq-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
for n in names {
std::fs::write(d.join(n), b"").unwrap();
}
d.to_string_lossy().to_string()
}
fn at(dir: &str, name: &str) -> String {
std::path::Path::new(dir).join(name).to_string_lossy().to_string()
}
fn session() -> Session {
let mut s = Session { importer: Some(std::sync::Arc::new(Stills)), ..Default::default() };
s.prefs.import.sequence_fps = 30.0;
s
}
fn footage(s: &Session, item: &Value) -> (String, Footage) {
let it = s.project.item(ItemId(item.as_u64().unwrap())).unwrap();
let ItemKind::Footage(f) = &it.kind else { panic!("footage") };
(it.name.clone(), f.clone())
}
const RUN: [&str; 5] = ["shot_0001.png", "shot_0002.png", "shot_0004.png", "shot_0005.png", "notes.txt"];
#[test]
fn one_picked_numbered_file_imports_its_run_as_one_sequence() {
let dir = folder(&RUN);
let mut s = session();
let r = s.execute("file.import", json!({"paths": [at(&dir, "shot_0002.png")]})).unwrap();
assert_eq!(r["items"].as_array().unwrap().len(), 1, "{r}");
let (name, f) = footage(&s, &r["items"][0]);
assert_eq!(name, "shot_[0001-0005].png");
assert_eq!((f.kind, f.sequence.len(), f.alphabetical), (FootageKind::Sequence, 4, false));
assert_eq!(f.path, at(&dir, "shot_0001.png"));
// Frames 1–5 at Settings ▸ Import ▸ Sequence Footage (30 fps); frame 3 is a placeholder.
assert_eq!(f.duration, FrameRate::FPS_30.tick_of(5));
assert_eq!(f.sequence_file(2), None);
// Settings ▸ Import ▸ Report Missing Frames.
let w = r["warnings"][0].as_str().unwrap();
assert!(w.contains("1 missing frame (3)"), "{w}");
}
/// Picking every frame of a sequence used to make one item per frame (each a whole sequence on
/// the desktop, a still in the browser).
#[test]
fn picking_every_frame_imports_one_sequence() {
let dir = folder(&RUN);
let mut s = session();
let all: Vec<String> = RUN[..4].iter().map(|n| at(&dir, n)).collect();
let r = s.execute("file.import", json!({"paths": all, "frameRate": 24})).unwrap();
assert_eq!(r["items"].as_array().unwrap().len(), 1, "{r}");
let (_, f) = footage(&s, &r["items"][0]);
assert_eq!(f.sequence.len(), 4);
// `frameRate` sets the sequence's rate on import.
assert_eq!((f.frame_rate, f.duration), (FrameRate::FPS_24, FrameRate::FPS_24.tick_of(5)));
// A picked range is just that range.
let r = s.execute("file.import", json!({"paths": [at(&dir, "shot_0004.png"), at(&dir, "shot_0005.png")]})).unwrap();
let (name, f) = footage(&s, &r["items"][0]);
assert_eq!((name.as_str(), f.sequence.len()), ("shot_[0004-0005].png", 2));
assert!(s.execute("file.import", json!({"paths": all, "frameRate": 0})).is_err());
}
#[test]
fn the_sequence_option_off_imports_stills() {
let dir = folder(&RUN);
let mut s = session();
let r = s.execute("file.import", json!({"paths": [at(&dir, "shot_0002.png")], "sequence": false})).unwrap();
let (name, f) = footage(&s, &r["items"][0]);
assert_eq!((name.as_str(), f.kind), ("shot_0002.png", FootageKind::Still));
let r = s.execute("file.import", json!({"paths": [at(&dir, "shot_0001.png"), at(&dir, "shot_0002.png")], "sequence": false})).unwrap();
assert_eq!(r["items"].as_array().unwrap().len(), 2);
}
#[test]
fn a_folder_imports_its_files_with_runs_as_sequences() {
let dir = folder(&["a_01.png", "a_02.png", "b.png", "readme.txt"]);
let mut s = session();
let r = s.execute("file.import", json!({"paths": [dir], "background": true})).unwrap();
s.execute("jobs.wait", json!({})).unwrap();
assert!(r["job"].is_u64() || r["job"].is_string(), "{r}");
let names: Vec<String> = s.project.items.values().map(|i| i.name.clone()).collect();
assert_eq!(names, ["a_[01-02].png", "b.png"], "the text file is skipped");
}
#[test]
fn force_alphabetical_order_takes_every_image_of_the_type() {
let dir = folder(&["take_b.png", "take_a.png", "other_7.png", "c.jpg"]);
let mut s = session();
let r = s.execute("file.import", json!({"paths": [at(&dir, "take_a.png")], "alphabetical": true})).unwrap();
let (name, f) = footage(&s, &r["items"][0]);
let files: Vec<String> = f.sequence.iter().map(|p| crate::sequence::file_name(p)).collect();
assert_eq!(files, ["other_7.png", "take_a.png", "take_b.png"]);
// Its numbering doesn't count: the files play one after another.
assert_eq!((name.as_str(), f.alphabetical, f.sequence_frames()), ("other_7.png", true, 3));
assert!(r["warnings"].as_array().is_none_or(Vec::is_empty), "{r}");
}
#[test]
fn interpret_footage_sets_start_frame() {
let dir = folder(&RUN);
let mut s = session();
let item = s.execute("file.import", json!({"paths": [at(&dir, "shot_0001.png")]})).unwrap()["items"][0].clone();
s.execute("comp.new", json!({"name": "Main", "width": 64, "height": 32, "frameRate": 30, "duration": 10})).unwrap();
let layer = s.execute("layer.addItem", json!({"item": item})).unwrap()["layer"].as_u64().unwrap();
let out = |s: &Session| s.active_comp().unwrap().layer(effectcraft_project::LayerId(layer)).unwrap().out_point;
assert_eq!(out(&s), FrameRate::FPS_30.tick_of(5));
// Start Frame 2 trims frame 1: 4 frames, and the layer that ran to the end still does.
s.execute("file.interpretFootage", json!({"items": [item], "startFrame": 2})).unwrap();
assert_eq!((footage(&s, &item).1.duration, out(&s)), (FrameRate::FPS_30.tick_of(4), FrameRate::FPS_30.tick_of(4)));
// Start Frame 0: frame 0 is missing (a placeholder), 6 frames in all.
let r = s.execute("file.interpretFootage", json!({"items": [item], "startFrame": 0})).unwrap();
assert_eq!((r["items"][0]["startFrame"].as_i64(), r["items"][0]["frames"].as_i64()), (Some(0), Some(6)));
assert_eq!(footage(&s, &item).1.sequence_file(0), None);
// The first file's own number isn't stored; "file" goes back to it.
s.execute("file.interpretFootage", json!({"items": [item], "startFrame": 1})).unwrap();
assert_eq!(footage(&s, &item).1.start_frame, None);
s.execute("file.interpretFootage", json!({"items": [item], "startFrame": 3})).unwrap();
s.execute("file.interpretFootage", json!({"items": [item], "startFrame": "file"})).unwrap();
assert_eq!(footage(&s, &item).1.start_frame, None);
// The frame rate re-times the frames.
s.execute("file.interpretFootage", json!({"items": [item], "frameRate": 10})).unwrap();
assert_eq!(footage(&s, &item).1.duration, Tick::from_seconds_f64(0.5));
for bad in [json!({"startFrame": "x"}), json!({"startFrame": 1e300})] {
let mut p = bad.clone();
p["items"] = json!([item]);
assert!(s.execute("file.interpretFootage", p).is_err(), "{bad}");
}
// Undo puts the interpretation back.
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(footage(&s, &item).1.frame_rate, FrameRate::FPS_30);
}
#[test]
fn replace_footage_and_reload_keep_sequences() {
let dir = folder(&RUN);
let mut s = session();
let item = s.execute("file.import", json!({"paths": [at(&dir, "shot_0001.png")], "sequence": false})).unwrap()["items"][0].clone();
s.state.project_selection = vec![ItemId(item.as_u64().unwrap())];
s.execute("file.replaceFootage", json!({"path": at(&dir, "shot_0004.png")})).unwrap();
let (name, f) = footage(&s, &item);
assert_eq!((name.as_str(), f.sequence.len()), ("shot_[0001-0005].png", 4));
// Reload finds a new frame and keeps the interpretation.
s.execute("file.interpretFootage", json!({"items": [item], "frameRate": 12, "startFrame": 2})).unwrap();
std::fs::write(at(&dir, "shot_0003.png"), b"").unwrap();
s.execute("file.reloadFootage", json!({"items": [item]})).unwrap();
let (_, f) = footage(&s, &item);
assert_eq!((f.sequence.len(), f.frame_rate, f.start_frame), (5, FrameRate::from_f64(12.0), Some(2)));
assert_eq!(f.duration, FrameRate::from_f64(12.0).tick_of(4));
}