Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

refactor(project): the document reads through serde, keeps what it does not know, and migrates by table

Jareer7b4362dbf778
diff --git a/src/crates/concat-project/src/commands/audio.rs b/src/crates/concat-project/src/commands/audio.rs
index 5295369f..71c93ab6 100644
--- a/src/crates/concat-project/src/commands/audio.rs
+++ b/src/crates/concat-project/src/commands/audio.rs
@@ -77,6 +77,7 @@ pub(super) fn apply(
id: id.clone(),
visible: true,
muted: false,
+ extra: Default::default(),
});
id
}
diff --git a/src/crates/concat-project/src/commands/clips.rs b/src/crates/concat-project/src/commands/clips.rs
index 6b389ce1..9d15599c 100644
--- a/src/crates/concat-project/src/commands/clips.rs
+++ b/src/crates/concat-project/src/commands/clips.rs
@@ -313,6 +313,7 @@ pub(super) fn apply(
has_audio: false,
audio_tracks: Vec::new(),
placeholder: false,
+ extra: Default::default(),
});
id
}
diff --git a/src/crates/concat-project/src/commands/media.rs b/src/crates/concat-project/src/commands/media.rs
index 65cf59d0..3216a524 100644
--- a/src/crates/concat-project/src/commands/media.rs
+++ b/src/crates/concat-project/src/commands/media.rs
@@ -39,6 +39,7 @@ pub(super) fn apply(
has_audio: item.has_audio,
audio_tracks: item.audio_tracks,
placeholder: false,
+ extra: Default::default(),
});
Ok(Outcome {
created_id: Some(id),
diff --git a/src/crates/concat-project/src/commands/timelines.rs b/src/crates/concat-project/src/commands/timelines.rs
index 1458a6f2..7adb10cf 100644
--- a/src/crates/concat-project/src/commands/timelines.rs
+++ b/src/crates/concat-project/src/commands/timelines.rs
@@ -29,6 +29,7 @@ pub(super) fn apply(
id: mint.next("t"),
visible: true,
muted: false,
+ extra: Default::default(),
})
.collect();
// Born at the frame of the timeline you were looking at: the
@@ -41,6 +42,7 @@ pub(super) fn apply(
video,
tracks,
clips: Vec::new(),
+ extra: Default::default(),
}));
project.active_timeline_id = id.clone();
Ok(Outcome {
diff --git a/src/crates/concat-project/src/commands/tracks.rs b/src/crates/concat-project/src/commands/tracks.rs
index 9a4f2b11..635eb87d 100644
--- a/src/crates/concat-project/src/commands/tracks.rs
+++ b/src/crates/concat-project/src/commands/tracks.rs
@@ -22,6 +22,7 @@ pub(super) fn apply(
id: id.clone(),
visible: true,
muted: false,
+ extra: Default::default(),
});
Ok(Outcome {
created_id: Some(id),
diff --git a/src/crates/concat-project/src/doc.rs b/src/crates/concat-project/src/doc.rs
index 7e32d299..b8f38759 100644
--- a/src/crates/concat-project/src/doc.rs
+++ b/src/crates/concat-project/src/doc.rs
@@ -1,39 +1,43 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
-//! Reading and writing `concat.json`.
+//! The document: `concat.json` in and out.
//!
-//! Projects saved before the renames carry the same document as
-//! `wolfcut.json`. The name on disk is the host's concern:
-//! it keeps whichever name a project already has, and this module never
-//! looks at a filename.
+//! Reading is three steps, each with one job:
//!
-//! The reader's tolerance rules are the contract with every document
-//! already on disk: every field defaults rather than being trusted, clips whose
-//! track or media vanished are dropped, text clips survive without media,
-//! legacy flat documents load as a single timeline. A hand-edited or older
-//! file must degrade to something openable, never to a load error.
+//! 1. **Migrate.** The JSON is walked through [`MIGRATIONS`], oldest shape
+//! first, until it has the shape this build writes. A document from a
+//! later build than this one is refused whole rather than read in part
+//! and then saved over.
+//! 2. **Parse.** The model's own `serde` derives read it. Every struct
+//! defaults a missing field, every list keeps the entries that parse and
+//! drops the rest, and every field this build does not know lands in the
+//! struct's `extra` map, so it is written back out untouched. See
+//! `model::wire` for the tolerant readers.
+//! 3. **Settle.** What no derive can decide: a clip whose track or media is
+//! gone has nowhere to live and is dropped, a timeline with no lanes is
+//! no timeline, every number is pulled into the range a command holds it
+//! to ([`Clip::tidy`]), and the active timeline is one that exists.
//!
-//! The writer produces the same structure - including the
-//! flat `tracks`/`clips` mirror of the active timeline that keeps documents
-//! openable in builds that predate multiple timelines.
-
-use std::collections::BTreeMap;
+//! The standing rule through all three: a hand-edited or older file
+//! degrades to something openable. Nothing short of a document that is not
+//! an object, or that has no timeline in it, fails the load.
+//!
+//! Writing is the derives again, plus a mirror of the active timeline in
+//! the flat `tracks` / `clips` / `video` fields that builds from before
+//! multiple timelines read, so a file saved here still opens there.
+use std::collections::HashSet;
use std::sync::Arc;
use serde_json::{Map, Value, json};
-use crate::model::{
- AppliedFilter, AudioTrack, Clip, ClipAnimation, ClipKey, ClipKind, Crop, CustomFont, Cutout,
- KeyEase, KeyProperty, MediaItem, MediaKind, ParamKey, Project, SpeedPoint, TextAlign,
- TextStyle, Timeline, Track, Transition, VideoSettings,
-};
+use crate::model::{Clip, MediaItem, Project, Timeline, VideoSettings};
/// Bumped only when a change cannot be absorbed by defaulting. Read back
/// on load: a document from a later version is refused whole rather than
-/// read in part and then saved over. Add a migration step here when it
-/// moves.
+/// read in part and then saved over. Every bump adds a step to
+/// [`MIGRATIONS`].
pub const DOCUMENT_VERSION: u64 = 1;
/// The version a document says it is. Documents from before the field
@@ -42,368 +46,233 @@ pub fn document_version(document: &Value) -> u64 {
document.get("version").and_then(Value::as_u64).unwrap_or(1)
}
-fn text(value: Option<&Value>, fallback: &str) -> String {
- value.and_then(Value::as_str).unwrap_or(fallback).to_owned()
+/// One step of the reader's migration table: a name for the log, and the
+/// rewrite. Each step is idempotent - a document already in the shape it
+/// produces passes through unchanged - so the table is simply applied in
+/// order, and a document at any age comes out at the current shape.
+struct Migration {
+ #[allow(dead_code)]
+ name: &'static str,
+ apply: fn(&mut Map<String, Value>),
}
-fn number(value: Option<&Value>, fallback: f64) -> f64 {
- value
- .and_then(Value::as_f64)
- .filter(|n| n.is_finite())
- .unwrap_or(fallback)
+/// The migration table, oldest shape first. Add to the end; never reorder
+/// or remove, because a document written at any point in the project's
+/// history has to walk the whole way up.
+const MIGRATIONS: &[Migration] = &[
+ Migration {
+ name: "timelines from the flat fields",
+ apply: lift_flat_timeline,
+ },
+ Migration {
+ name: "every timeline carries its frame",
+ apply: give_timelines_their_frame,
+ },
+];
+
+/// A document from before multiple timelines holds one, as the top-level
+/// `tracks`, `clips` and `video`. Lifted into `timelines` as the one
+/// timeline it always was, leaving the flat fields in place: they are
+/// written back as the mirror every save writes.
+fn lift_flat_timeline(document: &mut Map<String, Value>) {
+ let has_timelines = document
+ .get("timelines")
+ .and_then(Value::as_array)
+ .is_some_and(|entries| !entries.is_empty());
+ if has_timelines {
+ return;
+ }
+ let tracks = document.get("tracks").cloned().unwrap_or(Value::Null);
+ if tracks.as_array().is_none_or(|tracks| tracks.is_empty()) {
+ return;
+ }
+ let clips = document.get("clips").cloned().unwrap_or(json!([]));
+ let mut timeline = json!({
+ "id": "TL1",
+ "name": "Timeline 1",
+ "tracks": tracks,
+ "clips": clips,
+ });
+ if let Some(video) = document.get("video").cloned()
+ && let Some(timeline) = timeline.as_object_mut()
+ {
+ timeline.insert("video".to_owned(), video);
+ }
+ document.insert("timelines".to_owned(), json!([timeline]));
}
-fn flag(value: Option<&Value>, fallback: bool) -> bool {
- value.and_then(Value::as_bool).unwrap_or(fallback)
+/// Timelines from before each carried its own frame take the document's
+/// top-level `video` block, a field at a time: a timeline naming a zero
+/// dimension or rate gets the shared value for that field rather than the
+/// zero, and one naming nothing gets the block whole.
+fn give_timelines_their_frame(document: &mut Map<String, Value>) {
+ let shared = document
+ .get("video")
+ .and_then(Value::as_object)
+ .cloned()
+ .unwrap_or_default();
+ let Some(timelines) = document.get_mut("timelines").and_then(Value::as_array_mut) else {
+ return;
+ };
+ for timeline in timelines.iter_mut().filter_map(Value::as_object_mut) {
+ let mut video = timeline
+ .get("video")
+ .and_then(Value::as_object)
+ .cloned()
+ .unwrap_or_default();
+ for key in ["width", "height", "rateNum", "rateDen"] {
+ let usable = video
+ .get(key)
+ .and_then(Value::as_i64)
+ .is_some_and(|n| n > 0);
+ if !usable && let Some(value) = shared.get(key) {
+ video.insert(key.to_owned(), value.clone());
+ }
+ }
+ if !video.is_empty() {
+ timeline.insert("video".to_owned(), Value::Object(video));
+ }
+ }
}
-fn opt_u32(value: Option<&Value>) -> Option<u32> {
- value
- .and_then(Value::as_u64)
- .and_then(|n| u32::try_from(n).ok())
+/// The document at this build's shape, or `None` for one from a later
+/// build.
+fn migrate(document: &Value) -> Option<Map<String, Value>> {
+ let mut document = document.as_object()?.clone();
+ if document_version(&Value::Object(document.clone())) > DOCUMENT_VERSION {
+ return None;
+ }
+ for migration in MIGRATIONS {
+ (migration.apply)(&mut document);
+ }
+ Some(document)
}
-fn opt_string(value: Option<&Value>) -> Option<String> {
- value.and_then(Value::as_str).map(str::to_owned)
-}
+/// The top-level keys the writer owns. Read, they would land in the
+/// project's `extra` map and be written twice; they are the writer's to
+/// produce afresh.
+const WRITER_OWNED: &[&str] = &[
+ "concat",
+ "version",
+ "name",
+ "video",
+ "tracks",
+ "clips",
+ "media",
+ "fonts",
+ "timelines",
+ "activeTimelineId",
+];
-fn read_media(raw: Option<&Value>) -> Vec<MediaItem> {
- let Some(entries) = raw.and_then(Value::as_array) else {
- return Vec::new();
- };
- entries
- .iter()
- .filter_map(|entry| {
- let id = entry.get("id")?.as_str()?.to_owned();
- let path = entry.get("path")?.as_str()?.to_owned();
- let kind = match entry.get("kind").and_then(Value::as_str) {
- Some("audio") => MediaKind::Audio,
- Some("image") => MediaKind::Image,
- _ => MediaKind::Video,
- };
- Some(MediaItem {
- name: text(entry.get("name"), &path),
- duration: entry.get("duration").and_then(Value::as_f64),
- kind,
- width: opt_u32(entry.get("width")),
- height: opt_u32(entry.get("height")),
- frame_rate: entry.get("frameRate").and_then(Value::as_f64),
- frame_rate_fraction: opt_string(entry.get("frameRateFraction")),
- video_codec: opt_string(entry.get("videoCodec")),
- audio_codec: opt_string(entry.get("audioCodec")),
- has_audio: flag(entry.get("hasAudio"), false),
- // Tolerated like everything else: a list the reader cannot
- // make sense of is no list, and clips fall back to the
- // file's first stream.
- audio_tracks: entry
- .get("audioTracks")
- .and_then(|value| serde_json::from_value::<Vec<AudioTrack>>(value.clone()).ok())
- .unwrap_or_default(),
- placeholder: flag(entry.get("placeholder"), false),
- id,
- path,
- })
- })
- .collect()
+/// Rebuilds a project from a document. Returns None only when there is
+/// nothing to open: a value that is not an object, a document from a later
+/// build, or one with no timeline that has a lane.
+pub fn from_document(document: &Value) -> Option<Project> {
+ let document = migrate(document)?;
+ let project: Project = serde_json::from_value(Value::Object(document)).ok()?;
+ settle(project)
}
-fn read_tracks(raw: Option<&Value>) -> Vec<Track> {
- let Some(entries) = raw.and_then(Value::as_array) else {
- return Vec::new();
- };
- entries
- .iter()
- .filter_map(|entry| {
- let id = entry.get("id")?.as_str()?.to_owned();
- Some(Track {
- id,
- visible: flag(entry.get("visible"), true),
- muted: flag(entry.get("muted"), false),
- })
+/// Everything the derives cannot decide about a freshly parsed project;
+/// see the module doc. `None` when no timeline survives.
+fn settle(mut project: Project) -> Option<Project> {
+ for key in WRITER_OWNED {
+ project.extra.remove(*key);
+ }
+ project.media = project
+ .media
+ .into_iter()
+ // An empty path is a template's placeholder, not a broken entry.
+ .filter(|item| !item.id.is_empty())
+ .map(MediaItem::tidy)
+ .collect();
+ let media: Vec<MediaItem> = project.media.clone();
+ project
+ .fonts
+ .retain(|font| !font.family.is_empty() && !font.path.is_empty());
+
+ let mut seen: HashSet<String> = HashSet::new();
+ project.timelines = project
+ .timelines
+ .into_iter()
+ .filter_map(|timeline| {
+ let timeline = Arc::try_unwrap(timeline).unwrap_or_else(|shared| (*shared).clone());
+ settle_timeline(timeline, &media)
})
- .collect()
-}
-
-fn read_filters(raw: Option<&Value>) -> Vec<AppliedFilter> {
- let Some(entries) = raw.and_then(Value::as_array) else {
- return Vec::new();
- };
- entries
+ .filter(|timeline| seen.insert(timeline.id.clone()))
+ .map(Arc::new)
+ .collect();
+ if project.timelines.is_empty() {
+ return None;
+ }
+ if !project
+ .timelines
.iter()
- .filter_map(|entry| {
- let id = entry.get("id")?.as_str()?.to_owned();
- let params = entry
- .get("params")
- .and_then(Value::as_object)
- .map(|map| {
- map.iter()
- .filter_map(|(key, value)| Some((key.clone(), value.as_f64()?)))
- .collect()
- })
- .unwrap_or_default();
- let mut filter = AppliedFilter {
- id,
- params,
- enabled: flag(entry.get("enabled"), true),
- keys: read_param_keys(entry.get("keys")),
- };
- filter.sort_keys();
- Some(filter)
- })
- .collect()
-}
-
-/// An effect's parameter keys: a run per parameter name, each key read
-/// with the same tolerance as a clip's own.
-fn read_param_keys(raw: Option<&Value>) -> BTreeMap<String, Vec<ParamKey>> {
- let Some(runs) = raw.and_then(Value::as_object) else {
- return BTreeMap::new();
- };
- runs.iter()
- .filter_map(|(name, run)| {
- let keys: Vec<ParamKey> = run
- .as_array()?
- .iter()
- .filter_map(|entry| {
- let at = number(entry.get("at"), -1.0);
- let value = number(entry.get("value"), f64::NAN);
- ((0.0..=1.0).contains(&at) && value.is_finite()).then_some(ParamKey {
- at,
- value,
- ease: read_ease(entry.get("ease")),
- })
- })
- .collect();
- (!keys.is_empty()).then(|| (name.clone(), keys))
- })
- .collect()
-}
-
-fn read_text_style(raw: Option<&Value>) -> TextStyle {
- let base = TextStyle::default();
- let Some(style) = raw.filter(|value| value.is_object()) else {
- return base;
- };
- TextStyle {
- content: text(style.get("content"), &base.content),
- font_family: text(style.get("fontFamily"), &base.font_family),
- // Clamped, not just defaulted: a hand-edited 0 would render an
- // invisible title.
- font_size: number(style.get("fontSize"), base.font_size).clamp(0.01, 1.0),
- font_weight: number(style.get("fontWeight"), base.font_weight).clamp(100.0, 900.0),
- italic: flag(style.get("italic"), base.italic),
- color: text(style.get("color"), &base.color),
- align: match style.get("align").and_then(Value::as_str) {
- Some("left") => TextAlign::Left,
- Some("right") => TextAlign::Right,
- _ => TextAlign::Center,
- },
- opacity: number(style.get("opacity"), base.opacity).clamp(0.0, 1.0),
- stroke_width: number(style.get("strokeWidth"), base.stroke_width).max(0.0),
- stroke_color: text(style.get("strokeColor"), &base.stroke_color),
- shadow: flag(style.get("shadow"), base.shadow),
- background: text(style.get("background"), &base.background),
- line_height: number(style.get("lineHeight"), base.line_height).max(0.5),
- tracking: number(style.get("tracking"), base.tracking),
- max_width: number(style.get("maxWidth"), base.max_width).max(0.0),
+ .any(|timeline| timeline.id == project.active_timeline_id)
+ {
+ project.active_timeline_id = project.timelines[0].id.clone();
}
+ Some(project)
}
-fn read_clips(raw: Option<&Value>, tracks: &[Track], media: &[MediaItem]) -> Vec<Clip> {
- let Some(entries) = raw.and_then(Value::as_array) else {
- return Vec::new();
- };
- entries
- .iter()
- .filter_map(|entry| {
- let id = entry.get("id")?.as_str()?.to_owned();
- let track_id = entry.get("trackId")?.as_str()?.to_owned();
- // A clip whose track vanished has nowhere to live.
- if !tracks.iter().any(|track| track.id == track_id) {
- return None;
- }
-
- let kind_name = entry.get("kind").and_then(Value::as_str);
- let is_text = kind_name == Some("text");
- let is_layer = kind_name == Some("layer");
- let media_id = if is_text || is_layer {
- String::new()
- } else {
- let media_id = entry.get("mediaId")?.as_str()?.to_owned();
- // Only the kinds that come from the bin are dropped when
- // their source is gone.
- if !media.iter().any(|item| item.id == media_id) {
- return None;
- }
- media_id
- };
-
- let kind = if is_text {
- ClipKind::Text
- } else if is_layer {
- ClipKind::Layer
- } else {
- match kind_name {
- Some("audio") => ClipKind::Audio,
- Some("image") => ClipKind::Image,
- _ => ClipKind::Video,
- }
- };
-
- Some(Clip {
- name: text(entry.get("name"), "clip"),
- kind,
- start: number(entry.get("start"), 0.0).max(0.0),
- duration: number(entry.get("duration"), 1.0),
- source_start: number(entry.get("sourceStart"), 0.0).max(0.0),
- volume: number(entry.get("volume"), 1.0).max(0.0),
- fade_in: number(entry.get("fadeIn"), 0.0).max(0.0),
- fade_out: number(entry.get("fadeOut"), 0.0).max(0.0),
- scale: number(entry.get("scale"), 1.0),
- offset_x: number(entry.get("offsetX"), 0.0),
- offset_y: number(entry.get("offsetY"), 0.0),
- rotation: number(entry.get("rotation"), 0.0),
- stretch_x: number(entry.get("stretchX"), 1.0),
- stretch_y: number(entry.get("stretchY"), 1.0),
- opacity: number(entry.get("opacity"), 1.0),
- speed: number(entry.get("speed"), 1.0),
- speed_curve: entry.get("speedCurve").and_then(|value| {
- let points: Vec<SpeedPoint> = value
- .as_array()?
- .iter()
- .map(|point| SpeedPoint {
- at: number(point.get("at"), -1.0),
- speed: number(point.get("speed"), 1.0),
- })
- .collect();
- (!points.is_empty()).then_some(points)
- }),
- reverse: flag(entry.get("reverse"), false),
- animation_in: read_animation(entry.get("animationIn")),
- animation_out: read_animation(entry.get("animationOut")),
- animation_combo: read_animation(entry.get("animationCombo")),
- keys: read_keys(entry.get("keys")),
- flip_h: flag(entry.get("flipH"), false),
- flip_v: flag(entry.get("flipV"), false),
- blend: text(entry.get("blend"), ""),
- crop: entry.get("crop").map(|crop| Crop {
- left: number(crop.get("left"), 0.0),
- top: number(crop.get("top"), 0.0),
- right: number(crop.get("right"), 0.0),
- bottom: number(crop.get("bottom"), 0.0),
- }),
- // Tolerated like everything else: a cutout the reader
- // cannot make sense of is no cutout.
- cutout: entry
- .get("cutout")
- .and_then(|value| serde_json::from_value::<Cutout>(value.clone()).ok()),
- preserve_pitch: flag(entry.get("preservePitch"), true),
- filters: read_filters(entry.get("filters")),
- video_effects: read_filters(entry.get("videoEffects")),
- audio_stream: opt_u32(entry.get("audioStream")),
- muted: flag(entry.get("muted"), false).then_some(true),
- detached_from: opt_string(entry.get("detachedFrom")),
- transition_in: entry.get("transitionIn").and_then(|transition| {
- Some(Transition {
- id: transition.get("id")?.as_str()?.to_owned(),
- duration: number(transition.get("duration"), 1.0),
- })
- }),
- text: is_text.then(|| read_text_style(entry.get("text"))),
- id,
- track_id,
- media_id,
- })
+/// One timeline settled: lanes and clips with ids, clips on lanes that
+/// exist and media that is in the bin, every number in range. `None` for
+/// a timeline with no id or no lane.
+fn settle_timeline(mut timeline: Timeline, media: &[MediaItem]) -> Option<Timeline> {
+ if timeline.id.is_empty() {
+ return None;
+ }
+ if timeline.name.trim().is_empty() {
+ timeline.name = "Timeline".to_owned();
+ }
+ timeline.video = timeline.video.or(VideoSettings::default());
+ let mut seen: HashSet<String> = HashSet::new();
+ timeline
+ .tracks
+ .retain(|track| !track.id.is_empty() && seen.insert(track.id.clone()));
+ if timeline.tracks.is_empty() {
+ return None;
+ }
+ let tracks = timeline.tracks.clone();
+ timeline.clips = timeline
+ .clips
+ .into_iter()
+ .filter_map(|clip| {
+ let clip = Arc::try_unwrap(clip).unwrap_or_else(|shared| (*shared).clone());
+ settle_clip(clip, &tracks, media)
})
- // Every number pulled into the range a command holds it to: the
- // one place the rules live, so a file cannot disagree with an edit.
- .map(Clip::tidy)
- .collect()
+ .map(Arc::new)
+ .collect();
+ Some(timeline)
}
-/// Rebuilds a project from a document. Returns None only when there is
-/// nothing recognisable to load at all.
-pub fn from_document(document: &Value) -> Option<Project> {
- if !document.is_object() || document_version(document) > DOCUMENT_VERSION {
+/// One clip settled, or `None` for one with nowhere to live: no id, a
+/// track that vanished, or - for the kinds that come from the bin - media
+/// that is gone. Titles and layers have no media and need none.
+fn settle_clip(
+ mut clip: Clip,
+ tracks: &[crate::model::Track],
+ media: &[MediaItem],
+) -> Option<Clip> {
+ use crate::model::ClipKind;
+ if clip.id.is_empty() {
return None;
}
- let media = read_media(document.get("media"));
-
- // The document's frame, as every build has written it at the top level.
- // The default for any timeline that does not carry its own - which is
- // every timeline in a document from before they could.
- let shared = read_video(document.get("video"), VideoSettings::default());
-
- // The timelines array is the source of truth when present and usable; a
- // file from before multiple timelines loads its flat fields as the one
- // timeline they always were.
- let mut timelines: Vec<Arc<Timeline>> = Vec::new();
- if let Some(entries) = document.get("timelines").and_then(Value::as_array) {
- for entry in entries {
- let Some(id) = entry.get("id").and_then(Value::as_str) else {
- continue;
- };
- if timelines.iter().any(|existing| existing.id == id) {
- continue;
- }
- let tracks = read_tracks(entry.get("tracks"));
- if tracks.is_empty() {
- continue;
+ if !tracks.iter().any(|track| track.id == clip.track_id) {
+ return None;
+ }
+ match clip.kind {
+ ClipKind::Text | ClipKind::Layer => clip.media_id.clear(),
+ ClipKind::Video | ClipKind::Audio | ClipKind::Image => {
+ if !media.iter().any(|item| item.id == clip.media_id) {
+ return None;
}
- let clips = read_clips(entry.get("clips"), &tracks, &media);
- timelines.push(Arc::new(Timeline {
- id: id.to_owned(),
- name: text(entry.get("name"), "Timeline"),
- video: read_video(entry.get("video"), shared),
- tracks,
- clips: clips.into_iter().map(Arc::new).collect(),
- }));
}
}
- if timelines.is_empty() {
- let tracks = read_tracks(document.get("tracks"));
- if tracks.is_empty() {
- return None;
- }
- let clips = read_clips(document.get("clips"), &tracks, &media);
- timelines.push(Arc::new(Timeline {
- id: "TL1".to_owned(),
- name: "Timeline 1".to_owned(),
- video: shared,
- tracks,
- clips: clips.into_iter().map(Arc::new).collect(),
- }));
+ if clip.kind != ClipKind::Text {
+ clip.text = None;
}
-
- let active_timeline_id = document
- .get("activeTimelineId")
- .and_then(Value::as_str)
- .filter(|id| timelines.iter().any(|timeline| timeline.id == *id))
- .unwrap_or(&timelines[0].id)
- .to_owned();
-
- let fonts = document
- .get("fonts")
- .and_then(Value::as_array)
- .map(|entries| {
- entries
- .iter()
- .filter_map(|entry| {
- Some(CustomFont {
- family: entry.get("family")?.as_str()?.to_owned(),
- path: entry.get("path")?.as_str()?.to_owned(),
- })
- })
- .collect()
- })
- .unwrap_or_default();
-
- Some(Project {
- media,
- fonts,
- timelines,
- active_timeline_id,
- })
+ Some(clip.tidy())
}
/// Settings the host manages around the edit: the manifest's identity fields.
@@ -482,100 +351,10 @@ pub fn to_document(settings: &DocumentSettings, project: &Project) -> Value {
serde_json::to_value(&project.timelines).expect("serialises"),
);
document.insert("activeTimelineId".into(), json!(project.active_timeline_id));
- Value::Object(document)
-}
-
-/// The clip's own keys. Tolerant like everything else here: an entry naming
-/// a property this build does not have, or sitting outside the clip, is
-/// dropped rather than failing the load, and the survivors come back in the
-/// order the model promises.
-fn read_keys(raw: Option<&Value>) -> Vec<ClipKey> {
- let Some(entries) = raw.and_then(Value::as_array) else {
- return Vec::new();
- };
- let mut keys: Vec<ClipKey> = entries
- .iter()
- .filter_map(|entry| {
- let property = KeyProperty::from_name(entry.get("property")?.as_str()?)?;
- let at = number(entry.get("at"), -1.0);
- let value = number(entry.get("value"), f64::NAN);
- (0.0..=1.0)
- .contains(&at)
- .then_some(ClipKey {
- property,
- at,
- value,
- ease: read_ease(entry.get("ease")),
- })
- .filter(|key| key.value.is_finite())
- })
- .collect();
- keys.sort_by(|a, b| {
- (a.property as u8)
- .cmp(&(b.property as u8))
- .then_with(|| a.at.total_cmp(&b.at))
- });
- keys
-}
-
-/// A `video` block - the top-level one, or a timeline's own - falling back
-/// to `fallback` a field at a time. A block naming a zero dimension or rate
-/// gets the fallback for that field rather than the zero: a document that
-/// has been hand-edited into nonsense should still open at a size that is a
-/// size.
-fn read_video(value: Option<&Value>, fallback: VideoSettings) -> VideoSettings {
- let positive_u32 = |key: &str, fallback: u32| {
- value
- .and_then(|block| block.get(key))
- .and_then(Value::as_u64)
- .filter(|n| *n > 0)
- .and_then(|n| u32::try_from(n).ok())
- .unwrap_or(fallback)
- };
- let positive_i64 = |key: &str, fallback: i64| {
- value
- .and_then(|block| block.get(key))
- .and_then(Value::as_i64)
- .filter(|n| *n > 0)
- .unwrap_or(fallback)
- };
- VideoSettings {
- width: positive_u32("width", fallback.width),
- height: positive_u32("height", fallback.height),
- rate_num: positive_i64("rateNum", fallback.rate_num),
- rate_den: positive_i64("rateDen", fallback.rate_den),
- }
-}
-
-/// A key's easing, in either spelling.
-///
-/// Documents written before the curve editor name one of four shapes;
-/// documents written since carry the four control-point numbers. Both are
-/// read, and anything else is a straight line - the reader's standing rule
-/// is that a hand-edited file degrades to something openable.
-fn read_ease(value: Option<&Value>) -> KeyEase {
- match value {
- Some(Value::String(name)) => KeyEase::from_name(name),
- Some(Value::Array(points)) if points.len() == 4 => KeyEase([
- number(points.first(), 0.0),
- number(points.get(1), 0.0),
- number(points.get(2), 1.0),
- number(points.get(3), 1.0),
- ])
- .sane(),
- _ => KeyEase::LINEAR,
+ // Whatever a newer or a different build put at the top level, back
+ // where it was; never over a field this writer owns.
+ for (key, value) in &project.extra {
+ document.entry(key.clone()).or_insert_with(|| value.clone());
}
-}
-
-/// A named animation on a slot, or None when the entry says nothing usable.
-fn read_animation(value: Option<&Value>) -> Option<ClipAnimation> {
- let value = value?;
- let preset = value.get("preset")?.as_str()?.trim().to_owned();
- if preset.is_empty() {
- return None;
- }
- Some(ClipAnimation {
- preset,
- duration: number(value.get("duration"), 0.5).max(0.0),
- })
+ Value::Object(document)
}
diff --git a/src/crates/concat-project/src/lib.rs b/src/crates/concat-project/src/lib.rs
index bacac42a..11f8d991 100644
--- a/src/crates/concat-project/src/lib.rs
+++ b/src/crates/concat-project/src/lib.rs
@@ -663,6 +663,135 @@ mod tests {
assert_eq!(editor.project().active().clips[0].volume, 1.0);
}
+ #[test]
+ fn fields_this_build_does_not_know_survive_a_round_trip() {
+ let (editor, _, clip_id) = fixture();
+ let mut document = editor.to_document(&settings());
+ document["futureSetting"] = json!({ "on": true });
+ document["timelines"][0]["colourSpace"] = json!("rec709");
+ document["timelines"][0]["tracks"][0]["name"] = json!("Dialogue");
+ document["timelines"][0]["clips"][0]["mask"] = json!({ "shape": "ellipse" });
+ document["media"][0]["proxy"] = json!("/proxies/a.mp4");
+
+ let loaded = Editor::from_document(&document).expect("loads");
+ assert_eq!(
+ loaded
+ .project()
+ .active()
+ .clip(&clip_id)
+ .expect("clip")
+ .extra["mask"]["shape"],
+ "ellipse"
+ );
+ let saved = loaded.to_document(&settings());
+ assert_eq!(saved["futureSetting"]["on"], true);
+ assert_eq!(saved["timelines"][0]["colourSpace"], "rec709");
+ assert_eq!(saved["timelines"][0]["tracks"][0]["name"], "Dialogue");
+ assert_eq!(
+ saved["timelines"][0]["clips"][0]["mask"]["shape"],
+ "ellipse"
+ );
+ assert_eq!(saved["media"][0]["proxy"], "/proxies/a.mp4");
+ // The flat mirror carries the clip's unknown field too: it is the
+ // same clip serialised twice.
+ assert_eq!(saved["clips"][0]["mask"]["shape"], "ellipse");
+ // And the writer's own fields are never duplicated from `extra`.
+ assert_eq!(
+ loaded.project().extra.len(),
+ 1,
+ "{:?}",
+ loaded.project().extra
+ );
+ }
+
+ #[test]
+ fn a_timeline_without_its_own_frame_takes_the_documents() {
+ let document = json!({
+ "name": "Old", "version": 1,
+ "video": { "width": 1080, "height": 1920, "rateNum": 60, "rateDen": 1 },
+ "media": [],
+ "timelines": [
+ { "id": "TL1", "name": "Vertical",
+ "tracks": [{ "id": "T1", "visible": true, "muted": false }], "clips": [] },
+ { "id": "TL2", "name": "Half", "video": { "width": 0, "height": 540 },
+ "tracks": [{ "id": "T2", "visible": true, "muted": false }], "clips": [] }
+ ],
+ "activeTimelineId": "TL2"
+ });
+ let editor = Editor::from_document(&document).expect("loads");
+ let timelines = &editor.project().timelines;
+ assert_eq!(
+ (timelines[0].video.width, timelines[0].video.height),
+ (1080, 1920)
+ );
+ assert_eq!(timelines[0].video.rate_num, 60);
+ // A zero width takes the document's; a stated height is kept.
+ assert_eq!(
+ (timelines[1].video.width, timelines[1].video.height),
+ (1080, 540)
+ );
+ assert_eq!(editor.project().active_timeline_id, "TL2");
+ }
+
+ #[test]
+ fn an_entry_the_reader_cannot_parse_is_dropped_not_the_document() {
+ let document = json!({
+ "name": "Mixed", "version": 1,
+ "media": [
+ { "id": "m1", "path": "/a.mp4", "kind": "hologram" },
+ { "id": "m2", "path": "/b.mp4", "kind": "audio", "audioTracks": "nope" },
+ { "path": "/no-id.mp4" }
+ ],
+ "tracks": [{ "id": "T1" }, { "visible": false }],
+ "clips": [
+ { "id": "c1", "trackId": "T1", "mediaId": "m1", "kind": "video",
+ "cutout": { "mode": "unknown" }, "keys": "garbage",
+ "transitionIn": { "id": "cross-fade" },
+ "animationIn": { "preset": " " },
+ "videoEffects": [{ "id": "sepia", "keys": { "amount": [ { "at": 0.5, "value": 1.0 }, { "at": 7.0, "value": 2.0 } ] } }, "not an effect"] },
+ { "id": "c2", "trackId": "T1", "mediaId": "m2", "kind": "audio", "start": "soon" }
+ ]
+ });
+ let editor = Editor::from_document(&document).expect("loads");
+ let project = editor.project();
+ assert_eq!(project.media.len(), 2, "the entry without an id is dropped");
+ assert_eq!(
+ project.media[0].kind,
+ MediaKind::Video,
+ "an unknown kind is video"
+ );
+ assert_eq!(
+ project.media[0].name, "/a.mp4",
+ "a nameless entry is called by its path"
+ );
+ assert!(
+ project.media[1].audio_tracks.is_empty(),
+ "a list that is not one is empty"
+ );
+ let timeline = project.active();
+ assert_eq!(
+ timeline.tracks.len(),
+ 1,
+ "the lane without an id is dropped"
+ );
+ let ids: Vec<&str> = timeline.clips.iter().map(|clip| clip.id.as_str()).collect();
+ assert_eq!(ids, ["c1"], "a clip whose start is not a number is dropped");
+ let clip = timeline.clip("c1").expect("c1");
+ assert!(
+ clip.cutout.is_none(),
+ "a cutout that does not parse is no cutout"
+ );
+ assert!(clip.keys.is_empty());
+ assert_eq!(clip.transition_in.as_ref().expect("kept").duration, 1.0);
+ assert!(clip.animation_in.is_none(), "a preset with no name is none");
+ assert_eq!(clip.video_effects.len(), 1);
+ assert_eq!(
+ clip.video_effects[0].keys["amount"].len(),
+ 1,
+ "the out-of-range key is dropped"
+ );
+ }
+
#[test]
fn rearranged_pieces_refuse_to_merge() {
let (mut editor, _, clip_id) = fixture();
@@ -2285,6 +2414,7 @@ mod tests {
has_audio: false,
audio_tracks: vec![],
placeholder: false,
+ extra: Default::default(),
});
let missing = project.missing_media();
@@ -2320,6 +2450,7 @@ mod tests {
has_audio: false,
audio_tracks: vec![],
placeholder: false,
+ extra: Default::default(),
});
let missing = project.missing_media();
diff --git a/src/crates/concat-project/src/model.rs b/src/crates/concat-project/src/model.rs
index 2f712870..417011c4 100644
--- a/src/crates/concat-project/src/model.rs
+++ b/src/crates/concat-project/src/model.rs
@@ -14,14 +14,16 @@
use std::collections::BTreeMap;
use std::sync::Arc;
-use serde::{Deserialize, Serialize};
+use serde::{Deserialize, Deserializer, Serialize};
+use serde_json::{Map, Value};
/// What a piece of media is. A still is not a video with one frame: it has no
/// intrinsic duration, so its length on a timeline is editorial.
-#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
+#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MediaKind {
/// Moving pictures, with or without embedded sound.
+ #[default]
Video,
/// Sound only; nothing to composite.
Audio,
@@ -85,8 +87,8 @@ pub struct AudioTrack {
/// One entry in the media bin: a file the user imported, plus what the host's
/// probe learned about it. The probe metadata is stored, not re-derived, so a
/// document opens meaningfully even when the file itself is missing.
-#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
+#[derive(Clone, PartialEq, Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
pub struct MediaItem {
/// Minted by the editor ("m1", "m2", ...) and never re-issued, even
/// across a save/load - clips reference media by this id.
@@ -100,6 +102,7 @@ pub struct MediaItem {
pub duration: Option<f64>,
/// What the probe decided the file is; fixes which [`ClipKind`] its
/// clips get.
+ #[serde(deserialize_with = "wire::media_kind")]
pub kind: MediaKind,
/// Pixel width, when the file has pictures and the probe found one.
pub width: Option<u32>,
@@ -122,6 +125,7 @@ pub struct MediaItem {
/// what lets a clip choose between them. Skipped when empty, so
/// documents without such media stay byte-identical.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
+ #[serde(deserialize_with = "wire::list")]
pub audio_tracks: Vec<AudioTrack>,
/// True when this item is a template slot: a stand-in whose metadata says
/// what kind of media belongs here, waiting to be replaced by the user's
@@ -130,6 +134,16 @@ pub struct MediaItem {
/// false, so documents without templates stay byte-identical.
#[serde(default, skip_serializing_if = "is_false")]
pub placeholder: bool,
+ /// Fields this build does not know, kept so a document written by a
+ /// newer or a different build round-trips through this one intact.
+ #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
+ pub extra: Map<String, Value>,
+}
+
+/// Half a second: what an animation preset lasts when its entry does not
+/// say.
+fn default_animation_duration() -> f64 {
+ 0.5
}
fn unity() -> f64 {
@@ -146,7 +160,7 @@ fn is_false(value: &bool) -> bool {
/// A lane. Deliberately untyped: any media goes on any track.
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
+#[serde(rename_all = "camelCase", default)]
pub struct Track {
/// Minted per timeline ("t5", or "T1".."T4" for the first timeline's
/// starter lanes); never shared between timelines.
@@ -155,6 +169,20 @@ pub struct Track {
pub visible: bool,
/// Audio on this track is silent when true.
pub muted: bool,
+ /// Fields this build does not know, kept so they round-trip.
+ #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
+ pub extra: Map<String, Value>,
+}
+
+impl Default for Track {
+ fn default() -> Self {
+ Track {
+ id: String::new(),
+ visible: true,
+ muted: false,
+ extra: Map::new(),
+ }
+ }
}
/// One applied audio filter or video effect: a catalogue id plus whatever
@@ -177,7 +205,11 @@ pub struct AppliedFilter {
/// parameter name, each `at` a fraction of the clip like a `ClipKey`'s.
/// A parameter with keys is played from them and its `params` entry is
/// only what it falls back to with the keys taken off.
- #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ #[serde(
+ default,
+ deserialize_with = "wire::runs",
+ skip_serializing_if = "BTreeMap::is_empty"
+ )]
pub keys: BTreeMap<String, Vec<ParamKey>>,
}
@@ -548,9 +580,26 @@ pub struct ClipAnimation {
/// The shape's name, e.g. "Fade".
pub preset: String,
/// Seconds the shape takes, for In and Out; ignored by a Combo.
+ #[serde(default = "default_animation_duration")]
pub duration: f64,
}
+impl ClipAnimation {
+ /// The entry, or nothing for one naming no preset.
+ pub fn tidy(mut self) -> Option<ClipAnimation> {
+ self.preset = self.preset.trim().to_owned();
+ if self.preset.is_empty() {
+ return None;
+ }
+ self.duration = if self.duration.is_finite() {
+ self.duration.max(0.0)
+ } else {
+ default_animation_duration()
+ };
+ Some(self)
+ }
+}
+
/// Which property a user-set key belongs to.
///
/// Five of the six are the picture's; the sixth is the mix's. They are one
@@ -624,10 +673,33 @@ impl KeyProperty {
/// Serialised as a bare array: `"ease": [0.42, 0, 0.58, 1]`. Documents
/// written before the curve editor spell it `"linear"` / `"in"` / `"out"` /
/// `"inOut"` instead, and `from_value` still reads those.
-#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
+#[derive(Clone, Copy, PartialEq, Debug, Serialize)]
#[serde(transparent)]
pub struct KeyEase(pub [f64; 4]);
+impl<'de> Deserialize<'de> for KeyEase {
+ /// Either spelling, and a straight line for anything else: the
+ /// reader's standing rule is that a hand-edited file degrades to
+ /// something openable, and a key that still moves is better than one
+ /// that fails its clip.
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ #[derive(Deserialize)]
+ #[serde(untagged)]
+ enum Wire {
+ Name(String),
+ Points(Vec<f64>),
+ }
+ let value = Value::deserialize(deserializer)?;
+ Ok(match serde_json::from_value::<Wire>(value) {
+ Ok(Wire::Name(name)) => KeyEase::from_name(&name),
+ Ok(Wire::Points(points)) if points.len() == 4 => {
+ KeyEase([points[0], points[1], points[2], points[3]]).sane()
+ }
+ _ => KeyEase::LINEAR,
+ })
+ }
+}
+
impl Default for KeyEase {
fn default() -> Self {
KeyEase::LINEAR
@@ -743,6 +815,7 @@ pub struct Transition {
/// Which transition from the catalogue, e.g. "cross-fade".
pub id: String,
/// Seconds the transition covers.
+ #[serde(default = "unity")]
pub duration: f64,
}
@@ -787,6 +860,7 @@ pub struct TextStyle {
/// Fill colour as a CSS hex string, e.g. "#ffffff".
pub color: String,
/// Line alignment within the block; see [`TextAlign`].
+ #[serde(deserialize_with = "wire::text_align")]
pub align: TextAlign,
/// Opacity of the whole title in 0..=1, multiplied with the clip's own
/// opacity.
@@ -812,6 +886,26 @@ pub struct TextStyle {
pub max_width: f64,
}
+impl TextStyle {
+ /// Every number pulled into the range a title can be drawn at: a
+ /// hand-edited zero size would render an invisible title, and lines
+ /// cannot collapse onto each other.
+ pub fn tidy(mut self) -> TextStyle {
+ fn finite(value: f64, fallback: f64) -> f64 {
+ if value.is_finite() { value } else { fallback }
+ }
+ let base = TextStyle::default();
+ self.font_size = finite(self.font_size, base.font_size).clamp(0.01, 1.0);
+ self.font_weight = finite(self.font_weight, base.font_weight).clamp(100.0, 900.0);
+ self.opacity = finite(self.opacity, base.opacity).clamp(0.0, 1.0);
+ self.stroke_width = finite(self.stroke_width, base.stroke_width).max(0.0);
+ self.line_height = finite(self.line_height, base.line_height).max(0.5);
+ self.tracking = finite(self.tracking, base.tracking);
+ self.max_width = finite(self.max_width, base.max_width).max(0.0);
+ self
+ }
+}
+
impl Default for TextStyle {
fn default() -> Self {
Self {
@@ -834,6 +928,102 @@ impl Default for TextStyle {
}
}
+/// Reading with tolerance. The document reader's standing rule is that a
+/// hand-edited or older file degrades to something openable: a list keeps
+/// the entries that parse and drops the rest, an optional keeps a value
+/// that parses and is otherwise nothing, and a kind this build has never
+/// heard of falls back to the plainest one. Every helper reads a
+/// [`serde_json::Value`] first, so nothing here can fail the whole load.
+pub(crate) mod wire {
+ use std::collections::BTreeMap;
+
+ use serde::de::DeserializeOwned;
+ use serde::{Deserialize, Deserializer};
+ use serde_json::Value;
+
+ use super::{ClipKind, MediaKind, ParamKey, TextAlign};
+
+ /// The entries of a list that parse, in order; not a list at all is
+ /// an empty one.
+ pub fn list<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
+ where
+ D: Deserializer<'de>,
+ T: DeserializeOwned,
+ {
+ let value = Value::deserialize(deserializer)?;
+ Ok(match value {
+ Value::Array(items) => items
+ .into_iter()
+ .filter_map(|item| serde_json::from_value(item).ok())
+ .collect(),
+ _ => Vec::new(),
+ })
+ }
+
+ /// [`list`], as an optional that is none when nothing parsed.
+ pub fn maybe_list<'de, D, T>(deserializer: D) -> Result<Option<Vec<T>>, D::Error>
+ where
+ D: Deserializer<'de>,
+ T: DeserializeOwned,
+ {
+ let items: Vec<T> = list(deserializer)?;
+ Ok((!items.is_empty()).then_some(items))
+ }
+
+ /// A value that parses, or nothing.
+ pub fn maybe<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
+ where
+ D: Deserializer<'de>,
+ T: DeserializeOwned,
+ {
+ let value = Value::deserialize(deserializer)?;
+ Ok(serde_json::from_value(value).ok())
+ }
+
+ /// An effect's parameter keys: a run per parameter name, each run the
+ /// keys of it that parse, runs with none dropped.
+ pub fn runs<'de, D>(deserializer: D) -> Result<BTreeMap<String, Vec<ParamKey>>, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ let value = Value::deserialize(deserializer)?;
+ let Value::Object(runs) = value else {
+ return Ok(BTreeMap::new());
+ };
+ Ok(runs
+ .into_iter()
+ .filter_map(|(name, run)| {
+ let keys: Vec<ParamKey> = match run {
+ Value::Array(items) => items
+ .into_iter()
+ .filter_map(|item| serde_json::from_value(item).ok())
+ .collect(),
+ _ => Vec::new(),
+ };
+ (!keys.is_empty()).then_some((name, keys))
+ })
+ .collect())
+ }
+
+ /// A clip kind by name, video for a name this build does not know.
+ pub fn clip_kind<'de, D: Deserializer<'de>>(deserializer: D) -> Result<ClipKind, D::Error> {
+ let value = Value::deserialize(deserializer)?;
+ Ok(serde_json::from_value(value).unwrap_or(ClipKind::Video))
+ }
+
+ /// A media kind by name, video for a name this build does not know.
+ pub fn media_kind<'de, D: Deserializer<'de>>(deserializer: D) -> Result<MediaKind, D::Error> {
+ let value = Value::deserialize(deserializer)?;
+ Ok(serde_json::from_value(value).unwrap_or(MediaKind::Video))
+ }
+
+ /// A text alignment by name, centred for one this build does not know.
+ pub fn text_align<'de, D: Deserializer<'de>>(deserializer: D) -> Result<TextAlign, D::Error> {
+ let value = Value::deserialize(deserializer)?;
+ Ok(serde_json::from_value(value).unwrap_or(TextAlign::Center))
+ }
+}
+
/// The ranges a clip's numbers are held in. One set, used by every
/// command that sets a value and by the document reader through
/// [`Clip::tidy`], so a file and an edit can never disagree about what is
@@ -871,7 +1061,7 @@ pub mod ranges {
/// timing, mix, transform, and effects. Everything an edit decision touches
/// lives here, which is why most commands are clip commands.
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
+#[serde(rename_all = "camelCase", default)]
pub struct Clip {
/// Minted by the editor ("c1", "c2", ...); how every command names its
/// target. Survives splits - the head keeps the id - and merges.
@@ -886,6 +1076,7 @@ pub struct Clip {
pub name: String,
/// What this clip renders as. Follows the media's kind, and is rewritten
/// when a template slot is filled with a different kind of file.
+ #[serde(deserialize_with = "wire::clip_kind")]
pub kind: ClipKind,
/// Seconds from the start of the timeline.
pub start: f64,
@@ -923,18 +1114,22 @@ pub struct Clip {
/// Speed as it changes over the clip: points of `(at, speed)`, `at` a
/// fraction of the clip's timeline length. None is the constant rate.
#[serde(default, skip_serializing_if = "Option::is_none")]
+ #[serde(deserialize_with = "wire::maybe_list")]
pub speed_curve: Option<Vec<SpeedPoint>>,
/// Played backwards.
#[serde(default, skip_serializing_if = "is_false")]
pub reverse: bool,
/// How the clip comes in: a named shape over its first seconds.
#[serde(default, skip_serializing_if = "Option::is_none")]
+ #[serde(deserialize_with = "wire::maybe")]
pub animation_in: Option<ClipAnimation>,
/// How it goes out: a named shape over its last seconds.
#[serde(default, skip_serializing_if = "Option::is_none")]
+ #[serde(deserialize_with = "wire::maybe")]
pub animation_out: Option<ClipAnimation>,
/// A shape over its whole length.
#[serde(default, skip_serializing_if = "Option::is_none")]
+ #[serde(deserialize_with = "wire::maybe")]
pub animation_combo: Option<ClipAnimation>,
/// The user's own keys, sorted by property and then by `at`. Empty is a
/// clip whose properties are the constants above.
@@ -944,6 +1139,7 @@ pub struct Clip {
/// to, so a clip can carry both a hand-keyed scale and a Fade preset
/// without either having to know about the other.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
+ #[serde(deserialize_with = "wire::list")]
pub keys: Vec<ClipKey>,
/// Mirrored left to right.
#[serde(default, skip_serializing_if = "is_false")]
@@ -958,19 +1154,23 @@ pub struct Clip {
/// What is cut off each edge of the source before it is fitted, as
/// fractions of the source's width and height.
#[serde(default, skip_serializing_if = "Option::is_none")]
+ #[serde(deserialize_with = "wire::maybe")]
pub crop: Option<Crop>,
/// The background taken away by a mask rather than a key colour; see
/// [`Cutout`]. Keying by colour is a package on `video_effects`.
#[serde(default, skip_serializing_if = "Option::is_none")]
+ #[serde(deserialize_with = "wire::maybe")]
pub cutout: Option<Cutout>,
/// Keep voices at their natural pitch when `speed` is not 1. On by
/// default; off gives the tape-machine chipmunk/slow-motion sound.
pub preserve_pitch: bool,
/// Audio filters, in order - order is audible.
#[serde(default)]
+ #[serde(deserialize_with = "wire::list")]
pub filters: Vec<AppliedFilter>,
/// Video effects, in order - the visual sibling of `filters`.
#[serde(default)]
+ #[serde(deserialize_with = "wire::list")]
pub video_effects: Vec<AppliedFilter>,
/// Which of the media's audio streams this clip plays, by the stream's
/// index in the file - see [`MediaItem::audio_tracks`]. None is the first
@@ -986,10 +1186,24 @@ pub struct Clip {
pub detached_from: Option<String>,
/// The transition on the cut into this clip, if any.
#[serde(default, skip_serializing_if = "Option::is_none")]
+ #[serde(deserialize_with = "wire::maybe")]
pub transition_in: Option<Transition>,
/// The overlay, when this is a text clip.
#[serde(default, skip_serializing_if = "Option::is_none")]
+ #[serde(deserialize_with = "wire::maybe")]
pub text: Option<TextStyle>,
+ /// Fields this build does not know, kept so a document written by a
+ /// newer or a different build round-trips through this one intact.
+ #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
+ pub extra: Map<String, Value>,
+}
+
+impl Default for Clip {
+ /// What a document entry starts from before its own fields land on
+ /// it: [`Clip::blank`] with no id, on no track, one second of video.
+ fn default() -> Self {
+ Clip::blank("", "", ClipKind::Video, "clip", 0.0, 1.0)
+ }
}
impl Clip {
@@ -1044,6 +1258,7 @@ impl Clip {
detached_from: None,
transition_in: None,
text: None,
+ extra: Map::new(),
}
}
@@ -1093,8 +1308,24 @@ impl Clip {
transition.duration = finite(transition.duration, 1.0).max(MIN_TRANSITION);
}
self.keys
- .retain(|key| key.at.is_finite() && key.value.is_finite());
+ .retain(|key| (0.0..=1.0).contains(&key.at) && key.value.is_finite());
self.sort_keys();
+ for chain in [&mut self.filters, &mut self.video_effects] {
+ for entry in chain.iter_mut() {
+ entry.sort_keys();
+ }
+ }
+ for slot in [
+ &mut self.animation_in,
+ &mut self.animation_out,
+ &mut self.animation_combo,
+ ] {
+ *slot = slot.take().and_then(ClipAnimation::tidy);
+ }
+ self.text = self.text.take().map(TextStyle::tidy);
+ if self.muted == Some(false) {
+ self.muted = None;
+ }
self
}
@@ -1246,7 +1477,7 @@ impl Clip {
/// One timeline: a name and its lanes and clips. Every operation takes the
/// project and works on whichever timeline is active.
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
+#[serde(rename_all = "camelCase", default)]
pub struct Timeline {
/// Minted by the editor ("tl2", ...), except the founding "TL1".
pub id: String,
@@ -1260,6 +1491,7 @@ pub struct Timeline {
pub video: VideoSettings,
/// The lanes, top to bottom. Never empty - `RemoveTrack` keeps a floor
/// of one.
+ #[serde(deserialize_with = "wire::list")]
pub tracks: Vec<Track>,
/// Every clip on this timeline, in insertion order, not time order -
/// readers must sort by `start` where order matters.
@@ -1268,7 +1500,24 @@ pub struct Timeline {
/// every command - copies one pointer per clip, and only the clip a
/// command then writes to is copied for real ([`Arc::make_mut`] in
/// [`Timeline::clip_mut`]). Reading through the `Arc` is transparent.
+ #[serde(deserialize_with = "wire::list")]
pub clips: Vec<Arc<Clip>>,
+ /// Fields this build does not know, kept so they round-trip.
+ #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
+ pub extra: Map<String, Value>,
+}
+
+impl Default for Timeline {
+ fn default() -> Self {
+ Timeline {
+ id: String::new(),
+ name: "Timeline".to_owned(),
+ video: VideoSettings::default(),
+ tracks: Vec::new(),
+ clips: Vec::new(),
+ extra: Map::new(),
+ }
+ }
}
/// A timeline's output frame and rate.
@@ -1309,6 +1558,34 @@ impl VideoSettings {
self.rate_num as f64 / self.rate_den.max(1) as f64
}
+ /// This frame with every zero or negative field taken from `fallback`
+ /// instead: a document hand-edited into nonsense still opens at a size
+ /// that is a size.
+ pub fn or(self, fallback: VideoSettings) -> VideoSettings {
+ VideoSettings {
+ width: if self.width > 0 {
+ self.width
+ } else {
+ fallback.width
+ },
+ height: if self.height > 0 {
+ self.height
+ } else {
+ fallback.height
+ },
+ rate_num: if self.rate_num > 0 {
+ self.rate_num
+ } else {
+ fallback.rate_num
+ },
+ rate_den: if self.rate_den > 0 {
+ self.rate_den
+ } else {
+ fallback.rate_den
+ },
+ }
+ }
+
/// Whether every term is one a frame could actually have. A zero
/// dimension or rate is never a real setting, only a caller bug, and
/// writing one would poison the document until the next open.
@@ -1335,17 +1612,24 @@ pub struct CustomFont {
#[serde(rename_all = "camelCase")]
pub struct Project {
/// The bin: every imported file, shared by all timelines.
+ #[serde(default, deserialize_with = "wire::list")]
pub media: Vec<MediaItem>,
/// Fonts the user added from disk, available to every title.
+ #[serde(default, deserialize_with = "wire::list")]
pub fonts: Vec<CustomFont>,
/// Every timeline, in tab order. Always at least one. Behind `Arc` for
/// the reason [`Timeline::clips`] is: a command on one timeline leaves
/// the others shared with the undo snapshot.
+ #[serde(default, deserialize_with = "wire::list")]
pub timelines: Vec<Arc<Timeline>>,
/// Which timeline commands act on. Maintained by the command layer, so
/// it always names a member of `timelines`; [`Project::active`] degrades
/// to the first timeline if it somehow does not.
+ #[serde(default)]
pub active_timeline_id: String,
+ /// Top-level fields this build does not know, kept so they round-trip.
+ #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
+ pub extra: Map<String, Value>,
}
/// A media reference that points to a non-existent file.
@@ -1371,6 +1655,7 @@ impl Project {
Self {
media: Vec::new(),
fonts: Vec::new(),
+ extra: Map::new(),
timelines: vec![Arc::new(Timeline {
id: "TL1".to_owned(),
name: "Timeline 1".to_owned(),
@@ -1378,11 +1663,11 @@ impl Project {
tracks: (1..=4)
.map(|number| Track {
id: format!("T{number}"),
- visible: true,
- muted: false,
+ ..Track::default()
})
.collect(),
clips: Vec::new(),
+ extra: Map::new(),
})],
active_timeline_id: "TL1".to_owned(),
}
@@ -1429,6 +1714,14 @@ impl Project {
}
impl MediaItem {
+ /// A nameless entry is called by its path.
+ pub fn tidy(mut self) -> MediaItem {
+ if self.name.is_empty() {
+ self.name = self.path.clone();
+ }
+ self
+ }
+
/// Which row of `audio_tracks` a clip's `audio_stream` is: the named
/// stream's position, or the first row for a clip that names none or
/// names a stream this file does not have - the same fallback the