Skip to content

EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust

Merge remote-tracking branch 'origin/main' into enhance/avi-import

tylerjenningsw74b309e6cfd7
diff --cc Cargo.lock
index 9d818a649,4a4043140..2768cd30e
--- a/Cargo.lock
+++ b/Cargo.lock
@@@ -2055,10 -2220,20 +2219,20 @@@ version = "0.4.1
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
+ [[package]]
+ name = "filetime"
+ version = "0.2.29"
+ source = "registry+https://github.com/rust-lang/crates.io-index"
+ checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
+ dependencies = [
+ "cfg-if",
+ "libc",
+ ]
+
[[package]]
name = "filmcraft-aac"
-version = "0.1.1"
-source = "git+https://github.com/storytold/filmcraft?rev=2c5ba7a72619935f0481f99d59409e0d1844b234#2c5ba7a72619935f0481f99d59409e0d1844b234"
+version = "0.8.0"
+source = "git+https://github.com/storytold/filmcraft?rev=09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5#09aaf9bf15d510eda1c413c0ccabb1d7e08b41c5"
dependencies = [
"filmcraft-bitstream",
"thiserror 2.0.21",
diff --cc crates/project/src/footage.rs
index 000000000,ff1983d88..071409b51
mode 000000,100644..100644
--- a/crates/project/src/footage.rs
+++ b/crates/project/src/footage.rs
@@@ -1,0 -1,229 +1,234 @@@
+ use super::settings::yes;
+ use super::*;
+
+ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+ pub enum FootageKind {
+ #[default]
+ Video,
+ Still,
+ Sequence,
+ Audio,
+ /// A 3D model (glTF 2.0 / OBJ), placed as a model layer.
+ Model,
+ /// A data file (JSON, CSV, TSV) for data-driven animation: read by expressions through
+ /// `footage(name).sourceData` / `sourceText` / `dataValue`; it has no pixels.
+ Data,
+ }
+
+ /// Interpret Footage ▸ Fields and Pulldown ▸ Separate Fields.
+ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+ pub enum FieldOrder {
+ /// Progressive frames.
+ #[default]
+ Off,
+ /// Interlaced, upper (odd) field first: each field becomes a frame at twice the rate.
+ UpperFirst,
+ LowerFirst,
+ }
+
+ impl FieldOrder {
+ pub fn label(self) -> &'static str {
+ match self {
+ FieldOrder::Off => "Off",
+ FieldOrder::UpperFirst => "Upper Field First",
+ FieldOrder::LowerFirst => "Lower Field First",
+ }
+ }
+ pub fn parse(s: &str) -> Option<FieldOrder> {
+ match s.to_ascii_lowercase().replace([' ', '_', '-'], "").as_str() {
+ "off" | "none" | "progressive" => Some(FieldOrder::Off),
+ "upper" | "upperfirst" | "upperfieldfirst" => Some(FieldOrder::UpperFirst),
+ "lower" | "lowerfirst" | "lowerfieldfirst" => Some(FieldOrder::LowerFirst),
+ _ => None,
+ }
+ }
+ }
+
++/// File extensions of the movie containers footage is imported from (FilmCraft reads them). The
++/// import and proxy file dialogs, the Media Browser and `effectcraft_media::is_importable` all go
++/// by this list.
++pub const VIDEO_EXTENSIONS: &[&str] = &["mp4", "m4v", "mov", "mkv", "webm", "mxf", "avi"];
++
+ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+ pub enum AlphaMode {
+ #[default]
+ Straight,
+ Premultiplied,
+ Ignore,
+ }
+
+ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+ pub struct Footage {
+ pub path: String,
+ pub kind: FootageKind,
+ pub width: u32,
+ pub height: u32,
+ pub pixel_aspect: f64,
+ pub frame_rate: FrameRate,
+ /// Native rate before "Conform to frame rate".
+ #[serde(default)]
+ pub native_rate: Option<FrameRate>,
+ pub duration: Tick,
+ pub has_video: bool,
+ pub has_audio: bool,
+ pub alpha: AlphaMode,
+ #[serde(default)]
+ pub premul_color: [f32; 3],
+ #[serde(default = "one")]
+ pub loop_count: u32,
+ #[serde(default)]
+ pub codec: String,
+ #[serde(default)]
+ pub missing: bool,
+ /// Image sequence files (when kind = Sequence).
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub sequence: Vec<String>,
+ /// Colour profile (from the file's metadata, or Interpret Footage). `None` = sRGB.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub color_profile: Option<ColorSpace>,
+ /// One layer of a layered file (Photoshop) instead of its merged image.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub layer: Option<SourceLayer>,
+ /// Interpret Footage ▸ Fields and Pulldown ▸ Separate Fields.
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub fields: FieldOrder,
+ /// Interpret Footage ▸ Alpha ▸ Invert Alpha.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub invert_alpha: bool,
+ /// Interpret Footage ▸ Color ▸ Interpret As Linear Light: the file's values are linear.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub linear_light: bool,
+ /// Interpret Footage ▸ Color ▸ Preserve RGB: the file's values enter the composition
+ /// unconverted. Float footage (OpenEXR, float TIFF) is not sRGB-encoded on decode, and the
+ /// colour profile, Interpret As Linear Light and the working space don't apply.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub preserve_rgb: bool,
+ /// Data footage ([`FootageKind::Data`]): the file's text (JSON, CSV or TSV), kept in the
+ /// project so expressions read it everywhere (and on the web).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub data: Option<String>,
+ /// PDF / Illustrator footage: the page shown (0-based; File ▸ Import ▸ Page).
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub page: u32,
+ /// Image sequences imported with Force Alphabetical Order: the files play one after another
+ /// and their numbering doesn't count (otherwise a gap in it shows a placeholder, as in After
+ /// Effects; [`sequence`]).
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub alphabetical: bool,
+ /// Interpret Footage ▸ Start Timecode ▸ Override Start: the frame (at the footage's frame
+ /// rate) its timecode shows at its first frame. `None` = Use Source File Timecode (0: file
+ /// timecode isn't read). It only relabels source time, as in After Effects.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub start_timecode: Option<i64>,
+ }
+
+ fn is_default<T: Default + PartialEq>(v: &T) -> bool {
+ *v == T::default()
+ }
+
+ impl Default for Footage {
+ fn default() -> Self {
+ Footage {
+ path: String::new(),
+ kind: FootageKind::Still,
+ width: 0,
+ height: 0,
+ pixel_aspect: 1.0,
+ frame_rate: FrameRate::FPS_30,
+ native_rate: None,
+ duration: Tick::ZERO,
+ has_video: false,
+ has_audio: false,
+ alpha: AlphaMode::Straight,
+ premul_color: [0.0; 3],
+ loop_count: 1,
+ codec: String::new(),
+ missing: false,
+ sequence: vec![],
+ color_profile: None,
+ fields: FieldOrder::Off,
+ invert_alpha: false,
+ linear_light: false,
+ preserve_rgb: false,
+ data: None,
+ layer: None,
+ page: 0,
+ alphabetical: false,
+ start_timecode: None,
+ }
+ }
+ }
+
+ impl Footage {
+ /// Interpret As Linear Light applies (Preserve RGB passes the file's values through).
+ pub fn linear_light_applies(&self) -> bool {
+ self.linear_light && !self.preserve_rgb
+ }
+
+ /// How long the footage plays: its duration times Interpret Footage ▸ Loop.
+ pub fn looped_duration(&self) -> Tick {
+ Tick(self.duration.0.saturating_mul(self.loop_count.max(1) as i64))
+ }
+
+ /// Source time as the footage's timecode: its frame `frame` from Start Timecode
+ /// (`0:00:41:20`), as the Footage panel shows it.
+ pub fn timecode(&self, frame: i64) -> String {
+ effectcraft_time::format_timecode_ae(frame.saturating_add(self.start_timecode.unwrap_or(0)), self.frame_rate, false)
+ }
+
+ /// The data format of data footage: `json`, `csv` or `tsv` (from the file extension).
+ pub fn data_format(&self) -> Option<&'static str> {
+ if self.kind != FootageKind::Data {
+ return None;
+ }
+ let ext = std::path::Path::new(&self.path).extension().and_then(std::ffi::OsStr::to_str).unwrap_or("").to_ascii_lowercase();
+ Some(match ext.as_str() {
+ "csv" => "csv",
+ "tsv" | "tab" => "tsv",
+ _ => "json",
+ })
+ }
+ }
+
+ /// A proxy: a stand-in file used instead of a footage item or composition (File ▸ Set Proxy /
+ /// Create Proxy), when its Use Proxy switch is on and the render's Proxy Use allows it.
+ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+ pub struct Proxy {
+ /// The proxy's footage (path, size, rate…; File ▸ Interpret Footage ▸ Proxy edits it).
+ pub footage: Footage,
+ /// Use Proxy (the Project panel's proxy indicator: filled = in use, hollow = set but off).
+ #[serde(default = "yes")]
+ pub enabled: bool,
+ }
+
+ /// A layer of a layered still (a Photoshop document, or a PDF / Illustrator / EPS file) used as
+ /// footage (File ▸ Import ▸ Composition / Composition – Retain Layer Sizes, or Choose Layer).
+ #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+ pub struct SourceLayer {
+ /// Layer record index in the file (bottom of the stack = 0).
+ pub index: u32,
+ pub name: String,
+ /// The footage is the layer's own bounds (Retain Layer Sizes) rather than the document size.
+ #[serde(default)]
+ pub layer_size: bool,
+ /// A Photoshop smart object: the unique id of its embedded file (linked layer data), which
+ /// is the footage instead of the layer's pixels.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub embedded: Option<String>,
+ /// A smart object with a perspective quad or a warp: the footage is its embedded file baked
+ /// as placed (warped and pinned to its corners) over the placed bounds in document space.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub placed: bool,
+ }
+
+ fn one() -> u32 {
+ 1
+ }
+
+ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+ pub struct Solid {
+ pub color: [f32; 3],
+ pub width: u32,
+ pub height: u32,
+ pub pixel_aspect: f64,
+ }
diff --cc crates/project/src/lib.rs
index 93b099328,8e1409c37..6fa5ef793
--- a/crates/project/src/lib.rs
+++ b/crates/project/src/lib.rs
@@@ -29,1398 -29,20 +29,20 @@@ use serde::{Deserialize, Serialize}
pub use effectcraft_keyframe as keyframe;
pub use effectcraft_keyframe::{Keyframe, Value};
- /// The project file schema. 2: effects on layers without a source rectangle (shape, text)
- /// measure positions from the top-left of their comp-sized bounds (effect space), not from
- /// the layer's origin; projects from schema 1 are converted when opened (#227).
- pub const SCHEMA_VERSION: u32 = 2;
-
- /// The first schema in which effect positions are in effect space (see [`SCHEMA_VERSION`]).
- pub const SCHEMA_EFFECT_SPACE: u32 = 2;
-
- /// The EffectCraft version, written into project files as `savedBy`.
- pub const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
-
- /// The EffectCraft version that wrote a project file (its `savedBy`), when it says.
- pub fn saved_by(text: &str) -> Option<String> {
- #[derive(Deserialize)]
- struct Meta {
- #[serde(rename = "savedBy", default)]
- saved_by: Option<String>,
- }
- serde_json::from_str::<Meta>(text).ok()?.saved_by
- }
-
- /// The compositions that were open when a project file was saved and their current times
- /// (`activeComp`, `openComps` and `compTimes` next to `savedBy`), so it reopens where it was left
- /// (#748, #1714). Editor state rather than project
- /// content: opening a comp doesn't make the project unsaved, and it isn't part of
- /// [`Project`]. Older files have none; older versions ignore it.
- #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
- #[serde(rename_all = "camelCase")]
- pub struct SavedView {
- /// The comp shown in the viewer and the Timeline.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub active_comp: Option<ItemId>,
- /// The open comps (Timeline tabs), in tab order.
- #[serde(skip_serializing_if = "Vec::is_empty")]
- pub open_comps: Vec<ItemId>,
- /// Each comp's current time, so a project reopens on the frame it was saved at rather than
- /// at 0, where its layers may not have started yet (#1714).
- #[serde(skip_serializing_if = "BTreeMap::is_empty")]
- pub comp_times: BTreeMap<ItemId, Tick>,
- }
-
- /// The view a project file was saved with ([`SavedView`]); empty for older files. Values that
- /// aren't ids are ignored (whether an id still names a comp is up to the caller).
- pub fn saved_view(text: &str) -> SavedView {
- #[derive(Deserialize)]
- struct Meta {
- #[serde(rename = "activeComp", default)]
- active_comp: Option<serde_json::Value>,
- #[serde(rename = "openComps", default)]
- open_comps: Option<serde_json::Value>,
- #[serde(rename = "compTimes", default)]
- comp_times: Option<serde_json::Value>,
- }
- let Ok(m) = serde_json::from_str::<Meta>(text) else { return SavedView::default() };
- SavedView {
- active_comp: m.active_comp.as_ref().and_then(serde_json::Value::as_u64).map(ItemId),
- open_comps: m
- .open_comps
- .as_ref()
- .and_then(serde_json::Value::as_array)
- .map_or_else(Vec::new, |a| a.iter().filter_map(serde_json::Value::as_u64).map(ItemId).collect()),
- comp_times: m
- .comp_times
- .as_ref()
- .and_then(serde_json::Value::as_object)
- .map_or_else(BTreeMap::new, |o| o.iter().filter_map(|(k, v)| Some((ItemId(k.parse().ok()?), Tick(v.as_i64()?)))).collect()),
- }
- }
-
- /// Whether version `a` (`major.minor.patch`, pre-release suffixes ignored) is newer than `b`.
- pub fn is_newer_version(a: &str, b: &str) -> bool {
- let parts = |v: &str| -> [u64; 3] {
- let mut n = v.split(['-', '+']).next().unwrap_or("").split('.').map(|x| x.parse().unwrap_or(0));
- [n.next().unwrap_or(0), n.next().unwrap_or(0), n.next().unwrap_or(0)]
- };
- parts(a) > parts(b)
- }
-
- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
- pub struct ItemId(pub u64);
-
- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
- pub struct LayerId(pub u64);
-
- #[derive(Debug, thiserror::Error)]
- pub enum ProjectError {
- #[error("no item {0:?}")]
- NoItem(ItemId),
- #[error("item {0:?} is not a composition")]
- NotComp(ItemId),
- #[error("no layer {0:?}")]
- NoLayer(LayerId),
- #[error("no property `{0}`")]
- NoProperty(String),
- #[error("{0}")]
- Invalid(String),
- }
-
- /// Project bit depth.
- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
- pub enum BitDepth {
- #[default]
- Bpc8,
- Bpc16,
- Bpc32,
- }
-
- impl BitDepth {
- pub fn label(self) -> &'static str {
- match self {
- BitDepth::Bpc8 => "8 bpc",
- BitDepth::Bpc16 => "16 bpc",
- BitDepth::Bpc32 => "32 bpc",
- }
- }
- pub fn next(self) -> BitDepth {
- match self {
- BitDepth::Bpc8 => BitDepth::Bpc16,
- BitDepth::Bpc16 => BitDepth::Bpc32,
- BitDepth::Bpc32 => BitDepth::Bpc8,
- }
- }
- pub fn is_float(self) -> bool {
- self == BitDepth::Bpc32
- }
- /// Quantisation levels per channel of the integer depths (8 bpc: 255; 16 bpc: 32768, After
- /// Effects' "15 + 1" bit range), `None` for 32 bpc float.
- pub fn levels(self) -> Option<f32> {
- match self {
- BitDepth::Bpc8 => Some(255.0),
- BitDepth::Bpc16 => Some(32768.0),
- BitDepth::Bpc32 => None,
- }
- }
- pub fn bits(self) -> u32 {
- match self {
- BitDepth::Bpc8 => 8,
- BitDepth::Bpc16 => 16,
- BitDepth::Bpc32 => 32,
- }
- }
- }
-
- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
- pub enum TimeDisplayStyle {
- #[default]
- Timecode,
- Frames,
- /// Feet + Frames, 35 mm film (16 frames per foot).
- Feet35,
- /// Feet + Frames, 16 mm film (40 frames per foot).
- Feet16,
- }
-
- impl TimeDisplayStyle {
- /// Frames per foot of the Feet + Frames styles.
- pub fn frames_per_foot(self) -> Option<i64> {
- match self {
- TimeDisplayStyle::Feet35 => Some(16),
- TimeDisplayStyle::Feet16 => Some(40),
- _ => None,
- }
- }
- pub fn id(self) -> &'static str {
- match self {
- TimeDisplayStyle::Timecode => "timecode",
- TimeDisplayStyle::Frames => "frames",
- TimeDisplayStyle::Feet35 => "feet35",
- TimeDisplayStyle::Feet16 => "feet16",
- }
- }
- pub fn parse(s: &str) -> Option<TimeDisplayStyle> {
- let k: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase();
- match k.as_str() {
- "timecode" => Some(TimeDisplayStyle::Timecode),
- "frames" => Some(TimeDisplayStyle::Frames),
- "feet35" | "feetframes" | "feetandframes" | "feet35mm" | "35mm" | "feetframes35mm" => Some(TimeDisplayStyle::Feet35),
- "feet16" | "feet16mm" | "16mm" | "feetframes16mm" => Some(TimeDisplayStyle::Feet16),
- _ => None,
- }
- }
- }
-
- /// Project Settings ▸ Color ▸ Color Engine.
- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
- pub enum ColorEngine {
- /// Built-in colour management (ICC-style working spaces).
- #[default]
- Adobe,
- /// OCIO managed, with the built-in configuration (ACES working spaces).
- Ocio,
- }
-
- /// Project Settings ▸ Color ▸ HDR: how over-range (HDR) values reach a standard-dynamic-range
- /// display or output.
- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
- pub enum HdrMode {
- /// Values above 1.0 clip.
- #[default]
- Clip,
- /// Highlights above 80% are companded (an exponential knee) into the remaining range.
- Compand,
- /// Extended Reinhard tone mapping of luminance (white at 4.0).
- ToneMap,
- }
-
- #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
- pub struct ProjectSettings {
- pub bit_depth: BitDepth,
- /// Linearize Working Space: the working space uses linear light (1.0 gamma) for everything
- /// (sources, effects, blending). Needs a working space.
- pub linearize: bool,
- /// Working Space (colour management). `None` = no colour management.
- #[serde(default)]
- pub working_space: Option<ColorSpace>,
- /// Blend Colors Using 1.0 Gamma: layers blend in linear light (sources and effects stay in
- /// the working space's encoding).
- #[serde(default)]
- pub blend_linear: bool,
- pub time_display: TimeDisplayStyle,
- /// Frame numbering starts at 0 (or 1).
- pub frame_start: i64,
- pub audio_sample_rate: u32,
- /// Video Rendering and Effects ▸ Use: Mercury GPU Acceleration (`true`, the default; used
- /// when a GPU adapter exists) or Mercury Software Only (`false`, the CPU compositor).
- #[serde(default = "yes")]
- pub gpu_acceleration: bool,
- /// The project's comment (Metadata panel).
- #[serde(default, skip_serializing_if = "String::is_empty")]
- pub comment: String,
- /// Color Engine (Adobe-style built-in or OCIO with ACES working spaces).
- #[serde(default)]
- pub color_engine: ColorEngine,
- /// HDR handling for standard-dynamic-range output (display and renders).
- #[serde(default)]
- pub hdr: HdrMode,
- /// The space the top-level comp is output in (renders and the viewer's source). `None` =
- /// sRGB; Rec. 2100 PQ / HLG give HDR output.
- #[serde(default)]
- pub output_space: Option<ColorSpace>,
- /// Working Gamma, 2.2 or 2.4 (`app.project.workingGamma`): with no working space, the curve
- /// Interpret As Linear Light footage is encoded with and Blend Colors Using 1.0 Gamma
- /// linearizes with: the sRGB curve at 2.2, a pure 2.4 power curve at 2.4. Ignored with a
- /// working space (as in After Effects).
- #[serde(default = "gamma_22")]
- pub working_gamma: f64,
- }
-
- fn gamma_22() -> f64 {
- 2.2
- }
-
- impl ProjectSettings {
- /// Working Gamma is 2.4 (anything else reads as 2.2).
- pub fn working_gamma_24(&self) -> bool {
- (self.working_gamma - 2.4).abs() < 0.05
- }
- }
-
- impl Default for ProjectSettings {
- fn default() -> Self {
- ProjectSettings {
- bit_depth: BitDepth::Bpc8,
- linearize: false,
- working_space: None,
- blend_linear: false,
- time_display: TimeDisplayStyle::Timecode,
- frame_start: 0,
- audio_sample_rate: 48_000,
- gpu_acceleration: true,
- comment: String::new(),
- color_engine: ColorEngine::Adobe,
- hdr: HdrMode::Clip,
- output_space: None,
- working_gamma: 2.2,
- }
- }
- }
-
- #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
- pub struct Marker {
- pub time: Tick,
- #[serde(default)]
- pub duration: Tick,
- #[serde(default)]
- pub comment: String,
- #[serde(default)]
- pub label: Label,
- #[serde(default)]
- pub chapter: String,
- #[serde(default)]
- pub url: String,
- #[serde(default)]
- pub protected: bool,
- /// Web link frame target (`_blank`, a frame name…).
- #[serde(default, skip_serializing_if = "String::is_empty")]
- pub frame_target: String,
- /// Flash/video cue point (Event or Navigation) with name and parameters.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub cue_point: Option<CuePoint>,
- }
-
- /// A marker's cue point (Composition/Layer Marker dialog ▸ Cue Point).
- #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
- pub struct CuePoint {
- pub name: String,
- /// Navigation (true) or Event cue point.
- #[serde(default)]
- pub navigation: bool,
- /// (name, value) parameter pairs.
- #[serde(default)]
- pub params: Vec<(String, String)>,
- }
-
- /// 3D renderer of a composition.
- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
- pub enum Renderer {
- #[default]
- Classic3D,
- Advanced3D,
- }
-
- /// A composition's Resolution (the Composition panel's Resolution/Down Sample Factor popup, View ▸
- /// Resolution): how many of its pixels the viewer renders. Auto follows the magnification.
- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
- pub enum Resolution {
- #[default]
- Auto,
- Full,
- Half,
- Third,
- Quarter,
- /// View ▸ Resolution ▸ Custom: render every n-th pixel (2..=40).
- Custom(u8),
- }
-
- impl Resolution {
- pub const ALL: [Resolution; 5] = [Resolution::Auto, Resolution::Full, Resolution::Half, Resolution::Third, Resolution::Quarter];
- pub fn label(self) -> &'static str {
- match self {
- Resolution::Auto => "Auto",
- Resolution::Full => "Full",
- Resolution::Half => "Half",
- Resolution::Third => "Third",
- Resolution::Quarter => "Quarter",
- Resolution::Custom(_) => "Custom",
- }
- }
- pub fn is_auto(&self) -> bool {
- *self == Resolution::Auto
- }
- /// The down-sample factor (render every n-th pixel); `None` for Auto.
- pub fn factor(self) -> Option<u8> {
- match self {
- Resolution::Auto => None,
- Resolution::Full => Some(1),
- Resolution::Half => Some(2),
- Resolution::Third => Some(3),
- Resolution::Quarter => Some(4),
- Resolution::Custom(n) => Some(n),
- }
- }
- /// The resolution that renders every `n`-th pixel (1 = Full … 4 = Quarter; up to 40).
- pub fn from_factor(n: u64) -> Resolution {
- match n.clamp(1, 40) {
- 1 => Resolution::Full,
- 2 => Resolution::Half,
- 3 => Resolution::Third,
- 4 => Resolution::Quarter,
- n => Resolution::Custom(n as u8),
- }
- }
- /// Render scale for a viewer magnification (and display pixel density).
- pub fn scale(self, zoom: f32, ppp: f32) -> f64 {
- match self.factor() {
- Some(n) => 1.0 / f64::from(n.clamp(1, 40)),
- // As in After Effects, Auto renders the pixels the magnification needs: the coarsest
- // whole factor that still gives every screen pixel a rendered one (Full above 50 %,
- // Half down to 33.3 %, Third down to 25 %, Quarter below), never fewer (#417).
- None => {
- let n = (1.0 / (zoom * ppp) as f64 + 1e-3).floor();
- if n >= 1.0 { 1.0 / n.min(4.0) } else { 1.0 }
- }
- }
- }
- }
-
- #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
- pub struct Comp {
- pub width: u32,
- pub height: u32,
- pub pixel_aspect: f64,
- pub frame_rate: FrameRate,
- pub duration: Tick,
- /// Start timecode/frame shown for time 0.
- pub display_start: Tick,
- pub background: [f32; 3],
- pub work_area: (Tick, Tick),
- /// Layer #1 first (top of the stack).
- pub layers: Vec<Layer>,
- #[serde(default)]
- pub markers: Vec<Marker>,
- pub shutter_angle: f64,
- pub shutter_phase: f64,
- /// Samples Per Frame: the minimum motion-blur samples (and the count for 3D layers).
- pub motion_blur_samples: u32,
- /// Adaptive Sample Limit (Composition Settings ▸ Advanced): the most samples a 2D layer gets
- /// when it moves far within the shutter.
- #[serde(default = "adaptive_limit_default")]
- pub motion_blur_adaptive_limit: u32,
- #[serde(default)]
- pub renderer: Renderer,
- /// Comp switches (timeline toolbar).
- #[serde(default)]
- pub hide_shy: bool,
- #[serde(default = "yes")]
- pub enable_motion_blur: bool,
- #[serde(default = "yes")]
- pub enable_frame_blending: bool,
- #[serde(default)]
- pub draft_3d: bool,
- /// Composition Settings ▸ Advanced ▸ Preserve frame rate when nested or in render queue:
- /// nested in another comp, or rendered at another rate, it shows only its own frames.
- #[serde(default)]
- pub preserve_frame_rate: bool,
- /// Composition Settings ▸ Advanced ▸ Preserve resolution when nested: nested in a comp
- /// previewed at a lower resolution, it still renders at full size.
- #[serde(default)]
- pub preserve_resolution: bool,
- #[serde(default)]
- pub poster_time: Tick,
- /// Global Light for layer styles (Layer ▸ Layer Styles ▸ Blending Options).
- #[serde(default)]
- pub global_light: styles::GlobalLight,
- /// Viewer guides (View ▸ Add Guide…), in comp pixels.
- #[serde(default, skip_serializing_if = "Vec::is_empty")]
- pub guides: Vec<Guide>,
- /// Essential Graphics: the controls this comp exposes to instances and templates.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub essential: Option<essential::EssentialGraphics>,
- /// The Composition panel's Resolution, saved with the project as in After Effects. It changes
- /// what the viewer renders, not the comp's pixels ([`Comp::same_pixels`]), and stays out of
- /// the undo history.
- #[serde(default, skip_serializing_if = "Resolution::is_auto")]
- pub resolution: Resolution,
- }
-
- /// A viewer guide line: vertical guides sit at an x position, horizontal ones at a y position.
- #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
- pub struct Guide {
- pub vertical: bool,
- /// Comp pixels, or percent of the comp's width (vertical) / height (horizontal) when
- /// [`Guide::percent`] is set.
- pub position: f64,
- /// A percentage guide (After Effects 26.5): `position` is a percent of the comp's size, so the
- /// guide keeps its relative place when the comp is resized. Absent in older projects.
- #[serde(default, skip_serializing_if = "std::ops::Not::not")]
- pub percent: bool,
- }
-
- impl Guide {
- /// The comp's extent along this guide's axis, never zero.
- fn extent(&self, width: u32, height: u32) -> f64 {
- f64::from(if self.vertical { width } else { height }).max(1.0)
- }
-
- /// The guide's position in comp pixels for a comp of this size.
- pub fn px(&self, width: u32, height: u32) -> f64 {
- if self.percent { self.position / 100.0 * self.extent(width, height) } else { self.position }
- }
-
- /// Place the guide at `px` comp pixels, keeping its unit.
- pub fn set_px(&mut self, px: f64, width: u32, height: u32) {
- self.position = if self.percent { px / self.extent(width, height) * 100.0 } else { px };
- }
-
- /// Switch between pixels and percent without moving the guide on the comp.
- pub fn set_percent(&mut self, percent: bool, width: u32, height: u32) {
- let px = self.px(width, height);
- self.percent = percent;
- self.set_px(px, width, height);
- }
- }
-
- fn yes() -> bool {
- true
- }
-
- fn adaptive_limit_default() -> u32 {
- 128
- }
-
- impl Comp {
- pub fn new(width: u32, height: u32, frame_rate: FrameRate, duration: Tick) -> Comp {
- Comp {
- width,
- height,
- pixel_aspect: 1.0,
- frame_rate,
- duration,
- display_start: Tick::ZERO,
- background: [0.0, 0.0, 0.0],
- work_area: (Tick::ZERO, duration),
- layers: vec![],
- markers: vec![],
- shutter_angle: 180.0,
- shutter_phase: -90.0,
- motion_blur_samples: 16,
- motion_blur_adaptive_limit: 128,
- renderer: Renderer::Classic3D,
- hide_shy: false,
- enable_motion_blur: true,
- enable_frame_blending: true,
- draft_3d: false,
- preserve_frame_rate: false,
- preserve_resolution: false,
- poster_time: Tick::ZERO,
- guides: vec![],
- global_light: styles::GlobalLight::default(),
- essential: None,
- resolution: Resolution::Auto,
- }
- }
- /// Whether the composition has a frame at its time `t`: nested, it shows nothing before it
- /// starts or after it ends (a precomp layer trimmed or remapped past it).
- pub fn covers(&self, t: Tick) -> bool {
- t >= Tick::ZERO && t < self.duration
- }
- /// A new, empty composition with this one's settings (frame rate, pixel aspect, background,
- /// motion blur, frame blending and the 3D renderer), as Pre-compose makes.
- pub fn nested_like(&self, width: u32, height: u32, duration: Tick) -> Comp {
- Comp {
- pixel_aspect: self.pixel_aspect,
- background: self.background,
- shutter_angle: self.shutter_angle,
- shutter_phase: self.shutter_phase,
- motion_blur_samples: self.motion_blur_samples,
- motion_blur_adaptive_limit: self.motion_blur_adaptive_limit,
- renderer: self.renderer,
- enable_motion_blur: self.enable_motion_blur,
- enable_frame_blending: self.enable_frame_blending,
- preserve_frame_rate: self.preserve_frame_rate,
- preserve_resolution: self.preserve_resolution,
- ..Comp::new(width, height, self.frame_rate, duration)
- }
- }
- pub fn layer(&self, id: LayerId) -> Option<&Layer> {
- self.layers.iter().find(|l| l.id == id)
- }
- pub fn layer_mut(&mut self, id: LayerId) -> Option<&mut Layer> {
- self.layers.iter_mut().find(|l| l.id == id)
- }
- /// 1-based layer number (#) of a layer.
- pub fn index_of(&self, id: LayerId) -> Option<usize> {
- self.layers.iter().position(|l| l.id == id).map(|i| i + 1)
- }
- pub fn layer_by_name(&self, name: &str) -> Option<&Layer> {
- self.layers.iter().find(|l| l.name == name)
- }
- pub fn frame_duration(&self) -> Tick {
- self.frame_rate.frame_duration()
- }
- /// Any 3D layer present (camera/lights or a 3D switch).
- pub fn has_3d(&self) -> bool {
- self.layers.iter().any(|l| l.switches.three_d || matches!(l.source, LayerSource::Camera | LayerSource::Light { .. }))
- }
- /// The active camera at `t`: the topmost enabled camera layer active at that time.
- pub fn active_camera(&self, t: Tick) -> Option<&Layer> {
- self.layers.iter().find(|l| matches!(l.source, LayerSource::Camera) && l.switches.video && l.is_active_at(t))
- }
- /// Unique layer name with a numeric suffix (`Shape Layer 2`).
- pub fn unique_layer_name(&self, base: &str) -> String {
- if !self.layers.iter().any(|l| l.name == base) {
- return base.to_string();
- }
- let stem = base.trim_end_matches(|c: char| c.is_ascii_digit()).trim_end();
- (2..).map(|i| format!("{stem} {i}")).find(|n| !self.layers.iter().any(|l| &l.name == n)).unwrap_or_default()
- }
- }
-
- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
- pub enum LightKind {
- Parallel,
- Spot,
- #[default]
- Point,
- Ambient,
- Environment,
- }
-
- impl LightKind {
- pub const ALL: [LightKind; 5] = [LightKind::Parallel, LightKind::Spot, LightKind::Point, LightKind::Ambient, LightKind::Environment];
- pub fn label(self) -> &'static str {
- match self {
- LightKind::Parallel => "Parallel",
- LightKind::Spot => "Spot",
- LightKind::Point => "Point",
- LightKind::Ambient => "Ambient",
- LightKind::Environment => "Environment",
- }
- }
- }
-
- /// A parametric 3D primitive (Layer ▸ New ▸ Cube/Sphere/Plane/Torus/Cone/Cylinder).
- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
- pub enum PrimitiveKind {
- #[default]
- Cube,
- Sphere,
- Plane,
- Torus,
- Cone,
- Cylinder,
- }
-
- impl PrimitiveKind {
- pub const ALL: [PrimitiveKind; 6] =
- [PrimitiveKind::Cube, PrimitiveKind::Sphere, PrimitiveKind::Plane, PrimitiveKind::Torus, PrimitiveKind::Cone, PrimitiveKind::Cylinder];
- pub fn label(self) -> &'static str {
- match self {
- PrimitiveKind::Cube => "Cube",
- PrimitiveKind::Sphere => "Sphere",
- PrimitiveKind::Plane => "Plane",
- PrimitiveKind::Torus => "Torus",
- PrimitiveKind::Cone => "Cone",
- PrimitiveKind::Cylinder => "Cylinder",
- }
- }
- pub fn parse(s: &str) -> Option<PrimitiveKind> {
- PrimitiveKind::ALL.into_iter().find(|k| k.label().eq_ignore_ascii_case(s.trim()))
- }
- }
-
- /// What a layer shows.
- #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
- #[serde(tag = "type")]
- pub enum LayerSource {
- /// Footage item (video, still, sequence, audio).
- Footage {
- item: ItemId,
- },
- /// Nested composition (precomp).
- Comp {
- item: ItemId,
- },
- /// Solid item (solids also back adjustment layers).
- Solid {
- item: ItemId,
- },
- Text,
- Shape,
- Null,
- Camera,
- Light {
- kind: LightKind,
- },
- /// An imported 3D model (a footage item of kind [`FootageKind::Model`]; Advanced 3D).
- Model {
- item: ItemId,
- },
- /// A parametric 3D primitive (Advanced 3D).
- Primitive {
- kind: PrimitiveKind,
- },
- }
-
- impl LayerSource {
- pub fn item(&self) -> Option<ItemId> {
- match self {
- LayerSource::Footage { item } | LayerSource::Comp { item } | LayerSource::Solid { item } | LayerSource::Model { item } => Some(*item),
- _ => None,
- }
- }
- pub fn type_name(&self) -> &'static str {
- match self {
- LayerSource::Footage { .. } => "Footage",
- LayerSource::Comp { .. } => "Composition",
- LayerSource::Solid { .. } => "Solid",
- LayerSource::Text => "Text",
- LayerSource::Shape => "Shape",
- LayerSource::Null => "Null",
- LayerSource::Camera => "Camera",
- LayerSource::Light { .. } => "Light",
- LayerSource::Model { .. } => "3D Model",
- LayerSource::Primitive { .. } => "3D Primitive",
- }
- }
- /// Layers with pixels (cameras, lights and nulls have none).
- pub fn is_av(&self) -> bool {
- !matches!(self, LayerSource::Camera | LayerSource::Light { .. } | LayerSource::Null)
- }
- /// A 3D model or primitive layer (meshes; drawn by the Advanced 3D renderer).
- pub fn is_model(&self) -> bool {
- matches!(self, LayerSource::Model { .. } | LayerSource::Primitive { .. })
- }
- }
-
- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
- pub enum Quality {
- #[default]
- Best,
- Draft,
- Wireframe,
- }
-
- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
- pub enum Sampling {
- #[default]
- Bilinear,
- Bicubic,
- }
-
- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
- pub enum FrameBlend {
- #[default]
- Off,
- FrameMix,
- PixelMotion,
- }
-
- #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
- pub struct Switches {
- pub video: bool,
- pub audio: bool,
- pub solo: bool,
- pub locked: bool,
- pub shy: bool,
- /// Collapse transformations (precomps) / continuously rasterize (vector layers).
- pub collapse: bool,
- pub quality: Quality,
- pub sampling: Sampling,
- pub effects: bool,
- pub frame_blend: FrameBlend,
- pub motion_blur: bool,
- pub adjustment: bool,
- pub three_d: bool,
- pub guide: bool,
- }
-
- impl Default for Switches {
- fn default() -> Self {
- Switches {
- video: true,
- audio: true,
- solo: false,
- locked: false,
- shy: false,
- collapse: false,
- quality: Quality::Best,
- sampling: Sampling::Bilinear,
- effects: true,
- frame_blend: FrameBlend::Off,
- motion_blur: false,
- adjustment: false,
- three_d: false,
- guide: false,
- }
- }
- }
-
- // What a frame's pixels depend on. Caches key on it: the Audio, Lock and Shy switches and Hide
- // Shy Layers don't change pixels, so toggling them keeps cached frames (#103).
-
- impl Switches {
- /// These switches with Audio, Lock and Shy at their defaults.
- pub fn pixels(&self) -> Switches {
- Switches { audio: true, locked: false, shy: false, ..self.clone() }
- }
- }
-
- impl Layer {
- /// Draws the same pixels as `o`: equal but for the Audio, Lock and Shy switches.
- pub fn same_pixels(&self, o: &Layer) -> bool {
- // Every field (no `..`: a new field must be considered here); the property tree last.
- let Layer {
- id,
- name,
- source,
- label,
- comment,
- start_time,
- in_point,
- out_point,
- stretch,
- switches,
- blend_mode,
- preserve_transparency,
- track_matte,
- parent,
- markers,
- markers_locked,
- auto_orient,
- environment,
- environment_background,
- props,
- } = self;
- *id == o.id
- && *name == o.name
- && *source == o.source
- && *label == o.label
- && *comment == o.comment
- && *start_time == o.start_time
- && *in_point == o.in_point
- && *out_point == o.out_point
- && *stretch == o.stretch
- && switches.pixels() == o.switches.pixels()
- && *blend_mode == o.blend_mode
- && *preserve_transparency == o.preserve_transparency
- && *track_matte == o.track_matte
- && *parent == o.parent
- && *markers == o.markers
- && *markers_locked == o.markers_locked
- && *auto_orient == o.auto_orient
- && *environment == o.environment
- && *environment_background == o.environment_background
- && *props == o.props
- }
- }
-
- impl Comp {
- /// Draws the same pixels as `o`: equal but for its layers' Audio, Lock and Shy switches, Hide
- /// Shy Layers and the viewer's Resolution.
- pub fn same_pixels(&self, o: &Comp) -> bool {
- self.same_settings(o) && self.layers.len() == o.layers.len() && self.layers.iter().zip(&o.layers).all(|(a, b)| a.same_pixels(b))
- }
-
- /// [`Self::same_pixels`] but for the layers.
- fn same_settings(&self, o: &Comp) -> bool {
- // Every field (no `..`: a new field must be considered here).
- let Comp {
- width,
- height,
- pixel_aspect,
- frame_rate,
- duration,
- display_start,
- background,
- work_area,
- layers: _,
- markers,
- shutter_angle,
- shutter_phase,
- motion_blur_samples,
- motion_blur_adaptive_limit,
- renderer,
- hide_shy: _,
- enable_motion_blur,
- enable_frame_blending,
- draft_3d,
- preserve_frame_rate,
- preserve_resolution,
- poster_time,
- global_light,
- guides,
- essential,
- resolution: _,
- } = self;
- *width == o.width
- && *height == o.height
- && *pixel_aspect == o.pixel_aspect
- && *frame_rate == o.frame_rate
- && *duration == o.duration
- && *display_start == o.display_start
- && *background == o.background
- && *work_area == o.work_area
- && *markers == o.markers
- && *shutter_angle == o.shutter_angle
- && *shutter_phase == o.shutter_phase
- && *motion_blur_samples == o.motion_blur_samples
- && *motion_blur_adaptive_limit == o.motion_blur_adaptive_limit
- && *renderer == o.renderer
- && *enable_motion_blur == o.enable_motion_blur
- && *enable_frame_blending == o.enable_frame_blending
- && *draft_3d == o.draft_3d
- && *preserve_frame_rate == o.preserve_frame_rate
- && *preserve_resolution == o.preserve_resolution
- && *poster_time == o.poster_time
- && *global_light == o.global_light
- && *guides == o.guides
- && *essential == o.essential
- }
-
- /// The comp-time span (`in_point..out_point` of every layer changed, added or removed,
- /// widened by the shutter) outside which `self` draws the same pixels as `o`, so cached
- /// frames there stay valid (#1641). `None` when the edit can reach any frame: a comp setting,
- /// a layer reorder, Solo turning on or off, an expression (it reads anything), or a changed
- /// layer another layer parents to, mattes with or picks in an effect.
- pub fn changed_span(&self, o: &Comp) -> Option<(Tick, Tick)> {
- fn reads(g: &PropGroup, changed: &[LayerId]) -> bool {
- g.children.iter().any(|c| match c {
- Node::Prop(p) => {
- p.expr.is_some()
- || std::iter::once(&p.value)
- .chain(p.keys.iter().map(|k| &k.value))
- .any(|v| matches!(v, Value::Layer(Some(id)) if changed.contains(&LayerId(*id))))
- }
- Node::Group(g) => reads(g, changed),
- })
- }
- // Solo hides every other layer at every frame.
- if !self.same_settings(o) || self.any_solo() != o.any_solo() {
- return None;
- }
- let common = |a: &Comp, b: &Comp| a.layers.iter().map(|l| l.id).filter(|id| b.layer(*id).is_some()).collect::<Vec<_>>();
- if common(self, o) != common(o, self) {
- return None;
- }
- let mut changed = Vec::new();
- let mut span: Option<(Tick, Tick)> = None;
- // Each changed layer comes up from both sides: its old and its new span.
- for (l, other) in self.layers.iter().map(|l| (l, o.layer(l.id))).chain(o.layers.iter().map(|l| (l, self.layer(l.id)))) {
- if other.is_some_and(|b| l.same_pixels(b)) {
- continue;
- }
- changed.push(l.id);
- let (s, e) = (l.in_point.min(l.out_point), l.in_point.max(l.out_point));
- span = Some(span.map_or((s, e), |(a, b)| (a.min(s), b.max(e))));
- }
- let reaches = |l: &Layer| {
- l.parent.is_some_and(|p| changed.contains(&p)) || l.track_matte.as_ref().is_some_and(|m| changed.contains(&m.layer)) || reads(&l.props, &changed)
- };
- if self.layers.iter().chain(&o.layers).any(reaches) {
- return None;
- }
- // A frame at `t` samples cameras, lights and transforms over its shutter,
- // `t + (phase + angle * 0..=1) / 360` frames, and draws the layers active at `t` itself.
- let (a, p) = (self.shutter_angle / 360.0, self.shutter_phase / 360.0);
- let fd = self.frame_duration().seconds();
- let (before, after) = (Tick::from_seconds_f64(p.max(p + a).max(0.0) * fd), Tick::from_seconds_f64(-p.min(p + a).min(0.0) * fd));
- span.map(|(s, e)| (s - before, e + after))
- }
-
- /// Some layer is soloed: only the soloed layers draw.
- pub fn any_solo(&self) -> bool {
- self.layers.iter().any(|l| l.switches.solo && l.source.is_av())
- }
-
- /// Draws the same pixels as `o` once plain markers are ignored: they change no pixels. Protected
- /// time markers with a duration set the timing (Responsive Design), so those still count.
- pub fn same_pixels_ignoring_markers(&self, o: &Comp) -> bool {
- let protected =
- |m: &[Marker]| -> Vec<(Tick, Tick)> { m.iter().filter(|m| m.protected && m.duration > Tick::ZERO).map(|m| (m.time, m.duration)).collect() };
- if protected(&self.markers) != protected(&o.markers) {
- return false;
- }
- let mut c = self.clone();
- c.markers = o.markers.clone();
- for (a, b) in c.layers.iter_mut().zip(&o.layers) {
- a.markers = b.markers.clone();
- a.markers_locked = b.markers_locked;
- }
- c.same_pixels(o)
- }
-
- /// The comp with those switches and the Resolution at their defaults (borrowed when they
- /// already are), for keys that hash the whole comp.
- pub fn pixel_form(&self) -> std::borrow::Cow<'_, Comp> {
- if !self.hide_shy && self.resolution.is_auto() && self.layers.iter().all(|l| l.switches == l.switches.pixels()) {
- return std::borrow::Cow::Borrowed(self);
- }
- let mut c = self.clone();
- c.hide_shy = false;
- c.resolution = Resolution::Auto;
- for l in &mut c.layers {
- l.switches = l.switches.pixels();
- }
- std::borrow::Cow::Owned(c)
- }
- }
-
- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
- pub enum MatteKind {
- #[default]
- Alpha,
- AlphaInverted,
- Luma,
- LumaInverted,
- }
-
- impl MatteKind {
- pub const ALL: [MatteKind; 4] = [MatteKind::Alpha, MatteKind::AlphaInverted, MatteKind::Luma, MatteKind::LumaInverted];
- pub fn label(self) -> &'static str {
- match self {
- MatteKind::Alpha => "Alpha Matte",
- MatteKind::AlphaInverted => "Alpha Inverted Matte",
- MatteKind::Luma => "Luma Matte",
- MatteKind::LumaInverted => "Luma Inverted Matte",
- }
- }
- }
-
- #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
- pub struct TrackMatte {
- pub layer: LayerId,
- pub kind: MatteKind,
- }
-
- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
- pub enum AutoOrient {
- #[default]
- Off,
- AlongPath,
- TowardsCamera,
- TowardsPointOfInterest,
- }
-
- #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
- pub struct Layer {
- pub id: LayerId,
- pub name: String,
- pub source: LayerSource,
- pub label: Label,
- #[serde(default)]
- pub comment: String,
- /// Comp time where the layer's time 0 sits.
- pub start_time: Tick,
- /// Visible span in comp time.
- pub in_point: Tick,
- pub out_point: Tick,
- /// Time stretch in percent (100 = normal, negative = reversed).
- pub stretch: f64,
- pub switches: Switches,
- pub blend_mode: BlendMode,
- #[serde(default)]
- pub preserve_transparency: bool,
- #[serde(default)]
- pub track_matte: Option<TrackMatte>,
- #[serde(default)]
- pub parent: Option<LayerId>,
- #[serde(default)]
- pub markers: Vec<Marker>,
- /// Layer ▸ Markers ▸ Lock Markers.
- #[serde(default, skip_serializing_if = "std::ops::Not::not")]
- pub markers_locked: bool,
- #[serde(default)]
- pub auto_orient: AutoOrient,
- /// Layer ▸ Environment Layer: the layer is the environment (image-based light and
- /// reflections) of Advanced 3D comps instead of being drawn.
- #[serde(default, skip_serializing_if = "std::ops::Not::not")]
- pub environment: bool,
- /// Layer ▸ Light ▸ Create Environment Light Background Layer: the layer's (equirectangular)
- /// image is drawn as the 3D scene's backdrop, seen through the camera, instead of as a card.
- #[serde(default, skip_serializing_if = "std::ops::Not::not")]
- pub environment_background: bool,
- /// The property tree (Masks, Effects, Transform, Text, Contents, Camera/Light options…).
- pub props: PropGroup,
- }
-
- impl Layer {
- pub fn is_active_at(&self, t: Tick) -> bool {
- t >= self.in_point && t < self.out_point
- }
- /// Layer time for a comp time (stretch-aware).
- pub fn layer_time(&self, comp_t: Tick) -> Tick {
- let d = comp_t - self.start_time;
- if (self.stretch - 100.0).abs() < 1e-9 { d } else { Tick((d.0 as f64 * 100.0 / self.stretch) as i64) }
- }
- /// Comp time for a layer time.
- pub fn comp_time(&self, layer_t: Tick) -> Tick {
- if (self.stretch - 100.0).abs() < 1e-9 { self.start_time + layer_t } else { self.start_time + Tick((layer_t.0 as f64 * self.stretch / 100.0) as i64) }
- }
- pub fn transform(&self) -> Option<&PropGroup> {
- self.props.sub("transform")
- }
- pub fn transform_mut(&mut self) -> Option<&mut PropGroup> {
- self.props.sub_mut("transform")
- }
- pub fn effects(&self) -> Option<&PropGroup> {
- self.props.sub("effects")
- }
- pub fn masks(&self) -> Option<&PropGroup> {
- self.props.sub("masks")
- }
- pub fn is_camera(&self) -> bool {
- matches!(self.source, LayerSource::Camera)
- }
- pub fn is_light(&self) -> bool {
- matches!(self.source, LayerSource::Light { .. })
- }
- /// The layer participates in 3D (3D switch, or cameras/lights which are always 3D).
- pub fn is_3d(&self) -> bool {
- self.switches.three_d || self.is_camera() || self.is_light()
- }
- pub fn has_video(&self) -> bool {
- self.source.is_av() && self.switches.video
- }
- }
-
- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
- pub enum FootageKind {
- #[default]
- Video,
- Still,
- Sequence,
- Audio,
- /// A 3D model (glTF 2.0 / OBJ), placed as a model layer.
- Model,
- /// A data file (JSON, CSV, TSV) for data-driven animation: read by expressions through
- /// `footage(name).sourceData` / `sourceText` / `dataValue`; it has no pixels.
- Data,
- }
-
- /// Interpret Footage ▸ Fields and Pulldown ▸ Separate Fields.
- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
- pub enum FieldOrder {
- /// Progressive frames.
- #[default]
- Off,
- /// Interlaced, upper (odd) field first: each field becomes a frame at twice the rate.
- UpperFirst,
- LowerFirst,
- }
-
- impl FieldOrder {
- pub fn label(self) -> &'static str {
- match self {
- FieldOrder::Off => "Off",
- FieldOrder::UpperFirst => "Upper Field First",
- FieldOrder::LowerFirst => "Lower Field First",
- }
- }
- pub fn parse(s: &str) -> Option<FieldOrder> {
- match s.to_ascii_lowercase().replace([' ', '_', '-'], "").as_str() {
- "off" | "none" | "progressive" => Some(FieldOrder::Off),
- "upper" | "upperfirst" | "upperfieldfirst" => Some(FieldOrder::UpperFirst),
- "lower" | "lowerfirst" | "lowerfieldfirst" => Some(FieldOrder::LowerFirst),
- _ => None,
- }
- }
- }
-
- /// File extensions of the movie containers footage is imported from (FilmCraft reads them). The
- /// import and proxy file dialogs, the Media Browser and `effectcraft_media::is_importable` all go
- /// by this list.
- pub const VIDEO_EXTENSIONS: &[&str] = &["mp4", "m4v", "mov", "mkv", "webm", "mxf", "avi"];
-
- #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
- pub enum AlphaMode {
- #[default]
- Straight,
- Premultiplied,
- Ignore,
- }
-
- #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
- pub struct Footage {
- pub path: String,
- pub kind: FootageKind,
- pub width: u32,
- pub height: u32,
- pub pixel_aspect: f64,
- pub frame_rate: FrameRate,
- /// Native rate before "Conform to frame rate".
- #[serde(default)]
- pub native_rate: Option<FrameRate>,
- pub duration: Tick,
- pub has_video: bool,
- pub has_audio: bool,
- pub alpha: AlphaMode,
- #[serde(default)]
- pub premul_color: [f32; 3],
- #[serde(default = "one")]
- pub loop_count: u32,
- #[serde(default)]
- pub codec: String,
- #[serde(default)]
- pub missing: bool,
- /// Image sequence files (when kind = Sequence).
- #[serde(default, skip_serializing_if = "Vec::is_empty")]
- pub sequence: Vec<String>,
- /// Colour profile (from the file's metadata, or Interpret Footage). `None` = sRGB.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub color_profile: Option<ColorSpace>,
- /// One layer of a layered file (Photoshop) instead of its merged image.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub layer: Option<SourceLayer>,
- /// Interpret Footage ▸ Fields and Pulldown ▸ Separate Fields.
- #[serde(default, skip_serializing_if = "is_default")]
- pub fields: FieldOrder,
- /// Interpret Footage ▸ Alpha ▸ Invert Alpha.
- #[serde(default, skip_serializing_if = "std::ops::Not::not")]
- pub invert_alpha: bool,
- /// Interpret Footage ▸ Color ▸ Interpret As Linear Light: the file's values are linear.
- #[serde(default, skip_serializing_if = "std::ops::Not::not")]
- pub linear_light: bool,
- /// Interpret Footage ▸ Color ▸ Preserve RGB: the file's values enter the composition
- /// unconverted. Float footage (OpenEXR, float TIFF) is not sRGB-encoded on decode, and the
- /// colour profile, Interpret As Linear Light and the working space don't apply.
- #[serde(default, skip_serializing_if = "std::ops::Not::not")]
- pub preserve_rgb: bool,
- /// Data footage ([`FootageKind::Data`]): the file's text (JSON, CSV or TSV), kept in the
- /// project so expressions read it everywhere (and on the web).
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub data: Option<String>,
- /// PDF / Illustrator footage: the page shown (0-based; File ▸ Import ▸ Page).
- #[serde(default, skip_serializing_if = "is_default")]
- pub page: u32,
- /// Image sequences imported with Force Alphabetical Order: the files play one after another
- /// and their numbering doesn't count (otherwise a gap in it shows a placeholder, as in After
- /// Effects; [`sequence`]).
- #[serde(default, skip_serializing_if = "std::ops::Not::not")]
- pub alphabetical: bool,
- /// Interpret Footage ▸ Start Timecode ▸ Override Start: the frame (at the footage's frame
- /// rate) its timecode shows at its first frame. `None` = Use Source File Timecode (0: file
- /// timecode isn't read). It only relabels source time, as in After Effects.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub start_timecode: Option<i64>,
- }
-
- fn is_default<T: Default + PartialEq>(v: &T) -> bool {
- *v == T::default()
- }
-
- impl Default for Footage {
- fn default() -> Self {
- Footage {
- path: String::new(),
- kind: FootageKind::Still,
- width: 0,
- height: 0,
- pixel_aspect: 1.0,
- frame_rate: FrameRate::FPS_30,
- native_rate: None,
- duration: Tick::ZERO,
- has_video: false,
- has_audio: false,
- alpha: AlphaMode::Straight,
- premul_color: [0.0; 3],
- loop_count: 1,
- codec: String::new(),
- missing: false,
- sequence: vec![],
- color_profile: None,
- fields: FieldOrder::Off,
- invert_alpha: false,
- linear_light: false,
- preserve_rgb: false,
- data: None,
- layer: None,
- page: 0,
- alphabetical: false,
- start_timecode: None,
- }
- }
- }
-
- impl Footage {
- /// Interpret As Linear Light applies (Preserve RGB passes the file's values through).
- pub fn linear_light_applies(&self) -> bool {
- self.linear_light && !self.preserve_rgb
- }
-
- /// How long the footage plays: its duration times Interpret Footage ▸ Loop.
- pub fn looped_duration(&self) -> Tick {
- Tick(self.duration.0.saturating_mul(self.loop_count.max(1) as i64))
- }
-
- /// Source time as the footage's timecode: its frame `frame` from Start Timecode
- /// (`0:00:41:20`), as the Footage panel shows it.
- pub fn timecode(&self, frame: i64) -> String {
- effectcraft_time::format_timecode_ae(frame.saturating_add(self.start_timecode.unwrap_or(0)), self.frame_rate, false)
- }
-
- /// The data format of data footage: `json`, `csv` or `tsv` (from the file extension).
- pub fn data_format(&self) -> Option<&'static str> {
- if self.kind != FootageKind::Data {
- return None;
- }
- let ext = std::path::Path::new(&self.path).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
- Some(match ext.as_str() {
- "csv" => "csv",
- "tsv" | "tab" => "tsv",
- _ => "json",
- })
- }
- }
-
- /// A proxy: a stand-in file used instead of a footage item or composition (File ▸ Set Proxy /
- /// Create Proxy), when its Use Proxy switch is on and the render's Proxy Use allows it.
- #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
- pub struct Proxy {
- /// The proxy's footage (path, size, rate…; File ▸ Interpret Footage ▸ Proxy edits it).
- pub footage: Footage,
- /// Use Proxy (the Project panel's proxy indicator: filled = in use, hollow = set but off).
- #[serde(default = "yes")]
- pub enabled: bool,
- }
-
- /// A layer of a layered still (a Photoshop document, or a PDF / Illustrator / EPS file) used as
- /// footage (File ▸ Import ▸ Composition / Composition – Retain Layer Sizes, or Choose Layer).
- #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
- pub struct SourceLayer {
- /// Layer record index in the file (bottom of the stack = 0).
- pub index: u32,
- pub name: String,
- /// The footage is the layer's own bounds (Retain Layer Sizes) rather than the document size.
- #[serde(default)]
- pub layer_size: bool,
- /// A Photoshop smart object: the unique id of its embedded file (linked layer data), which
- /// is the footage instead of the layer's pixels.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub embedded: Option<String>,
- /// A smart object with a perspective quad or a warp: the footage is its embedded file baked
- /// as placed (warped and pinned to its corners) over the placed bounds in document space.
- #[serde(default, skip_serializing_if = "std::ops::Not::not")]
- pub placed: bool,
- }
-
- fn one() -> u32 {
- 1
- }
-
- #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
- pub struct Solid {
- pub color: [f32; 3],
- pub width: u32,
- pub height: u32,
- pub pixel_aspect: f64,
- }
-
- #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
- #[serde(tag = "type")]
- #[allow(clippy::large_enum_variant)]
- pub enum ItemKind {
- Folder,
- Comp(Arc<Comp>),
- Footage(Footage),
- Solid(Solid),
- }
-
- #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
- pub struct Item {
- pub id: ItemId,
- pub name: String,
- pub label: Label,
- #[serde(default)]
- pub comment: String,
- /// Containing folder (None = project root).
- #[serde(default)]
- pub parent: Option<ItemId>,
- pub kind: ItemKind,
- /// The item's proxy (footage and compositions).
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub proxy: Option<Box<Proxy>>,
- }
-
- impl Item {
- pub fn type_name(&self) -> &'static str {
- match &self.kind {
- ItemKind::Folder => "Folder",
- ItemKind::Comp(_) => "Composition",
- ItemKind::Footage(f) => match f.kind {
- FootageKind::Video => "Video",
- FootageKind::Still => "Image",
- FootageKind::Sequence => "Image Sequence",
- FootageKind::Audio => "Audio",
- FootageKind::Model => "3D Model",
- FootageKind::Data => "Data",
- },
- ItemKind::Solid(_) => "Solid",
- }
- }
- pub fn as_comp(&self) -> Option<&Comp> {
- if let ItemKind::Comp(c) = &self.kind { Some(c) } else { None }
- }
- pub fn is_folder(&self) -> bool {
- matches!(self.kind, ItemKind::Folder)
- }
- /// (width, height) for visual items.
- pub fn dimensions(&self) -> Option<(u32, u32)> {
- match &self.kind {
- ItemKind::Comp(c) => Some((c.width, c.height)),
- ItemKind::Footage(f) if f.has_video => Some((f.width, f.height)),
- ItemKind::Solid(s) => Some((s.width, s.height)),
- _ => None,
- }
- }
- pub fn duration(&self) -> Option<Tick> {
- match &self.kind {
- ItemKind::Comp(c) => Some(c.duration),
- ItemKind::Footage(f) if f.kind != FootageKind::Still => Some(f.looped_duration()),
- _ => None,
- }
- }
- pub fn frame_rate(&self) -> Option<FrameRate> {
- match &self.kind {
- ItemKind::Comp(c) => Some(c.frame_rate),
- ItemKind::Footage(f) if f.kind == FootageKind::Video || f.kind == FootageKind::Sequence => Some(f.frame_rate),
- _ => None,
- }
- }
- }
+ mod comp;
+ mod footage;
+ mod item;
+ mod layer;
+ mod settings;
+
+ pub use comp::{Comp, Guide, Renderer, Resolution};
-pub use footage::{AlphaMode, FieldOrder, Footage, FootageKind, Proxy, Solid, SourceLayer};
++pub use footage::{AlphaMode, FieldOrder, Footage, FootageKind, Proxy, Solid, SourceLayer, VIDEO_EXTENSIONS};
+ pub use item::{Item, ItemId, ItemKind, LayerId};
+ pub use layer::{AutoOrient, FrameBlend, Layer, LayerSource, LightKind, MatteKind, PrimitiveKind, Quality, Sampling, Switches, TrackMatte};
+ pub use settings::{
+ APP_VERSION, BitDepth, ColorEngine, CuePoint, HdrMode, Marker, ProjectError, ProjectSettings, SCHEMA_EFFECT_SPACE, SCHEMA_VERSION, SavedView,
+ TimeDisplayStyle, is_newer_version, saved_by, saved_view,
+ };
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Project {
diff --cc crates/render/src/footage.rs
index 000000000,e58ef2a57..0b4b798b8
mode 000000,100644..100644
--- a/crates/render/src/footage.rs
+++ b/crates/render/src/footage.rs
@@@ -1,0 -1,178 +1,190 @@@
+ use super::*;
+
+ /// How a [`FootageSource`] hands over float footage (OpenEXR, float TIFF), whose values are
+ /// linear light: encoded with a curve, as the compositor takes footage, or as stored. Other
+ /// footage is decoded the same way whatever it says. Interpret Footage ▸ Preserve RGB always
+ /// reads the values as stored.
+ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
+ pub enum FloatCurve {
+ /// The sRGB curve (managed projects, and Working Gamma 2.2).
+ #[default]
+ Srgb,
+ /// A pure 2.4 power curve (no working space, Working Gamma 2.4).
+ Gamma24,
+ /// The linear values as stored (Interpret As Linear Light encodes them afterwards).
+ Linear,
+ }
+
+ /// Supplies decoded footage frames (implemented by the media layer).
+ pub trait FootageSource: Send + Sync {
+ /// The frame of `item` at source time `t`, straight from the file (any size).
+ fn frame(&self, item: ItemId, footage: &Footage, t: Tick) -> Option<Arc<Image>>;
+ /// [`FootageSource::frame`] for a render that shows it at `width` × `height`, at most half its
+ /// size: either that frame or, when the source can make it more cheaply than the whole frame
+ /// (movies, see `effectcraft-media`), the frame already resampled to that size as
+ /// [`effectcraft_raster::resample`] would.
+ fn frame_at_size(&self, item: ItemId, footage: &Footage, t: Tick, _width: u32, _height: u32) -> Option<Arc<Image>> {
+ self.frame(item, footage, t)
+ }
+ /// [`FootageSource::frame`] (`size: None`) or [`FootageSource::frame_at_size`] with float
+ /// footage handed over as `float` says ([`FootageSource::frame`] uses [`FloatCurve::Srgb`]).
+ /// Sources without float footage can leave the default, which ignores `float`.
+ fn frame_with(&self, item: ItemId, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve) -> Option<Arc<Image>> {
+ let _ = float;
+ match size {
+ Some((w, h)) => self.frame_at_size(item, footage, t, w, h),
+ None => self.frame(item, footage, t),
+ }
+ }
+ /// `frames` interleaved stereo sample frames of `item`'s audio from source time `t` at
+ /// `rate` Hz (`None` when unavailable). The first sample is `t.to_units_floor(rate)`;
+ /// a sample boundary uses the earliest representable tick that selects that sample.
+ fn audio(&self, _item: ItemId, _footage: &Footage, _t: Tick, _frames: usize, _rate: u32) -> Option<Vec<f32>> {
+ None
+ }
+ /// Auxiliary 3D channels of `item` at source time `t` (multi-layer OpenEXR: depth, IDs,
+ /// Cryptomatte, any named channel), with `scale` relative to the file's pixels. `None` when
+ /// the footage has none.
+ fn aux(&self, _item: ItemId, _footage: &Footage, _t: Tick) -> Option<Arc<effectcraft_raster::AuxChannels>> {
+ None
+ }
+ /// The parsed 3D model of a [`effectcraft_project::FootageKind::Model`] item (Advanced 3D).
+ fn model(&self, _item: ItemId, _footage: &Footage) -> Option<Arc<effectcraft_model::Model>> {
+ None
+ }
+ /// Set the decoded-frame cache budget in bytes (Settings ▸ Memory & CPU); sources without
+ /// a cache ignore it.
+ fn set_cache_budget(&self, _bytes: usize) {}
+ /// Drop the decoded frames it keeps (Edit ▸ Purge ▸ All Memory / Image Cache Memory): the
+ /// next reads decode again. Sources without a cache ignore it.
+ fn purge(&self) {}
+ /// The file at `path` changed on disk (Reload Footage): drop what it keeps of it (decoded
+ /// frames, open decoders, parsed models), so the next reads see the new contents. Sources
+ /// without a cache ignore it.
+ fn forget(&self, _path: &str) {}
+ /// Settings ▸ Disk ▸ Conformed Audio Folder: where decoded audio is kept between reads
+ /// (`None` = off); sources that don't decode audio ignore it.
+ fn set_conform_folder(&self, _folder: Option<std::path::PathBuf>) {}
+ /// The decoded-frame cache budget in bytes, if the source has a cache.
+ fn cache_budget(&self) -> Option<usize> {
+ None
+ }
+ /// Vector footage (SVG) rasterised at `scale` × its pixel size, for Continuously Rasterize.
+ /// `None` when the footage is not vector or cannot be read.
+ fn vector_frame(&self, _item: ItemId, _footage: &Footage, _scale: f64) -> Option<Arc<Image>> {
+ None
+ }
+ /// Run `f`, which reads frames from this source, as work that can be called off: once
+ /// `cancel` is set, long decodes it starts (a movie seeking back to a keyframe and decoding
+ /// forward) stop early and their frames come back `None`. Sources that can't stop a decode
+ /// just run `f`. See [`CancellableFootage`].
+ fn cancellable(&self, _cancel: &Arc<AtomicBool>, f: &mut dyn FnMut()) {
+ f()
+ }
+ /// Reads through this source have been called off: frames may have come back `None` that
+ /// exist, so what was made from them must not be kept.
+ fn called_off(&self) -> bool {
+ false
+ }
+ /// Why `footage` shows no picture although its file is there: a read of it failed because
+ /// no decoder handles its codec, profile, chroma format or bit depth, or the stream is damaged
+ /// (e.g. "H.264 (High 4:2:2) isn't supported by the built-in decoder: ..."). `None` while it
+ /// decodes, and for sources that don't track failures. Stays set until the file is forgotten.
+ fn problem(&self, _footage: &Footage) -> Option<String> {
+ None
+ }
++ /// [`Self::problem`] of what `item` shows: its proxy's while Use Proxy shows the proxy
++ /// instead (the reason then says it is the proxy's), else the footage item's own. A
++ /// composition has one only through its proxy.
++ fn item_problem(&self, item: &effectcraft_project::Item) -> Option<String> {
++ match item.proxy.as_deref().filter(|px| px.enabled && px.footage.has_video) {
++ Some(px) => self.problem(&px.footage).map(|why| format!("Proxy: {why}")),
++ None => match &item.kind {
++ ItemKind::Footage(f) => self.problem(f),
++ _ => None,
++ },
++ }
++ }
+ }
+
+ /// A render's view of a [`FootageSource`] whose frame reads can be called off with `cancel`
+ /// (a viewer frame nobody waits for any more, #329). Every read goes through
+ /// [`FootageSource::cancellable`] on its own, so reads made for this render on another thread
+ /// (a parallel loop) answer to this render's flag, and reads for other renders never do.
+ pub struct CancellableFootage<'a> {
+ pub inner: &'a dyn FootageSource,
+ pub cancel: Arc<AtomicBool>,
+ }
+
+ impl CancellableFootage<'_> {
+ fn read<R>(&self, f: impl FnOnce() -> Option<R>) -> Option<R> {
+ if self.cancel.load(Ordering::Relaxed) {
+ return None;
+ }
+ let (mut f, mut out) = (Some(f), None);
+ self.inner.cancellable(&self.cancel, &mut || out = f.take().and_then(|f| f()));
+ out
+ }
+ }
+
+ impl FootageSource for CancellableFootage<'_> {
+ fn frame(&self, item: ItemId, footage: &Footage, t: Tick) -> Option<Arc<Image>> {
+ self.read(|| self.inner.frame(item, footage, t))
+ }
+ fn frame_at_size(&self, item: ItemId, footage: &Footage, t: Tick, width: u32, height: u32) -> Option<Arc<Image>> {
+ self.read(|| self.inner.frame_at_size(item, footage, t, width, height))
+ }
+ fn audio(&self, item: ItemId, footage: &Footage, t: Tick, frames: usize, rate: u32) -> Option<Vec<f32>> {
+ self.inner.audio(item, footage, t, frames, rate)
+ }
+ fn aux(&self, item: ItemId, footage: &Footage, t: Tick) -> Option<Arc<effectcraft_raster::AuxChannels>> {
+ self.inner.aux(item, footage, t)
+ }
+ fn model(&self, item: ItemId, footage: &Footage) -> Option<Arc<effectcraft_model::Model>> {
+ self.inner.model(item, footage)
+ }
+ fn set_cache_budget(&self, bytes: usize) {
+ self.inner.set_cache_budget(bytes)
+ }
+ fn purge(&self) {
+ self.inner.purge()
+ }
+ fn forget(&self, path: &str) {
+ self.inner.forget(path)
+ }
+ fn set_conform_folder(&self, folder: Option<std::path::PathBuf>) {
+ self.inner.set_conform_folder(folder)
+ }
+ fn cache_budget(&self) -> Option<usize> {
+ self.inner.cache_budget()
+ }
+ fn vector_frame(&self, item: ItemId, footage: &Footage, scale: f64) -> Option<Arc<Image>> {
+ self.inner.vector_frame(item, footage, scale)
+ }
+ fn cancellable(&self, cancel: &Arc<AtomicBool>, f: &mut dyn FnMut()) {
+ self.inner.cancellable(cancel, f)
+ }
+ fn called_off(&self) -> bool {
+ self.cancel.load(Ordering::Relaxed) || self.inner.called_off()
+ }
+ fn problem(&self, footage: &Footage) -> Option<String> {
+ self.inner.problem(footage)
+ }
+ fn frame_with(&self, item: ItemId, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve) -> Option<Arc<Image>> {
+ self.read(|| self.inner.frame_with(item, footage, t, size, float))
+ }
+ }
+
+ /// Footage that can be rasterised at any scale (SVG).
+ pub fn is_vector_footage(f: &Footage) -> bool {
+ matches!(f.codec.as_str(), "SVG" | "PDF" | "AI" | "EPS")
+ }
+
+ /// No footage available (renders footage layers as transparent).
+ pub struct NoFootage;
+
+ impl FootageSource for NoFootage {
+ fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option<Arc<Image>> {
+ None
+ }
+ }
diff --cc crates/ui-egui/src/menus/frontend.rs
index 000000000,d808b4620..934150d76
mode 000000,100644..100644
--- a/crates/ui-egui/src/menus/frontend.rs
+++ b/crates/ui-egui/src/menus/frontend.rs
@@@ -1,0 -1,684 +1,691 @@@
+ use super::*;
+
+ /// Run an engine command and perform the frontend events it emitted right away.
+ /// Commands that fill the internal clipboard.
+ const COPY_COMMANDS: &[&str] =
+ &["edit.copy", "edit.cut", "edit.copyWithPropertyLinks", "edit.copyWithRelativePropertyLinks", "edit.copyExpressionOnly", "keys.copy", "effect.copy"];
+
+ /// A line for the system clipboard naming what EffectCraft copied. The system clipboard must
+ /// hold something: with nothing on it, the windowing layer sends no paste event for Ctrl+V.
+ fn clipboard_note(s: &effectcraft_engine::Session) -> String {
+ let st = &s.state;
+ let n = |n: usize, one: &str, many: &str| format!("EffectCraft: {n} {}", if n == 1 { one } else { many });
+ if st.clip_is_keys && !st.key_clipboard.is_empty() {
+ n(st.key_clipboard.iter().map(|c| c.keys.len()).sum(), "keyframe", "keyframes")
+ } else if !st.effect_clipboard.is_empty() {
+ n(st.effect_clipboard.len(), "effect", "effects")
+ } else if !st.contents_clipboard.is_empty() {
+ n(st.contents_clipboard.len(), "shape item", "shape items")
+ } else if st.link_clipboard.is_some() {
+ "EffectCraft: property links".into()
+ } else {
+ n(st.clipboard.len(), "layer", "layers")
+ }
+ }
+
+ pub(crate) fn run_engine(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result<Value, String> {
+ // Events already queued belong to earlier invocations (`engine.execute` defers them).
+ let queued = app.session.events.len();
+ let mut r = app.session.execute(id, params).map_err(|e| e.to_string());
+ if let Err(e) = &r {
+ app.ui.status = e.clone();
+ } else if COPY_COMMANDS.contains(&id) && app.session.state.text_edit.is_none() {
+ ctx.copy_text(clipboard_note(&app.session));
+ }
+ let events = app.session.drain_events();
+ for (index, ev) in events.into_iter().enumerate() {
+ match ev {
+ effectcraft_engine::Event::Frontend { command, params } => {
+ if let Err(e) = frontend(app, ctx, &command, params) {
+ app.ui.status = e.clone();
+ // A frontend-only command's own failure is the command's result (#696: a
+ // workspace save that didn't reach disk reported success). An earlier
+ // invocation's failure only sets the status.
+ if index >= queued && command == id && r.is_ok() {
+ r = Err(e);
+ }
+ }
+ }
+ other => app.session.events.push(other),
+ }
+ }
+ r
+ }
+
+ fn toggle(slot: &mut bool, p: &Value) -> Value {
+ *slot = p.get("value").and_then(Value::as_bool).unwrap_or(!*slot);
+ json!(*slot)
+ }
+
+ /// Perform a frontend command (from `Event::Frontend`).
+ pub fn frontend(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, p: Value) -> Result<Value, String> {
+ let now = app.now();
+ let v = &mut app.ui.viewer;
+ Ok(match id {
+ "mediaBrowser.copySourcePath" => {
+ let path = p.get("path").and_then(Value::as_str).filter(|path| !path.is_empty()).ok_or("A source path is required")?;
+ ctx.copy_text(path.to_string());
+ json!({"path": path})
+ }
+ "effects.copyPresetsFolderPath" => {
+ if cfg!(target_arch = "wasm32") {
+ return Err("The web app has no local presets folder".into());
+ }
+ let path = crate::panels::effects_presets::presets_dir().filter(|path| !path.as_os_str().is_empty()).ok_or("No presets folder is configured")?;
+ let path = std::path::absolute(path).map_err(|e| format!("Cannot resolve the presets folder path: {e}"))?;
+ let path = path.to_str().ok_or("The presets folder path is not valid UTF-8")?;
+ ctx.copy_text(path.to_string());
+ json!({"path": path})
+ }
+ "app.checkForUpdates" | "help.checkForUpdates" => {
+ crate::updates_ui::check(app);
+ Value::Null
+ }
+ "app.about" => {
+ app.dialog = Some(crate::Dialog::About);
+ Value::Null
+ }
+ // Window ▸ <ScriptUI panel>: dock (or bring forward) the panel the script built.
+ // Audio scrubbing: one frame of audio at `time` (default the current time).
+ "playback.scrubAudio" => {
+ let cid = app.session.active_comp_id().ok_or("no composition")?;
+ let t = p.get("time").and_then(Value::as_f64).map_or(app.session.time(), effectcraft_engine::time::Tick::from_seconds_f64);
+ app.scrub_audio(cid, t, now);
+ json!({"playing": app.scrub.is_some()})
+ }
+ // View ▸ New Viewer.
+ "view.newViewer" => json!({"viewer": crate::panels::viewers::new_viewer(app)}),
+ // Reveal Layer Source / Reveal Composition: show the Project panel on the item, opening
+ // its folders and clearing the search so the row is visible.
+ "project.reveal" => {
+ let ids: Vec<effectcraft_engine::project::ItemId> = p
+ .get("items")
+ .and_then(Value::as_array)
+ .map(|items| items.iter().filter_map(Value::as_u64).map(effectcraft_engine::project::ItemId).collect())
+ .or_else(|| p.get("item").and_then(Value::as_u64).map(|item| vec![effectcraft_engine::project::ItemId(item)]))
+ .unwrap_or_default();
+ crate::panels::project::reveal(app, ctx, &ids);
+ json!({"items": ids.iter().map(|item| item.0).collect::<Vec<_>>()})
+ }
+ // Run by id (control channel, MCP): the Project panel's selection, whatever has focus.
+ "project.deleteWithoutConfirmation" => crate::panels::delete_items::delete_confirmed(app, ctx, json!({}))?,
+ // A gradient property's "Edit Gradient…" (the Timeline's value): the Gradient Editor.
+ "prop.editGradient" => crate::panels::gradient_editor::open(app, &p)?,
+ "window.scriptPanel" => {
+ let id = p.get("window").and_then(Value::as_u64).ok_or("no ScriptUI panel window")? as u32;
+ app.show_panel(PanelKind::ScriptPanel(id));
+ json!({"window": id})
+ }
+ "layer.style.options" => {
+ crate::panels::layer_styles_dialog::open(app, &p)?;
+ Value::Null
+ }
+ "app.settings" => {
+ let page = p.get("page").and_then(Value::as_str).unwrap_or("general");
+ crate::panels::settings::open(app, effectcraft_engine::prefs::page_id(page).unwrap_or("general"));
+ Value::Null
+ }
+ "app.gpuInfo" => {
+ crate::panels::dialogs::info(
+ app,
+ "GPU Information",
+ &format!(
+ "{}Layer cache: {} MB • Preview cache: {} MB.",
+ effectcraft_engine::sysinfo::gpu_summary(&app.session),
+ app.session.layer_cache.budget() >> 20,
+ app.frames.budget() >> 20
+ ),
+ );
+ Value::Null
+ }
+ "app.hide" | "app.hideOthers" | "app.showAll" => {
+ // The desktop app asks macOS (NSApplication hide / hideOtherApplications /
+ // unhideAllApplications); elsewhere Hide minimizes and the others don't apply.
+ if app.hooks.app_action.as_ref().is_some_and(|f| f(id)) {
+ return Ok(Value::Null);
+ }
+ match id {
+ "app.hide" => ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(true)),
+ _ => return Err(format!("`{id}` is only available on macOS")),
+ }
+ Value::Null
+ }
+ "app.quit" => {
+ ctx.send_viewport_cmd(egui::ViewportCommand::Close);
+ Value::Null
+ }
+ "app.commandPalette" => {
+ app.dialog_state.palette_query = p.get("query").and_then(Value::as_str).unwrap_or_default().to_string();
+ app.dialog_state.palette_sel = 0;
+ app.dialog = Some(crate::Dialog::CommandPalette);
+ Value::Null
+ }
+ "app.keyboardShortcuts" => {
+ crate::panels::shortcut_editor::open(app);
+ Value::Null
+ }
+ "app.templates" => {
+ let kind = p.get("kind").and_then(Value::as_str).unwrap_or("renderSettings");
+ crate::panels::rq_templates::open(app, ctx, kind);
+ Value::Null
+ }
+ "renderQueue.notify" => {
+ // Render finished with Notify on: a toast, the dock/taskbar attention request, and the
+ // host's system sound (the desktop app handles `renderQueue.notify`).
+ let msg = p.get("message").and_then(Value::as_str).unwrap_or("Render finished").to_string();
+ app.toast = Some((msg, now));
+ ctx.send_viewport_cmd(egui::ViewportCommand::RequestUserAttention(egui::UserAttentionType::Informational));
+ if let Some(f) = app.hooks.app_action.as_ref() {
+ f("renderQueue.notify");
+ }
+ Value::Null
+ }
+ "app.find" => {
+ if let Some(q) = p.get("query").and_then(Value::as_str) {
+ app.ui.project_search = q.to_string();
+ }
+ app.show_panel(PanelKind::Project);
+ Value::Null
+ }
+ "playback.toggle" => {
+ // The play button and Spacebar: `{shortcut?}` picks which Preview panel shortcut's
+ // options to play with (default Spacebar).
+ let sc = match p.get("shortcut").and_then(Value::as_str) {
+ Some(k) => effectcraft_engine::preview::PreviewShortcut::parse(k).ok_or_else(|| format!("unknown preview shortcut `{k}`"))?,
+ None => effectcraft_engine::preview::PreviewShortcut::Spacebar,
+ };
+ app.toggle_play_with(now, sc);
+ json!({"playing": app.playback.playing, "shortcut": sc.id()})
+ }
+ "playback.cacheWhenIdle" => {
+ let r = toggle(&mut app.ui.cache_when_idle, &p);
+ app.set_pref("previews.cacheFramesWhenIdle", r.clone())?;
+ r
+ }
+ "playback.audio" => {
+ // Include Audio of the shortcut shown in the Preview panel.
+ let mut on = app.session.prefs.preview.active().include_audio;
+ let r = toggle(&mut on, &p);
+ app.session.execute("playback.settings.set", json!({"includeAudio": on})).map_err(|e| e.to_string())?;
+ if !on {
+ app.audio = None;
+ }
+ r
+ }
+ // Zoom In / Zoom Out act on the focused viewer: the Layer panel when it has focus, else
+ // the Composition viewer.
+ "view.zoomIn" | "view.zoomOut" if app.ui.focused == PanelKind::Layer => {
+ let cur = app.ui.layer_zoom.unwrap_or_else(|| crate::panels::layer_panel::last_fit(ctx));
+ // The Layer panel zooms in points (pixels-per-point 1).
+ let next = zoom_step(cur, 1.0, id == "view.zoomIn");
+ app.ui.layer_zoom = Some(next);
+ json!({"zoom": next, "panel": "layer"})
+ }
+ "view.zoomIn" | "view.zoomOut" => {
+ let ppp = ctx.pixels_per_point();
+ let cur = v.zoom.unwrap_or_else(|| crate::panels::viewer::last_fit(ctx));
+ let next = zoom_step(cur, ppp, id == "view.zoomIn");
+ v.zoom = Some(next);
+ json!({"zoom": next})
+ }
+ // View ▸ Resolution ▸ Custom without a factor (the engine sets the comp's resolution).
+ "view.res.custom" => {
+ let cur = match app.viewer_res() {
+ Resolution::Custom(n) => f64::from(n),
+ _ => 2.0,
+ };
+ crate::panels::dialogs::form(
+ app,
+ "Custom Resolution",
+ "view.res.custom",
+ json!({}),
+ vec![crate::panels::dialogs::Field::num("factor", "Render every n-th pixel", cur)],
+ );
+ Value::Null
+ }
+ "view.rulers" => toggle(&mut v.rulers, &p),
+ "view.guides" => toggle(&mut v.guides, &p),
+ "view.snapToGuides" => toggle(&mut v.snap_guides, &p),
+ "view.lockGuides" => toggle(&mut v.lock_guides, &p),
+ "view.grid" => toggle(&mut v.grid, &p),
+ "view.snapToGrid" => toggle(&mut v.snap_grid, &p),
+ "view.layerControls" => toggle(&mut v.show_layer_controls, &p),
+ "view.options" => {
+ app.dialog = Some(crate::Dialog::ViewOptions);
+ Value::Null
+ }
+ "view.panelBackground" => {
+ if p.get("pick").and_then(Value::as_bool) == Some(true) {
+ let [r, g, b] = v.custom_pasteboard;
+ crate::panels::dialogs::form(
+ app,
+ "Panel Background Color",
+ "view.panelBackground",
+ json!({}),
+ vec![crate::panels::dialogs::Field::text("color", "Color (#rrggbb)", &format!("#{r:02x}{g:02x}{b:02x}"))],
+ );
+ return Ok(Value::Null);
+ }
+ let c = p.get("color").and_then(Value::as_str).unwrap_or("mediumGray");
+ v.pasteboard = match c {
+ "black" => Some([0, 0, 0]),
+ "darkGray" => Some([0x2a, 0x2a, 0x2a]),
+ "mediumGray" => None,
+ "lightGray" => Some([0xb4, 0xb4, 0xb4]),
+ "white" => Some([0xff, 0xff, 0xff]),
+ "custom" => Some(v.custom_pasteboard),
+ hex => {
+ let c = effectcraft_engine::color::Rgba::from_hex(hex).ok_or_else(|| format!("unknown colour `{hex}`"))?;
+ let rgb = [(c.r * 255.0).round() as u8, (c.g * 255.0).round() as u8, (c.b * 255.0).round() as u8];
+ v.custom_pasteboard = rgb;
+ Some(rgb)
+ }
+ };
+ Value::Null
+ }
+ // Ctrl+\ / Cmd+\, as in After Effects (#336): `{maximized}`, the window's new state.
+ "window.maximizeApp" => {
+ let maximized = !ctx.input(|i| i.viewport().maximized.unwrap_or(false));
+ ctx.send_viewport_cmd(egui::ViewportCommand::Maximized(maximized));
+ json!({"maximized": maximized})
+ }
+ "view.fullScreen" => {
+ let full = ctx.input(|i| i.viewport().fullscreen.unwrap_or(false));
+ ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(!full));
+ json!(!full)
+ }
+ "window.panel" => {
+ let name = p.get("panel").and_then(Value::as_str).unwrap_or_default();
+ if name.eq_ignore_ascii_case("tools") {
+ app.ui.status = "The Tools panel is the toolbar in the header".into();
+ return Ok(Value::Null);
+ }
+ let panel = PanelKind::from_name(name).ok_or_else(|| format!("unknown panel `{name}`"))?;
+ app.show_panel(panel);
+ Value::Null
+ }
+ "window.workspace" => {
+ let want = p.get("name").and_then(Value::as_str).unwrap_or("Default").to_ascii_lowercase().replace(' ', "");
+ let name = app
+ .workspace_names()
+ .into_iter()
+ .find(|w| w.to_ascii_lowercase().replace(' ', "") == want)
+ .ok_or_else(|| format!("unknown workspace `{want}`"))?;
+ app.set_workspace(&name);
+ json!({"workspace": name})
+ }
+ "window.resetWorkspace" => {
+ let name = app.ui.workspace.clone();
+ app.set_workspace(&name);
+ Value::Null
+ }
+ "window.saveWorkspace" => {
+ let name = app.ui.workspace.clone();
+ app.ui.saved_workspaces.insert(name.clone(), app.ui.dock.clone());
+ app.store_saved_workspaces()?;
+ json!({"workspace": name})
+ }
+ "window.saveWorkspaceAs" => {
+ let Some(name) = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string) else {
+ crate::panels::dialogs::form(
+ app,
+ "New Workspace",
+ "window.saveWorkspaceAs",
+ json!({}),
+ vec![crate::panels::dialogs::Field::text("name", "Name", "Untitled Workspace")],
+ );
+ return Ok(Value::Null);
+ };
+ app.ui.saved_workspaces.insert(name.clone(), app.ui.dock.clone());
+ app.ui.workspace = name.clone();
+ app.store_saved_workspaces()?;
+ json!({"workspace": name})
+ }
+ "window.editWorkspaces" => {
+ let Some(name) = p.get("name").and_then(Value::as_str).map(str::to_string) else {
+ let cur = app.ui.workspace.clone();
+ crate::panels::dialogs::form(
+ app,
+ "Edit Workspaces",
+ "window.editWorkspaces",
+ json!({}),
+ vec![
+ crate::panels::dialogs::Field::text("name", "Workspace", &cur),
+ crate::panels::dialogs::Field::text("rename", "Rename to", &cur),
+ crate::panels::dialogs::Field::bool("delete", "Delete", false),
+ ],
+ );
+ return Ok(Value::Null);
+ };
+ let builtin = crate::dock::WORKSPACES.contains(&name.as_str());
+ if p.get("delete").and_then(Value::as_bool) == Some(true) {
+ if app.ui.saved_workspaces.remove(&name).is_none() && !builtin {
+ return Err(format!("no workspace `{name}`"));
+ }
+ // Leave the deleted workspace first: a current workspace needs a definition.
+ if app.ui.workspace == name {
+ app.set_workspace("Default");
+ }
+ app.store_saved_workspaces()?;
+ return Ok(json!({"deleted": name}));
+ }
+ if let Some(new) = p.get("rename").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty() && *n != name) {
+ if builtin {
+ return Err(format!("`{name}` is a built-in workspace: save it as a new workspace instead"));
+ }
+ let dock = app.ui.saved_workspaces.remove(&name).ok_or_else(|| format!("no workspace `{name}`"))?;
+ app.ui.saved_workspaces.insert(new.to_string(), dock);
+ if app.ui.workspace == name {
+ app.ui.workspace = new.to_string();
+ }
+ app.store_saved_workspaces()?;
+ return Ok(json!({"renamed": new}));
+ }
+ json!({"workspaces": app.workspace_names()})
+ }
+ "view.lookAt" => {
+ let r: Vec<f64> = p.get("rect").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
+ if r.len() == 4 {
+ let map: Option<crate::panels::viewer::ViewerMap> = ctx.data(|d| d.get_temp(egui::Id::unique("viewer-map")));
+ if let Some(m) = map {
+ let (rw, rh) = (((r[2] - r[0]) as f32).max(1.0), ((r[3] - r[1]) as f32).max(1.0));
+ let zoom = ((m.area.width() - 40.0) / rw).min((m.area.height() - 40.0) / rh).clamp(0.015, 32.0);
+ let rc = [(r[0] + r[2]) as f32 / 2.0, (r[1] + r[3]) as f32 / 2.0];
+ let v = &mut app.ui.viewer;
+ v.zoom = Some(zoom);
+ v.pan = [m.comp[0] * zoom / 2.0 - rc[0] * zoom, m.comp[1] * zoom / 2.0 - rc[1] * zoom];
+ }
+ }
+ Value::Null
+ }
+ "comp.flowchart" => {
+ // Chart the active comp; Layer ▸ Reveal ▸ Reveal Layer in Project Flowchart shows
+ // layers and selects the layer's node.
+ app.ui.flowchart.root = app.session.active_comp_id().map(|c| c.0);
+ if let (Some(c), Some(l)) = (app.session.active_comp_id(), app.session.state.selected_layers.first()) {
+ app.ui.flowchart.layers = true;
+ app.ui.flowchart.selected = Some(format!("layer:{}:{}", c.0, l.0));
+ }
+ app.show_panel(PanelKind::Flowchart);
+ Value::Null
+ }
+ "comp.miniFlowchart" => {
+ let at = ctx.input(|i| i.pointer.hover_pos()).unwrap_or_else(|| ctx.content_rect().center());
+ app.ui.mini_flowchart = Some([at.x, at.y]);
+ Value::Null
+ }
+ "track.editTargetDialog" => {
+ crate::panels::tracker::open_target(app)?;
+ Value::Null
+ }
+ "track.optionsDialog" => {
+ crate::panels::tracker::open_options(app)?;
+ Value::Null
+ }
+ "layer.openLayer" => {
+ let id = p.get("layer").and_then(Value::as_u64).or_else(|| app.session.state.selected_layers.first().map(|l| l.0));
+ // Another layer opens at Fit.
+ if id != app.ui.layer_panel {
+ app.ui.layer_zoom = None;
+ app.ui.layer_pan = [0.0, 0.0];
+ }
+ app.ui.layer_panel = id;
+ app.ui.layer_view = None;
+ app.show_panel(PanelKind::Layer);
+ Value::Null
+ }
+ "app.confirmExecute" => {
+ // Settings ▸ Scripting ▸ Warn User When Executing Files.
+ let path = p.get("path").and_then(Value::as_str).unwrap_or_default().to_string();
+ crate::panels::forms::form(
+ app,
+ "A script wants to open a file",
+ "file.executeFile",
+ json!({"path": path, "confirmed": true}),
+ vec![crate::panels::forms::Field::text("path", "Open", &path)],
+ );
+ Value::Null
+ }
+ "app.showReport" => {
+ let title = p.get("title").and_then(Value::as_str).unwrap_or("Report").to_string();
+ let text = p.get("text").and_then(Value::as_str).unwrap_or_default().to_string();
+ crate::panels::dialogs::info(app, &title, &text);
+ Value::Null
+ }
+ "window.assignWorkspaceShortcut" => {
+ let mut q = p.clone();
+ q["workspace"] = json!(app.ui.workspace);
+ return run_engine(app, ctx, "window.assignWorkspaceShortcut", q);
+ }
+ "file.interpretFootage" => {
+ // Import ▸ Interpret Unlabeled Alpha As: Ask User.
+ if let Some(i) = p.get("item").and_then(Value::as_u64) {
+ app.session.state.project_selection = vec![effectcraft_engine::project::ItemId(i)];
+ }
+ crate::panels::dialogs::open_form(app, "file.interpretFootage", &json!({}));
+ Value::Null
+ }
+ // Help ▸ In-App Tutorials: the Home screen's Learn tab.
+ "help.inAppTutorials" => {
+ app.ui.start_screen = true;
+ app.ui.home_learn = true;
+ app.ui.home_templates = false;
+ Value::Null
+ }
+ // File ▸ New ▸ New Project from Template…: the Home screen's Templates tab.
+ "file.newFromTemplate" => {
+ app.ui.start_screen = true;
+ app.ui.home_learn = false;
+ app.ui.home_templates = true;
+ Value::Null
+ }
+ "effect.manage" | "anim.browsePresets" => {
+ app.show_panel(PanelKind::EffectsPresets);
+ Value::Null
+ }
+ "timeline.revealProps" => {
+ let props = p.get("props").and_then(Value::as_array).cloned().unwrap_or_default();
+ let uids = |k: &str| -> Vec<u64> { props.iter().filter_map(|x| x.get(k).and_then(Value::as_u64)).collect() };
+ let (found, with_props) = (uids("prop"), uids("layer"));
+ // The layers it looked at (`layers`), else those it found something on. Layers that
+ // have nothing to show close; the others' reveals stay.
+ let targets: Vec<u64> = match p.get("layers").and_then(Value::as_array) {
+ Some(l) => l.iter().filter_map(Value::as_u64).collect(),
+ None => with_props.clone(),
+ };
+ // The targets' earlier picks go (U after UU shows the keyframed ones only).
+ let comp = app.session.active_comp_arc();
+ let theirs = |u: u64| {
+ comp.as_ref().is_some_and(|c| {
+ targets
+ .iter()
+ .filter_map(|l| c.layer(effectcraft_engine::project::LayerId(*l)))
+ .any(|l| l.props.find(u).is_some() || l.props.find_group(u).is_some())
+ })
+ };
+ let tl = &mut app.ui.timeline;
+ tl.reveal_props.retain(|u| !theirs(*u));
+ tl.reveal_props.extend(found.iter().copied());
+ let (shown, hidden): (Vec<u64>, Vec<u64>) = targets.into_iter().partition(|l| with_props.contains(l));
+ tl.apply_reveal(&hidden, vec![]);
+ if !shown.is_empty() {
+ tl.apply_reveal(&shown, vec!["props".into()]);
+ }
+ // Properties inside effects (puppet pins…) show under their effect, twirled open.
+ for (layer, prop) in props.iter().filter_map(|x| Some((x.get("layer")?.as_u64()?, x.get("prop")?.as_u64()?))) {
+ crate::panels::timeline::open_effect_paths(app, layer, &[prop]);
+ }
+ json!({"revealed": found.len()})
+ }
+ _ => return Err(format!("`{id}` is not a frontend command")),
+ })
+ }
+
+ /// Commands that need a file or folder path: ask the host's file dialog when `params` lacks one.
+ pub(super) fn file_dialog(app: &mut EffectcraftApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
+ enum Ask {
+ Folder,
+ Import,
+ OpenProject,
+ Save(&'static str),
+ Open(&'static [&'static str]),
++ /// A movie, or a file with one of these extensions.
++ OpenFootage(&'static [&'static str]),
+ }
+ let (key, ask) = match id {
+ "file.import" | "file.importMultiple" => ("paths", Ask::Import),
+ "file.open" => ("path", Ask::OpenProject),
+ "file.save" if app.session.path.is_none() => ("path", Ask::Save("Untitled Project.ecproj")),
+ "file.saveAs" | "file.saveCopy" => ("path", Ask::Save("Untitled Project.ecproj")),
+ "comp.saveFrameAs" => ("path", Ask::Save("Frame.png")),
+ "comp.saveFrameAsPsd" => ("path", Ask::Save("Frame.psd")),
+ "comp.saveFrameAsExr" => ("path", Ask::Save("Frame.exr")),
+ "file.watchFolder" if params.get("stop").is_none() => ("folder", Ask::Save("Watch Folder")),
+ "anim.savePreset" => ("path", Ask::Save("Preset.ecpreset")),
+ "anim.applyPreset" => ("path", Ask::Open(&["ecpreset", "json"])),
+ "view.exportGuides" => ("path", Ask::Save("Guides.json")),
+ "view.importGuides" => ("path", Ask::Open(&["json"])),
+ "file.exportLottie" => ("path", Ask::Save("Animation.json")),
+ "file.importLottie" => ("path", Ask::Open(&["json", "lottie"])),
+ "file.importProject" => ("path", Ask::Open(&["ecproj", "ecprojx"])),
+ "file.importTimeline" => ("path", Ask::Open(&["xml", "fcpxml", "otio", "edl", "aaf", "omf"])),
+ "render.saveCurrentPreview" => ("path", Ask::Save("Preview.mp4")),
+ "file.runScript" if params.get("name").is_none() => ("path", Ask::Open(&["jsx", "js", "jsonl", "json", "txt"])),
+ "file.installScript" | "file.installScriptUIPanel" => ("path", Ask::Open(&["jsx", "js"])),
+ "effect.plugins.load" if params.get("folder").is_none() => ("path", Ask::Open(&["wasm", "wat"])),
+ "file.replaceFootage" => ("path", Ask::Import),
+ "file.relinkFootage" => ("folder", Ask::Folder),
+ "file.collectFiles" => ("folder", Ask::Save("Collected Files")),
+ "file.saveCopyAsXml" => ("path", Ask::Save("Untitled Project.ecprojx")),
+ "keys.rpfCameraImport" => ("path", Ask::Open(&["json", "csv", "txt"])),
+ "essential.exportTemplate" => ("path", Ask::Save("Template.ectemplate")),
+ "essential.importTemplate" => ("path", Ask::Open(&["ectemplate"])),
- "file.setProxy" => {
- ("path", Ask::Open(&["mp4", "mov", "m4v", "mkv", "webm", "mxf", "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "tga", "exr"]))
- }
++ "file.setProxy" => ("path", Ask::OpenFootage(&["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "tga", "exr"])),
+ _ => return None,
+ };
+ if params.get(key).is_some()
+ || params.get("path").is_some()
+ || params.get("paths").is_some()
+ || params.get("steps").is_some()
+ || params.get("preset").is_some()
+ {
+ return None;
+ }
++ // Importable files besides movies.
+ const MEDIA: &[&str] = &[
- "mp4", "mov", "m4v", "mkv", "webm", "mxf", "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "dpx", "cin", "wav", "aif", "aiff", "mp3",
- "flac", "ogg", "opus", "svg", "pdf", "ai", "eps", "psd", "psb", "tga", "hdr", "gltf", "glb", "obj", "stl", "fbx", "json", "csv", "tsv",
++ "png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "dpx", "cin", "wav", "aif", "aiff", "mp3", "flac", "ogg", "opus", "svg", "pdf", "ai",
++ "eps", "psd", "psb", "tga", "hdr", "gltf", "glb", "obj", "stl", "fbx", "json", "csv", "tsv",
+ ];
++ let footage = |more: &[&'static str]| effectcraft_project::VIDEO_EXTENSIONS.iter().chain(more).copied().collect::<Vec<_>>();
+ // A host whose blocking dialogs are unsafe inside this frame shows the dialog without
+ // blocking — macOS: the nested event loop re-entered winit's handler on a drag over the
+ // window and aborted the app (#511); Linux: the desktop portal's answer never gets pumped,
+ // so the compositor marks the window as not responding (#1275) — and the command continues
+ // when the answer arrives.
+ if let Some(spawn) = app.hooks.file_dialog_async.as_ref() {
+ let request = match ask {
+ Ask::Folder => crate::FileDialog::Folder,
- Ask::Import => crate::FileDialog::Open { exts: MEDIA.iter().map(|e| e.to_string()).collect(), many: key == "paths" },
++ Ask::Import => crate::FileDialog::Open { exts: footage(MEDIA).iter().map(|e| e.to_string()).collect(), many: key == "paths" },
+ Ask::OpenProject => crate::FileDialog::OpenProject,
+ Ask::Open(exts) => crate::FileDialog::Open { exts: exts.iter().map(|e| e.to_string()).collect(), many: false },
++ Ask::OpenFootage(more) => crate::FileDialog::Open { exts: footage(more).iter().map(|e| e.to_string()).collect(), many: false },
+ Ask::Save(default) => crate::FileDialog::save(default),
+ };
+ let tx = app.dialog_answers.0.clone();
+ let answer = crate::DialogAnswer { command: id.to_string(), key, params: params.clone(), paths: Vec::new() };
+ app.file_dialogs.opened();
+ spawn(
+ request,
+ Box::new(move |paths| {
+ let _ = tx.send(crate::DialogAnswer { paths, ..answer });
+ }),
+ );
+ return Some(Ok(json!({"dialog": id})));
+ }
+ let picked: Option<Value> = match ask {
+ Ask::Folder => {
+ let Some(f) = app.hooks.pick_folder.as_ref() else { return Some(Err("no folder dialog available (pass `folder`)".into())) };
+ f().map(Value::from)
+ }
+ Ask::Import => {
+ let Some(f) = app.hooks.pick_files.as_ref() else { return Some(Err("no file dialog available (pass `paths`)".into())) };
- picked_value(key, f(MEDIA))
++ picked_value(key, f(&footage(MEDIA)))
+ }
+ Ask::OpenProject => {
+ let Some(f) = app.hooks.pick_open_project.as_ref() else { return Some(Err("no file dialog available (pass `path`)".into())) };
+ f().map(|s| json!(s))
+ }
+ Ask::Open(exts) => {
+ let Some(f) = app.hooks.pick_files.as_ref() else { return Some(Err("no file dialog available (pass `path`)".into())) };
+ f(exts).first().map(|s| json!(s))
+ }
++ Ask::OpenFootage(more) => {
++ let Some(f) = app.hooks.pick_files.as_ref() else { return Some(Err("no file dialog available (pass `path`)".into())) };
++ f(&footage(more)).first().map(|s| json!(s))
++ }
+ Ask::Save(default) => {
+ let Some(picked) = app.hooks.save_dialog(default) else { return Some(Err("no file dialog available (pass `path`)".into())) };
+ picked.map(|s| json!(s))
+ }
+ };
+ let Some(v) = picked else { return Some(Ok(Value::Null)) };
+ Some(run_with_picked(app, id, key, params, v))
+ }
+
+ /// The dialog's answer as the command's `key` parameter (`None`: cancelled).
+ fn picked_value(key: &str, paths: Vec<String>) -> Option<Value> {
+ match (paths.is_empty(), key) {
+ (true, _) => None,
+ (false, "paths") => Some(json!(paths)),
+ (false, _) => paths.into_iter().next().map(Value::from),
+ }
+ }
+
+ /// A file dialog shown without blocking ([`crate::Hooks::file_dialog_async`]) answered: run its
+ /// command with the picked path (nothing when it was cancelled).
+ pub(crate) fn dialog_answered(app: &mut EffectcraftApp, answer: crate::DialogAnswer) {
+ let Some(v) = picked_value(answer.key, answer.paths) else { return };
+ if let Err(e) = run_with_picked(app, &answer.command, answer.key, &answer.params, v) {
+ app.ui.status = e;
+ }
+ }
+
+ /// Run command `id` with the path picked for it in parameter `key`.
+ fn run_with_picked(app: &mut EffectcraftApp, id: &str, key: &str, params: &Value, v: Value) -> Result<Value, String> {
+ let mut p = params.as_object().cloned().unwrap_or_default();
+ p.insert(key.to_string(), v);
+ // Picked files import in the background, with the Importing card showing progress (#270).
+ if matches!(id, "file.import" | "file.importMultiple") {
+ p.insert("background".into(), Value::Bool(true));
+ }
+ // Photoshop files ask how to import them first; numbered stills whether to import them as an
+ // image sequence.
+ let picked = Value::Object(p.clone());
+ if id == "file.import" && crate::panels::dialogs::open_form(app, id, &picked)
+ || matches!(id, "file.import" | "file.importMultiple") && crate::panels::forms::open_import_sequence(app, &picked)
+ {
+ return Ok(json!({"dialog": id}));
+ }
+ // Save (untitled) becomes Save As.
+ let id = if id == "file.save" { "file.saveAs" } else { id };
+ let r = app.session.execute(id, Value::Object(p)).map_err(|e| e.to_string());
+ if let Err(e) = &r {
+ app.ui.status = e.clone();
+ }
+ r
+ }
+
+ /// View ▸ Zoom In / Zoom Out: the next standard magnification (as a share of screen pixels, so
+ /// 100 % is one comp pixel per screen pixel at any display scaling) above or below `cur`, which is
+ /// in points per comp pixel like the result (#882).
+ pub(super) fn zoom_step(cur: f32, ppp: f32, zoom_in: bool) -> f32 {
+ const STEPS: [f32; 16] = [0.015, 0.03, 0.0625, 0.125, 0.25, 0.333, 0.5, 0.66, 1.0, 1.5, 2.0, 3.0, 4.0, 8.0, 16.0, 32.0];
+ let ppp = if ppp.is_finite() && ppp > 0.0 { ppp } else { 1.0 };
+ let shown = cur * ppp;
+ let next = if zoom_in {
+ STEPS.iter().copied().find(|s| *s > shown + 1e-3).unwrap_or(32.0)
+ } else {
+ STEPS.iter().rev().copied().find(|s| *s < shown - 1e-3).unwrap_or(0.015)
+ };
+ next / ppp
+ }
diff --cc docs/gaps.md
index e0dcc618f,3f59b1f99..167adb194
--- a/docs/gaps.md
+++ b/docs/gaps.md
@@@ -73,10 -73,10 +73,10 @@@ are grouped by area; the issue tracker
| 14 | **Object Matte** (26.2, disk cache in 26.5) | First slice (#783): the Object Matte effect (Effect ▸ Matte) and `objectMatte.apply` turn a point (and optional box) on a reference frame into a matte and follow the object up to 600 frames each way, or segment every frame on its own; Roto Brush's engine, cache and model (MobileSAM from Settings ▸ Roto Brush, classical graph cut without it). Since then: the Object Matte tool in the viewer (click / drag a box, hover crosshair), the box as the model's box prompt, background tracking with progress and cancel, Freeze, and segmentations kept in the disk cache (26.5). Missing: a comparison with After Effects ([plan](fidelity/object-matte.md)) | The new one-click roto | 10–20 h | G7 · [target-app-parity.md](target-app-parity.md) |
| 15 | **Hardware video decode and encode** | No VideoToolbox, NVENC, Quick Sync or VA-API; #498 asks for it (answered: CUDA / NVENC need Nvidia's proprietary SDK through FFI, which the no-`unsafe` rule forbids); open PR #819 adds hardware decoding via `filmcraft-platform`; FilmCraft has VideoToolbox / NVENC / VA-API paths to borrow | 4K playback and export speed | 25–45 h | G5/G6 · [hardware-parity.md](hardware-parity.md) |
| 16 | **Localization depth** | Menus in 11 languages (ja, zh-hans, zh-hant, uk, es, pt-br, ru, fr, de, cs, ka: 628 rows each); panels in 7 (ja, zh-hans, zh-hant, uk, pt-br, cs, ka); effect names translated in Simplified Chinese and Georgian (307, plus the generated Effect menu), their ~1,650 parameter names untranslated; Korean and Italian (After Effects ships them) absent; Hangul probe added (#599 closed) | After Effects is used heavily in Japan, China, Korea, Brazil, Europe | 60–110 h + native review | G9 · [localization-parity.md](localization-parity.md) |
-| 17 | **Media Browser lists files import refuses** | `media_browser.rs` lists AVI; `media::is_importable` has none of them (Targa and Radiance HDR import since #745; DPX and Cineon since #756, log shown as stored: no Cineon Settings conversion yet; MXF OP1a / OP-Atom since #767; FilmCraft has no AVI demuxer); #431 and #324 closed | Confusing failures on common VFX formats | 15–30 h | G6 · [file-format-parity.md](file-format-parity.md) |
+| 17 | **Media Browser lists files import refuses** | The Media Browser, the import and proxy dialogs and `media::is_importable` share one movie list since #1701, AVI included (Targa and Radiance HDR import since #745; DPX and Cineon since #756, log shown as stored: no Cineon Settings conversion yet; MXF OP1a / OP-Atom since #767; AVI since #1701, without DV, MPEG-4 Part 2 or other legacy codecs yet); #431 and #324 closed | Confusing failures on common VFX formats | 15–30 h | G6 · [file-format-parity.md](file-format-parity.md) |
| 18 | **Relative paths and relinking** | Projects store absolute footage paths; no relink when a project moves | Moving or sharing a project breaks it | 6–12 h | G4 · [file-format-parity.md](file-format-parity.md) |
| 19 | **Plug-in ecosystem** | No After Effects SDK hosting (#600, #327 OpenFX, #334, #376 plug-in manager); our WebAssembly API has no third-party plug-ins | Many pro projects depend on Trapcode, Element, Saber… | 40–80 h for API growth; SDK hosting needs an owner decision | G8 · [scripting-parity.md](scripting-parity.md) |
- | 20 | **Multi-monitor and video output** | #486: any panel can move into a native window of its own (panel menu ▸ Move Panel to New Window, `window.panelWindow`) and so onto another screen, restored with the workspace; still missing: dragging tabs between those windows, app shortcuts while one has the focus, named workspaces remembering them, Mercury Transmit to video hardware (we have a second preview window only) | Two-screen setups are standard for professionals | 10–20 h | G2 · [hardware-parity.md](hardware-parity.md) |
+ | 20 | **Multi-monitor and video output** | #486: on Windows, macOS and X11 every floating panel is an OS window of its own (Undock Panel, a drag out of the main window, panel menu ▸ Move Panel to New Window, `window.panelWindow`) and so can go onto another screen (on Wayland, the web and in embedded viewports floating panels stay in the app window, since Wayland reports no window positions); tabs and groups drag between windows, shortcuts work in them, and the current and named workspaces restore their places; still missing: Mercury Transmit to video hardware (we have a second preview window only) | Two-screen setups are standard for professionals | 10–20 h | G2 · [hardware-parity.md](hardware-parity.md) |
| 21 | **Small 26.x features** | Proportional Scrubbing (26.2), pasting Illustrator's own clipboard data as shapes (26.3; SVG markup on the clipboard pastes as a shape layer, #738), variable-font filter (26.3), the rebuilt Effect Controls (26.5). Percentage guides (View ▸ Add Percentage Guide, Convert Guides to Percentage / Pixels) and effect colour labels (Effect Controls header bar and right-click Label menu, `effect.setLabel`) are in (#1095), built from the release notes' one-line descriptions and never compared with After Effects: the Timeline's effect rows wear the label as a colour bar on the left edge (#1509), but After Effects' exact UI there is unknown | Users of the current version expect them | 10–20 h left | — · [ui-parity.md](ui-parity.md) |
| 22 | **Encoder efficiency** | HEVC / AV1 have no B-frames, multi-reference or SAO / CDEF; Opus no FEC / DTX; single-file intermediates are 8-bit uncompressed QuickTime only (#372 closed by #778: no 16-bpc, AVI or lossless-compressed codec); #325 render over existing file | Larger files than After Effects + Media Encoder | 20–40 h | G6 · [file-format-parity.md](file-format-parity.md) |
| 23 | **Essential Graphics interchange** | Templates are `.ectemplate`, not `.mogrt`; #338 and #611 closed | Premiere editors can't use our templates | 15–30 h | — · [file-format-parity.md](file-format-parity.md) |