Skip to content

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

fix(project): cuts keep a reverse, numbers must be finite, the reader clamps like a command

Jareer4ee61f761e24
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 446415e7..8ac72c6b 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -42,8 +42,8 @@ Slint UI - is one Cargo workspace under `src/`.
| `src/crates/` | The engine (core, media, render, export, project), the host layer (`concat-host`, `concat-speech`), the CLI, and `concat`, the Slint editor window |
| `test/` | Media and analysis fixtures |
-[`ARCHITECTURE.md`](ARCHITECTURE.md) explains how these fit together and where
-the sharp edges are. Read it before touching the engine.
+[`src/README.md`](src/README.md) explains how the crates fit together and
+where the sharp edges are. Read it before touching the engine.
## Checks
diff --git a/src/.cargo/config.toml b/src/.cargo/config.toml
index 75413d2c..0fae32c9 100644
--- a/src/.cargo/config.toml
+++ b/src/.cargo/config.toml
@@ -1,24 +1,8 @@
-# Where the FFmpeg development build lives - machine configuration, not
-# repository configuration.
-#
-# Only the optional `ffi` feature of concat-media needs FFmpeg headers and
-# libraries at build time. A normal build - which talks to FFmpeg as a
-# subprocess - needs nothing here. Do not commit machine paths into this
-# file: rusty_ffmpeg panics on an FFMPEG_INCLUDE_DIR that does not exist,
-# which breaks `--features ffi` for everyone else.
-#
-# To build the ffi feature, set the variables in your own environment (or a
-# cargo config outside the repository):
-#
-# macOS / Linux, package-manager FFmpeg with dev files:
-# export FFMPEG_PKG_CONFIG_PATH="$(brew --prefix ffmpeg)/lib/pkgconfig"
-#
-# Windows, a -shared dev build (gyan.dev / BtbN) unpacked into vendor/:
-# FFMPEG_INCLUDE_DIR = <build>/include
-# FFMPEG_LIBS_DIR = <build>/lib
-# (Deliberately not FFMPEG_DLL_PATH: rusty_ffmpeg turns that into the
-# linker's /LIBPATH, which hunts for import libraries in bin/ where only
-# the DLLs live. The DLLs still have to be findable at run time.)
+# Where the FFmpeg development build lives is machine configuration, not
+# repository configuration: concat-media links FFmpeg through
+# ffmpeg-the-third, which finds it by pkg-config or by FFMPEG_DIR pointing
+# at an unpacked shared build. Set those in your own environment, never
+# here - a machine path committed to this file breaks every other checkout.
# No incremental caches. They are a speed-up for the second build of one
# crate and a tax on the disk for everything else: a session of edits across
diff --git a/src/README.md b/src/README.md
index 9730b2c6..ed88c99d 100644
--- a/src/README.md
+++ b/src/README.md
@@ -156,7 +156,7 @@ same JSON, with the token as `authorization: Bearer ...` metadata.
## Reading this codebase cold
-1. [`../ARCHITECTURE.md`](../ARCHITECTURE.md) - the map of the whole system. Read it first.
+1. The layout table and dependency arrows above - the map of the whole system.
2. `crates/*/src/lib.rs` - every crate opens with a `//!` block saying what it is for.
3. `cargo doc --open` - the generated API map of the whole engine.
diff --git a/src/crates/concat-host/src/projects.rs b/src/crates/concat-host/src/projects.rs
index e0c9fb26..d8571f38 100644
--- a/src/crates/concat-host/src/projects.rs
+++ b/src/crates/concat-host/src/projects.rs
@@ -179,8 +179,16 @@ pub fn save(path: &str, document: &serde_json::Value) -> Result<(), String> {
let encoded = serde_json::to_vec_pretty(document)
.map_err(|error| format!("could not encode the project: {error}"))?;
- std::fs::write(&temporary, encoded)
+ // Written, then flushed to the disk, then renamed: a rename is only
+ // atomic over bytes that have reached the platter. Without the sync a
+ // power cut after the rename can leave a zero-length manifest.
+ let mut file = std::fs::File::create(&temporary)
.map_err(|error| format!("could not write {}: {error}", temporary.display()))?;
+ std::io::Write::write_all(&mut file, &encoded)
+ .map_err(|error| format!("could not write {}: {error}", temporary.display()))?;
+ file.sync_all()
+ .map_err(|error| format!("could not flush {}: {error}", temporary.display()))?;
+ drop(file);
std::fs::rename(&temporary, &manifest)
.map_err(|error| format!("could not replace {}: {error}", manifest.display()))
diff --git a/src/crates/concat-host/src/session.rs b/src/crates/concat-host/src/session.rs
index 4d8c443b..70985265 100644
--- a/src/crates/concat-host/src/session.rs
+++ b/src/crates/concat-host/src/session.rs
@@ -80,6 +80,13 @@ impl Session {
None if projects::is_settings_only(&document) => {
Editor::with_video(settings.video())
}
+ None if concat_project::document_version(&document)
+ > concat_project::DOCUMENT_VERSION =>
+ {
+ return Err(format!(
+ "{path} was saved by a newer Concat than this one: update to open it"
+ ));
+ }
None => {
return Err(format!("{path} holds a document this build cannot read"));
}
diff --git a/src/crates/concat-project/src/commands.rs b/src/crates/concat-project/src/commands.rs
index b4d67c10..fb1e6e6f 100644
--- a/src/crates/concat-project/src/commands.rs
+++ b/src/crates/concat-project/src/commands.rs
@@ -25,19 +25,19 @@ const DEFAULT_IMAGE_DURATION: f64 = 5.0;
const DEFAULT_TEXT_DURATION: f64 = 4.0;
/// How long a layer covers when first placed. Editorial default, not a fact.
const DEFAULT_LAYER_DURATION: f64 = 5.0;
-const MIN_CLIP_DURATION: f64 = 1.0 / 60.0;
+pub(crate) const MIN_CLIP_DURATION: f64 = 1.0 / 60.0;
/// Default hold for a CapCut-style freeze when the caller omits duration.
const DEFAULT_FREEZE_DURATION: f64 = 1.0;
/// The engine's speed range (concat-media `SPEED_RANGE`), verbatim.
-const MIN_SPEED: f64 = 0.0625;
-const MAX_SPEED: f64 = 16.0;
-const MIN_SCALE: f64 = 0.05;
-const MAX_SCALE: f64 = 8.0;
+pub(crate) const MIN_SPEED: f64 = 0.0625;
+pub(crate) const MAX_SPEED: f64 = 16.0;
+pub(crate) const MIN_SCALE: f64 = 0.05;
+pub(crate) const MAX_SCALE: f64 = 8.0;
/// How far a picture may be pulled along one axis: a tenth to ten times
/// its fitted extent, which covers every squash and every banner.
pub(crate) const MIN_STRETCH: f64 = 0.1;
pub(crate) const MAX_STRETCH: f64 = 10.0;
-const MAX_OFFSET: f64 = 3.0;
+pub(crate) const MAX_OFFSET: f64 = 3.0;
/// How far apart two clips may sit and still count as touching, in seconds.
const JOIN_EPSILON: f64 = 1e-6;
@@ -97,6 +97,12 @@ pub struct ClipPatch {
pub opacity: Option<f64>,
/// New pitch-preservation setting, taken as sent.
pub preserve_pitch: Option<bool>,
+ /// Whether the clip's own sound is silenced: true mutes it, false lets
+ /// it play again. A detach sets this on the video it took the sound
+ /// from, so this is also how a video whose detached sound was later
+ /// deleted gets its voice back.
+ #[serde(default)]
+ pub muted: Option<bool>,
/// Play backwards.
#[serde(default)]
pub reverse: Option<bool>,
@@ -665,6 +671,10 @@ pub enum CommandError {
/// [`Command::RemoveTimeline`] would have deleted the last timeline.
#[error("A project needs at least one timeline.")]
LastTimeline,
+ /// A number in the command is NaN or infinite. No edit means one, and
+ /// one stored would poison every duration and key that touched it.
+ #[error("A number in that edit is not finite.")]
+ NotANumber,
}
/// Mints ids. Owned by the editor so restored projects advance it past every
@@ -798,17 +808,139 @@ fn first_line(content: &str) -> String {
}
/// "Track 5" from the highest number already in use, not from the count.
+/// Only names of the exact shape `"{name} N"` count: a renamed "Timeline 2
+/// v10" is somebody's own name, not a number in the sequence.
fn next_numbered(name: &str, existing: impl Iterator<Item = String>) -> String {
let highest = existing
.filter_map(|candidate| {
- let digits: String = candidate.chars().filter(char::is_ascii_digit).collect();
- digits.parse::<u64>().ok()
+ candidate
+ .strip_prefix(name)
+ .and_then(|rest| rest.strip_prefix(' '))
+ .and_then(|digits| digits.parse::<u64>().ok())
})
.max()
.unwrap_or(0);
format!("{name} {}", highest + 1)
}
+impl Command {
+ /// True when any number in the command is NaN or infinite. JSON cannot
+ /// spell one, but a caller in Rust can, and `NaN.clamp()` is NaN: one
+ /// stored would poison every duration and key it touched, and the
+ /// document reader would only repair it on the next load.
+ pub fn has_non_finite(&self) -> bool {
+ fn bad(values: impl IntoIterator<Item = f64>) -> bool {
+ values.into_iter().any(|value| !value.is_finite())
+ }
+ fn bad_stroke(stroke: &Stroke) -> bool {
+ bad([stroke.size]) || bad(stroke.at) || stroke.points.iter().any(|point| bad(*point))
+ }
+ fn bad_chain(chain: &[AppliedFilter]) -> bool {
+ chain.iter().any(|entry| {
+ bad(entry.params.values().copied())
+ || entry
+ .keys
+ .values()
+ .flatten()
+ .any(|key| bad([key.at, key.value]) || bad(key.ease.0))
+ })
+ }
+ match self {
+ Command::Batch { commands } => commands.iter().any(Command::has_non_finite),
+ Command::AddMedia { item } | Command::FillSlot { item, .. } => {
+ bad(item.duration) || bad(item.frame_rate)
+ }
+ Command::AddClip { start, .. } | Command::AddClipAtFirstFree { start, .. } => {
+ bad([*start])
+ }
+ Command::AddTextClip {
+ start,
+ duration,
+ offset_y,
+ ..
+ } => bad([*start]) || bad(*duration) || bad(*offset_y),
+ Command::AddLayerClip {
+ start, duration, ..
+ } => bad([*start]) || bad(*duration),
+ Command::SetClipSpeedCurve { curve, .. } => bad(curve
+ .iter()
+ .flatten()
+ .flat_map(|point| [point.at, point.speed])),
+ Command::SetClipAnimation { animation, .. } => {
+ bad(animation.iter().map(|animation| animation.duration))
+ }
+ Command::SetClipKey {
+ at, value, ease, ..
+ }
+ | Command::SetEffectKey {
+ at, value, ease, ..
+ } => bad([*at, *value]) || bad(ease.0),
+ Command::ClearClipKey { at, .. } | Command::ClearEffectKey { at, .. } => bad([*at]),
+ Command::SetClipCutout { cutout, .. } => cutout.as_ref().is_some_and(|cutout| {
+ bad([cutout.feather]) || cutout.strokes.iter().any(bad_stroke)
+ }),
+ Command::AddCutoutStroke { stroke, .. } => bad_stroke(stroke),
+ Command::MoveClips { moves } => bad(moves.iter().map(|wanted| wanted.start)),
+ Command::TrimClip { delta, .. } => bad([*delta]),
+ Command::SplitClips { time, .. } => bad([*time]),
+ Command::FreezeFrame { time, duration, .. } => bad([*time]) || bad(*duration),
+ Command::UpdateClip { patch, .. } => {
+ bad(patch.volume)
+ || bad(patch.fade_in)
+ || bad(patch.fade_out)
+ || bad(patch.opacity)
+ || patch
+ .crop
+ .iter()
+ .flatten()
+ .any(|crop| bad([crop.left, crop.top, crop.right, crop.bottom]))
+ || patch.filters.as_deref().is_some_and(bad_chain)
+ || patch.video_effects.as_deref().is_some_and(bad_chain)
+ }
+ Command::SetClipSpeed { speed, .. } => bad([*speed]),
+ Command::SetClipTransform {
+ scale,
+ offset_x,
+ offset_y,
+ rotation,
+ stretch_x,
+ stretch_y,
+ ..
+ } => bad([scale, offset_x, offset_y, rotation, stretch_x, stretch_y]
+ .into_iter()
+ .flatten()
+ .copied()),
+ _ => false,
+ }
+ }
+}
+
+/// A rotation kept in (-180, 180] so a full drag never accumulates turns.
+pub(crate) fn wrap_rotation(degrees: f64) -> f64 {
+ let wrapped = ((degrees % 360.0) + 540.0) % 360.0 - 180.0;
+ if wrapped == -180.0 { 180.0 } else { wrapped }
+}
+
+/// Where each piece of a clip cut at `offset` begins in the source.
+/// Forwards, the head keeps its in-point and the tail starts `offset ×
+/// speed` later. Backwards, the head shows the late end of the span, so
+/// the tail keeps the in-point and the head's moves up past what the tail
+/// now shows. Either way the two pieces together show exactly what the
+/// whole did.
+fn split_source(
+ source_start: f64,
+ duration: f64,
+ speed: f64,
+ offset: f64,
+ reverse: bool,
+) -> (f64, f64) {
+ if reverse {
+ (source_start + (duration - offset) * speed, source_start)
+ } else {
+ (source_start, source_start + offset * speed)
+ }
+}
+
/// Why these clips cannot be merged, or None if they can. A sentence, because
/// a disabled button that will not say why is worse than no button.
pub fn why_not_merge(timeline: &Timeline, clip_ids: &[String]) -> Option<String> {
@@ -828,6 +960,21 @@ pub fn why_not_merge(timeline: &Timeline, clip_ids: &[String]) -> Option<String>
if clips.iter().any(|clip| clip.speed != clips[0].speed) {
return Some("Merged clips must play at the same speed.".to_owned());
}
+ if clips.iter().any(|clip| clip.kind != clips[0].kind) {
+ return Some("Merged clips must be the same kind.".to_owned());
+ }
+ if clips.iter().any(|clip| clip.reverse != clips[0].reverse) {
+ return Some("Merged clips must play the same way round.".to_owned());
+ }
+ if clips.iter().any(|clip| clip.speed_curve.is_some()) {
+ return Some("A clip with a speed curve cannot be merged.".to_owned());
+ }
+ if clips
+ .iter()
+ .any(|clip| clip.audio_stream != clips[0].audio_stream)
+ {
+ return Some("Merged clips must play the same audio track.".to_owned());
+ }
let mut ordered = clips.clone();
ordered.sort_by(|left, right| left.start.total_cmp(&right.start));
@@ -836,10 +983,15 @@ pub fn why_not_merge(timeline: &Timeline, clip_ids: &[String]) -> Option<String>
if (current.start - (previous.start + previous.duration)).abs() > JOIN_EPSILON {
return Some("Merged clips must touch, with no gap or overlap.".to_owned());
}
- if (current.source_start - (previous.source_start + previous.duration * previous.speed))
- .abs()
- > JOIN_EPSILON
- {
+ // Forwards the next piece starts where the last one's source ended;
+ // backwards it is the other way round, the earlier piece showing the
+ // later source.
+ let continuous = if previous.reverse {
+ previous.source_start - (current.source_start + current.duration * current.speed)
+ } else {
+ current.source_start - (previous.source_start + previous.duration * previous.speed)
+ };
+ if continuous.abs() > JOIN_EPSILON {
return Some("These pieces are no longer in their original order.".to_owned());
}
}
@@ -868,6 +1020,9 @@ pub fn apply(
mint: &mut IdMint,
command: Command,
) -> Result<Outcome, CommandError> {
+ if command.has_non_finite() {
+ return Err(CommandError::NotANumber);
+ }
match command {
Command::AddMedia { item } => {
if project
@@ -1228,12 +1383,23 @@ pub fn apply(
}
TrimEdge::Start => {
// Dragging the head moves the in-point too, so the pixels
- // under the remaining part of the clip do not slide.
- let shift = delta.min(clip.duration - MIN_CLIP_DURATION);
+ // under the remaining part of the clip do not slide. A
+ // reversed clip shows the far end of its span at the
+ // head, so its in-point is the span's other end and stays
+ // put: only the span changes.
+ let mut shift = delta.min(clip.duration - MIN_CLIP_DURATION);
+ if !clip.reverse {
+ // The head cannot reach before the source begins.
+ shift = shift.max(-clip.source_start / clip.speed);
+ }
let start = (clip.start + shift).max(0.0);
let moved = start - clip.start;
let duration = clip.duration - moved;
- let source_start = (clip.source_start + moved * clip.speed).max(0.0);
+ let source_start = if clip.reverse {
+ clip.source_start
+ } else {
+ (clip.source_start + moved * clip.speed).max(0.0)
+ };
// Bitwise so no assignment is short-circuited away.
assign(&mut clip.start, start)
| assign(&mut clip.duration, duration)
@@ -1254,18 +1420,17 @@ pub fn apply(
continue;
};
{
- // A curve or a reverse does not survive a cut in halves:
- // the map from here to the source is not affine, so both
- // halves go to the constant mean, which is what they
- // averaged.
+ // A curve does not survive a cut in halves: the map from
+ // here to the source is not affine, so both halves go to
+ // the constant mean, which is what they averaged. A
+ // reverse is affine and survives: see `split_source`.
let clip = &mut timeline.clips[index];
let offset = time - clip.start;
if offset > MIN_CLIP_DURATION
&& offset < clip.duration - MIN_CLIP_DURATION
- && (clip.speed_curve.is_some() || clip.reverse)
+ && clip.speed_curve.is_some()
{
clip.speed_curve = None;
- clip.reverse = false;
}
}
let clip = &timeline.clips[index];
@@ -1273,16 +1438,24 @@ pub fn apply(
if offset <= MIN_CLIP_DURATION || offset >= clip.duration - MIN_CLIP_DURATION {
continue;
}
+ let (head_source, tail_source) = split_source(
+ clip.source_start,
+ clip.duration,
+ clip.speed,
+ offset,
+ clip.reverse,
+ );
let mut tail = clip.clone();
tail.id = mint.next("c");
tail.start = clip.start + offset;
tail.duration = clip.duration - offset;
- tail.source_start = clip.source_start + offset * clip.speed;
+ tail.source_start = tail_source;
// The transition belongs to the cut at the original clip's
// start, which the head keeps.
tail.transition_in = None;
created = Some(tail.id.clone());
timeline.clips[index].duration = offset;
+ timeline.clips[index].source_start = head_source;
timeline.clips.insert(index + 1, tail);
}
// A split always mints the tail, so "minted anything" and
@@ -1364,22 +1537,22 @@ pub fn apply(
return Ok(Outcome::default());
};
// The cut is a split's, so it leaves the pieces as a split does:
- // under a curve or a reverse the map is not affine, and the
- // in-point below assumes it is, so both pieces go to the constant
- // mean they averaged.
- {
- let clip = &mut timeline.clips[index];
- clip.speed_curve = None;
- clip.reverse = false;
- }
+ // under a curve the map is not affine, and the in-point below
+ // assumes it is, so both pieces go to the constant mean they
+ // averaged. A reverse is affine and is kept; see `split_source`.
+ timeline.clips[index].speed_curve = None;
+ let reverse = timeline.clips[index].reverse;
let offset = time - start;
+ let (head_source, tail_source) =
+ split_source(source_start, clip_duration, speed, offset, reverse);
let mut tail = timeline.clips[index].clone();
tail.id = mint.next("c");
tail.start = time;
tail.duration = clip_duration - offset;
- tail.source_start = source_start + offset * speed;
+ tail.source_start = tail_source;
tail.transition_in = None;
timeline.clips[index].duration = offset;
+ timeline.clips[index].source_start = head_source;
timeline.clips.insert(index + 1, tail);
// Ripple every later placement on this track (including the new
@@ -1445,6 +1618,11 @@ pub fn apply(
.clip_mut(&first.id)
.expect("the first piece survives the retain");
survivor.duration = merged_duration;
+ if first.reverse {
+ // The last piece shows the earliest source, and the merged
+ // clip's in-point is that.
+ survivor.source_start = last.source_start;
+ }
// A validated merge always absorbs at least one piece.
Ok(Outcome {
created_id: Some(first.id),
@@ -1490,6 +1668,11 @@ pub fn apply(
if let Some(preserve) = patch.preserve_pitch {
applied |= assign(&mut clip.preserve_pitch, preserve);
}
+ if let Some(muted) = patch.muted {
+ // Unmuted is the absent value, so a document never carries
+ // a `muted: false` that means the same as nothing.
+ applied |= assign(&mut clip.muted, muted.then_some(true));
+ }
if let Some(reverse) = patch.reverse {
applied |= assign(&mut clip.reverse, reverse);
}
@@ -1791,10 +1974,7 @@ pub fn apply(
applied |= assign(&mut clip.offset_y, offset.clamp(-MAX_OFFSET, MAX_OFFSET));
}
if let Some(rotation) = rotation {
- // Kept in (-180, 180] so a full drag never accumulates turns.
- let wrapped = ((rotation % 360.0) + 540.0) % 360.0 - 180.0;
- let next = if wrapped == -180.0 { 180.0 } else { wrapped };
- applied |= assign(&mut clip.rotation, next);
+ applied |= assign(&mut clip.rotation, wrap_rotation(rotation));
}
if let Some(stretch) = stretch_x {
applied |= assign(&mut clip.stretch_x, stretch.clamp(MIN_STRETCH, MAX_STRETCH));
diff --git a/src/crates/concat-project/src/doc.rs b/src/crates/concat-project/src/doc.rs
index 21a67d75..fbba1222 100644
--- a/src/crates/concat-project/src/doc.rs
+++ b/src/crates/concat-project/src/doc.rs
@@ -22,15 +22,27 @@ use std::collections::BTreeMap;
use serde_json::{Map, Value, json};
-use crate::commands::{MAX_STRETCH, MIN_STRETCH};
+use crate::commands::{
+ MAX_OFFSET, MAX_SCALE, MAX_SPEED, MAX_STRETCH, MIN_CLIP_DURATION, MIN_SCALE, MIN_SPEED,
+ MIN_STRETCH, wrap_rotation,
+};
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,
};
-/// Bumped only when a change cannot be absorbed by defaulting.
-const DOCUMENT_VERSION: u64 = 1;
+/// 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.
+pub const DOCUMENT_VERSION: u64 = 1;
+
+/// The version a document says it is. Documents from before the field
+/// existed are version 1: that is the version their shape was given.
+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()
@@ -244,28 +256,31 @@ fn read_clips(raw: Option<&Value>, tracks: &[Track], media: &[MediaItem]) -> Vec
name: text(entry.get("name"), "clip"),
kind,
start: number(entry.get("start"), 0.0).max(0.0),
- duration: number(entry.get("duration"), 1.0).max(0.01),
+ // The same floors and ceilings every command holds, so a
+ // hand-edited or older file cannot carry a value no edit
+ // could produce.
+ duration: number(entry.get("duration"), 1.0).max(MIN_CLIP_DURATION),
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).max(0.05),
- offset_x: number(entry.get("offsetX"), 0.0),
- offset_y: number(entry.get("offsetY"), 0.0),
- rotation: number(entry.get("rotation"), 0.0),
+ scale: number(entry.get("scale"), 1.0).clamp(MIN_SCALE, MAX_SCALE),
+ offset_x: number(entry.get("offsetX"), 0.0).clamp(-MAX_OFFSET, MAX_OFFSET),
+ offset_y: number(entry.get("offsetY"), 0.0).clamp(-MAX_OFFSET, MAX_OFFSET),
+ rotation: wrap_rotation(number(entry.get("rotation"), 0.0)),
stretch_x: number(entry.get("stretchX"), 1.0).clamp(MIN_STRETCH, MAX_STRETCH),
stretch_y: number(entry.get("stretchY"), 1.0).clamp(MIN_STRETCH, MAX_STRETCH),
// Clamped: a hand-edited 2 would export differently from how
// the preview clamps it on screen.
opacity: number(entry.get("opacity"), 1.0).clamp(0.0, 1.0),
- speed: number(entry.get("speed"), 1.0).clamp(0.0625, 16.0),
+ speed: number(entry.get("speed"), 1.0).clamp(MIN_SPEED, MAX_SPEED),
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),
+ speed: number(point.get("speed"), 1.0).clamp(MIN_SPEED, MAX_SPEED),
})
.filter(|point| (0.0..=1.0).contains(&point.at))
.collect();
@@ -318,7 +333,7 @@ fn read_clips(raw: Option<&Value>, tracks: &[Track], media: &[MediaItem]) -> Vec
/// 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() {
+ if !document.is_object() || document_version(document) > DOCUMENT_VERSION {
return None;
}
let media = read_media(document.get("media"));
diff --git a/src/crates/concat-project/src/lib.rs b/src/crates/concat-project/src/lib.rs
index efc17e28..dd7b64bc 100644
--- a/src/crates/concat-project/src/lib.rs
+++ b/src/crates/concat-project/src/lib.rs
@@ -29,7 +29,7 @@ pub mod model;
pub mod speed;
pub use commands::{Command, CommandError, Outcome, why_not_merge};
-pub use doc::{DocumentSettings, from_document, to_document};
+pub use doc::{DOCUMENT_VERSION, DocumentSettings, document_version, from_document, to_document};
pub use editor::Editor;
pub use model::Project;
@@ -188,8 +188,9 @@ mod tests {
}
/// A freeze cuts the clip the way a split does, so a reversed or curved
- /// clip has to come out of it the way a split leaves one: both pieces at
- /// the constant mean, forwards, meeting at the frozen source time.
+ /// clip has to come out of it the way a split leaves one: a curve goes
+ /// to its constant mean, a reverse is kept, and the pieces meet at the
+ /// frozen source time either way.
#[test]
fn freeze_frame_on_a_reversed_or_curved_clip_keeps_the_pieces_continuous() {
for (reverse, curve) in [
@@ -257,15 +258,27 @@ mod tests {
.expect("tail");
for piece in [head, tail] {
assert!(
- !piece.reverse && piece.speed_curve.is_none(),
- "reverse {reverse}, curve {curve:?}: a piece kept a map its in-point was not computed for"
+ piece.speed_curve.is_none(),
+ "reverse {reverse}, curve {curve:?}: a piece kept a curve its in-point was not computed for"
+ );
+ assert_eq!(piece.reverse, reverse, "a cut keeps the direction");
+ }
+ if reverse {
+ // Backwards, the tail shows the early source and the head
+ // picks up where the tail's span ends.
+ assert_eq!(
+ tail.source_start + tail.duration * tail.speed,
+ head.source_start,
+ "the head shows what comes after the tail's span"
+ );
+ assert_eq!(tail.source_start, 0.0, "the tail keeps the in-point");
+ } else {
+ assert_eq!(
+ head.source_start + head.duration * head.speed,
+ tail.source_start,
+ "curve {curve:?}: the tail picks up where the head ends"
);
}
- assert_eq!(
- head.source_start + head.duration * head.speed,
- tail.source_start,
- "reverse {reverse}, curve {curve:?}: the tail picks up where the head ends"
- );
}
}
@@ -295,6 +308,238 @@ mod tests {
assert_eq!(clips[0].id, clip_id, "the first piece keeps its identity");
}
+ #[test]
+ fn a_reversed_clip_splits_into_mirrored_halves_and_merges_back() {
+ let (mut editor, _, clip_id) = fixture();
+ editor
+ .apply(Command::UpdateClip {
+ clip_id: clip_id.clone(),
+ patch: ClipPatch {
+ reverse: Some(true),
+ ..Default::default()
+ },
+ })
+ .expect("reverses");
+ editor
+ .apply(Command::SplitClips {
+ clip_ids: vec![clip_id.clone()],
+ time: 4.0,
+ })
+ .expect("splits");
+ let clips = &editor.project().active().clips;
+ assert_eq!(clips.len(), 2);
+ let (head, tail) = (&clips[0], &clips[1]);
+ assert!(
+ head.reverse && tail.reverse,
+ "both halves still play backwards"
+ );
+ // The whole showed source 10→0. The head's four seconds show 10→6,
+ // so its span is [6, 10); the tail's six show 6→0, span [0, 6).
+ assert_eq!(head.duration, 4.0);
+ assert_eq!(head.source_start, 6.0);
+ assert_eq!(tail.duration, 6.0);
+ assert_eq!(tail.source_start, 0.0);
+
+ let ids: Vec<String> = clips.iter().map(|clip| clip.id.clone()).collect();
+ editor
+ .apply(Command::MergeClips { clip_ids: ids })
+ .expect("merges");
+ let clip = &editor.project().active().clips[0];
+ assert_eq!((clip.duration, clip.source_start), (10.0, 0.0));
+ assert!(clip.reverse);
+ }
+
+ #[test]
+ fn a_head_trim_on_a_reversed_clip_keeps_the_in_point() {
+ let (mut editor, _, clip_id) = fixture();
+ editor
+ .apply(Command::UpdateClip {
+ clip_id: clip_id.clone(),
+ patch: ClipPatch {
+ reverse: Some(true),
+ ..Default::default()
+ },
+ })
+ .expect("reverses");
+ editor
+ .apply(Command::TrimClip {
+ clip_id: clip_id.clone(),
+ edge: TrimEdge::Start,
+ delta: 3.0,
+ })
+ .expect("trims");
+ let clip = &editor.project().active().clips[0];
+ // The head showed source 10; three seconds in it shows 7, and that
+ // is what the trimmed clip now opens on: span [0, 7), in-point 0.
+ assert_eq!(
+ (clip.start, clip.duration, clip.source_start),
+ (3.0, 7.0, 0.0)
+ );
+ }
+
+ #[test]
+ fn a_head_trim_cannot_reach_before_the_source_begins() {
+ let (mut editor, _, clip_id) = fixture();
+ editor
+ .apply(Command::MoveClips {
+ moves: vec![crate::commands::ClipMove {
+ clip_id: clip_id.clone(),
+ start: 5.0,
+ track_id: editor.project().active().clips[0].track_id.clone(),
+ }],
+ })
+ .expect("moves");
+ // Pulling the head four seconds left would want source -4: the trim
+ // stops at the source's start, and the pixels do not slide.
+ editor
+ .apply(Command::TrimClip {
+ clip_id: clip_id.clone(),
+ edge: TrimEdge::Start,
+ delta: -4.0,
+ })
+ .expect("trims");
+ let clip = &editor.project().active().clips[0];
+ assert_eq!(
+ (clip.start, clip.duration, clip.source_start),
+ (5.0, 10.0, 0.0)
+ );
+ }
+
+ #[test]
+ fn a_video_whose_detached_sound_was_deleted_can_be_unmuted() {
+ let (mut editor, _, clip_id) = fixture();
+ editor
+ .apply(Command::DetachAudio {
+ clip_id: clip_id.clone(),
+ })
+ .expect("detaches");
+ let sound: Vec<String> = editor
+ .project()
+ .active()
+ .clips
+ .iter()
+ .filter(|clip| clip.id != clip_id)
+ .map(|clip| clip.id.clone())
+ .collect();
+ assert_eq!(sound.len(), 1);
+ editor
+ .apply(Command::RemoveClips { clip_ids: sound })
+ .expect("removes");
+ assert_eq!(
+ editor
+ .project()
+ .active()
+ .clip(&clip_id)
+ .expect("video")
+ .muted,
+ Some(true)
+ );
+ editor
+ .apply(Command::UpdateClip {
+ clip_id: clip_id.clone(),
+ patch: ClipPatch {
+ muted: Some(false),
+ ..Default::default()
+ },
+ })
+ .expect("unmutes");
+ assert_eq!(
+ editor
+ .project()
+ .active()
+ .clip(&clip_id)
+ .expect("video")
+ .muted,
+ None,
+ "unmuted is the absent value"
+ );
+ }
+
+ #[test]
+ fn a_command_carrying_nan_is_refused_whole() {
+ let (mut editor, _, clip_id) = fixture();
+ let before = editor.project().clone();
+ for command in [
+ Command::SetClipSpeed {
+ clip_id: clip_id.clone(),
+ speed: f64::NAN,
+ },
+ Command::SplitClips {
+ clip_ids: vec![clip_id.clone()],
+ time: f64::NAN,
+ },
+ Command::SetClipTransform {
+ clip_id: clip_id.clone(),
+ scale: None,
+ offset_x: Some(f64::INFINITY),
+ offset_y: None,
+ rotation: None,
+ stretch_x: None,
+ stretch_y: None,
+ },
+ Command::Batch {
+ commands: vec![Command::TrimClip {
+ clip_id: clip_id.clone(),
+ edge: TrimEdge::End,
+ delta: f64::NAN,
+ }],
+ },
+ ] {
+ assert_eq!(
+ editor.apply(command).expect_err("refused"),
+ crate::CommandError::NotANumber
+ );
+ }
+ assert_eq!(editor.project(), &before, "nothing changed");
+ }
+
+ #[test]
+ fn a_document_from_a_newer_build_is_refused() {
+ let (editor, _, _) = fixture();
+ let mut document = editor.to_document(&settings());
+ document["version"] = serde_json::json!(crate::DOCUMENT_VERSION + 1);
+ assert!(Editor::from_document(&document).is_none());
+ assert_eq!(
+ crate::document_version(&document),
+ crate::DOCUMENT_VERSION + 1
+ );
+ assert_eq!(crate::document_version(&serde_json::json!({})), 1);
+ }
+
+ #[test]
+ fn a_loaded_document_holds_the_same_ranges_every_command_does() {
+ let (editor, _, _) = fixture();
+ let mut document = editor.to_document(&settings());
+ let clip = &mut document["timelines"][0]["clips"][0];
+ clip["duration"] = serde_json::json!(0.001);
+ clip["scale"] = serde_json::json!(50.0);
+ clip["offsetX"] = serde_json::json!(-9.0);
+ clip["rotation"] = serde_json::json!(540.0);
+ clip["speed"] = serde_json::json!(100.0);
+ let loaded = Editor::from_document(&document).expect("loads");
+ let clip = &loaded.project().active().clips[0];
+ assert_eq!(clip.duration, 1.0 / 60.0);
+ assert_eq!(clip.scale, 8.0);
+ assert_eq!(clip.offset_x, -3.0);
+ assert_eq!(clip.rotation, 180.0);
+ assert_eq!(clip.speed, 16.0);
+ }
+
+ #[test]
+ fn a_renamed_timeline_does_not_count_towards_the_next_number() {
+ let (mut editor, _, _) = fixture();
+ editor.apply(Command::AddTimeline).expect("adds");
+ let second = editor.project().timelines[1].id.clone();
+ editor
+ .apply(Command::RenameTimeline {
+ timeline_id: second,
+ name: "Timeline 2 v10".to_owned(),
+ })
+ .expect("renames");
+ editor.apply(Command::AddTimeline).expect("adds");
+ assert_eq!(editor.project().timelines[2].name, "Timeline 2");
+ }
+
#[test]
fn rearranged_pieces_refuse_to_merge() {
let (mut editor, _, clip_id) = fixture();
@@ -1793,7 +2038,7 @@ mod tests {
let editor = Editor::from_document(&document).expect("loads");
let clip = &editor.project().active().clips[0];
assert_eq!(clip.start, 0.0);
- assert_eq!(clip.duration, 0.01);
+ assert_eq!(clip.duration, 1.0 / 60.0, "the floor every command holds");
assert_eq!(clip.source_start, 0.0);
assert_eq!(clip.volume, 0.0);
assert_eq!(clip.opacity, 1.0);