Skip to content

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

refactor(project): one clip constructor, one tidy, and the commands in six modules

Jareer53d66e6ed53a
diff --git a/src/crates/concat-project/src/commands.rs b/src/crates/concat-project/src/commands.rs
deleted file mode 100644
index 9c6a94cf..00000000
--- a/src/crates/concat-project/src/commands.rs
+++ /dev/null
@@ -1,2341 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
-
-//! Every edit operation, as data.
-//!
-//! A [`Command`] is what the window sends; [`apply`] is the one place its
-//! meaning lives. The clamps and tolerances documented on each variant are
-//! the contract the window's gesture echo mirrors and tests against.
-
-use std::collections::HashSet;
-use std::sync::Arc;
-
-use serde::{Deserialize, Serialize};
-
-use crate::model::{
- AnimationSlot, AppliedFilter, AudioTrack, Clip, ClipAnimation, ClipKind, Crop, CustomFont,
- Cutout, CutoutMode, KeyEase, KeyProperty, MediaItem, MediaKind, Project, SpeedPoint, Stroke,
- TextStyle, Timeline, Track, Transition, VideoSettings,
-};
-
-/// Fallback length for media whose container reports no duration.
-const UNKNOWN_DURATION: f64 = 5.0;
-/// How long a still lasts when first placed. Editorial default, not a fact.
-const DEFAULT_IMAGE_DURATION: f64 = 5.0;
-/// How long a title lasts when first placed.
-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;
-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.
-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;
-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;
-
-/// Which end of a clip a trim drags. The two are not symmetric: see
-/// [`Command::TrimClip`].
-#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
-#[serde(rename_all = "lowercase")]
-pub enum TrimEdge {
- /// The head. Trimming here moves the in-point with the edge, so the
- /// remaining frames stay where they were on the timeline.
- Start,
- /// The tail. Trimming here only lengthens or shortens the clip.
- End,
-}
-
-/// Which per-track toggle a [`Command::SetTrackFlag`] flips.
-#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
-#[serde(rename_all = "lowercase")]
-pub enum TrackFlag {
- /// [`Track::visible`]: whether the track's video reaches the composite.
- Visible,
- /// [`Track::muted`]: whether the track's audio is silenced.
- Muted,
-}
-
-/// Where one clip is going, in a multi-clip move.
-#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ClipMove {
- /// The clip to move. An unknown id is skipped, not an error - the rest
- /// of the batch of moves still lands.
- pub clip_id: String,
- /// New timeline position in seconds, floored at 0.
- pub start: f64,
- /// Destination track. An unknown id moves the clip in time but leaves it
- /// on its current track.
- pub track_id: String,
-}
-
-/// A partial update to one clip. Every field optional; `transition_in` and
-/// `text` are double-optional so "clear it" and "leave it alone" stay
-/// distinct on the wire (absent = untouched, null = cleared).
-#[derive(Clone, Default, PartialEq, Debug, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ClipPatch {
- /// New display name, taken verbatim. A later `text` patch overwrites it
- /// with the title's first line.
- pub name: Option<String>,
- /// New gain; floored at 0, deliberately not capped at 1 - boosting quiet
- /// footage is legitimate.
- pub volume: Option<f64>,
- /// New fade-in length in seconds, floored at 0.
- pub fade_in: Option<f64>,
- /// New fade-out length in seconds, floored at 0.
- pub fade_out: Option<f64>,
- /// New opacity, clamped into 0..=1.
- 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>,
- /// Mirror left to right.
- #[serde(default)]
- pub flip_h: Option<bool>,
- /// Mirror top to bottom.
- #[serde(default)]
- pub flip_v: Option<bool>,
- /// The blend mode's name; empty is normal.
- #[serde(default)]
- pub blend: Option<String>,
- /// The crop; `Some(None)` takes it off.
- #[serde(default)]
- pub crop: Option<Option<Crop>>,
- /// Wholesale replacement of the audio filter chain - the UI sends the
- /// full list, not a diff.
- pub filters: Option<Vec<AppliedFilter>>,
- /// Wholesale replacement of the video effect chain, like `filters`.
- pub video_effects: Option<Vec<AppliedFilter>>,
- /// The transition on the cut into the clip: absent leaves it alone,
- /// null clears it, a value replaces it.
- #[serde(
- default,
- with = "double_option",
- skip_serializing_if = "Option::is_none"
- )]
- pub transition_in: Option<Option<Transition>>,
- /// The title styling, same three-way wire semantics as `transition_in`.
- /// Setting a style also renames the clip after its first line.
- #[serde(
- default,
- with = "double_option",
- skip_serializing_if = "Option::is_none"
- )]
- pub text: Option<Option<TextStyle>>,
- /// Which of the media's audio streams the clip plays, by stream index:
- /// absent leaves it alone, null goes back to the file's first, a value
- /// names one. See `Clip::audio_stream`.
- #[serde(
- default,
- with = "double_option",
- skip_serializing_if = "Option::is_none"
- )]
- pub audio_stream: Option<Option<u32>>,
-}
-
-/// `Option<Option<T>>` over JSON: absent → None, null → Some(None).
-mod double_option {
- use serde::{Deserialize, Deserializer, Serialize, Serializer};
-
- pub fn serialize<T: Serialize, S: Serializer>(
- value: &Option<Option<T>>,
- serializer: S,
- ) -> Result<S::Ok, S::Error> {
- match value {
- Some(inner) => inner.serialize(serializer),
- None => serializer.serialize_none(),
- }
- }
-
- pub fn deserialize<'de, T: Deserialize<'de>, D: Deserializer<'de>>(
- deserializer: D,
- ) -> Result<Option<Option<T>>, D::Error> {
- Option::<T>::deserialize(deserializer).map(Some)
- }
-}
-
-/// A media item as probed by the host, before the model mints its id.
-#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct NewMedia {
- /// Absolute path on disk. Adding a path already in the bin is a no-op,
- /// so re-imports cannot duplicate media.
- pub path: String,
- /// Display name for the bin, normally the file's basename.
- pub name: String,
- /// Seconds, or None when the container did not report one - clips of
- /// such media get a five-second fallback length.
- pub duration: Option<f64>,
- /// What the host's probe decided the file is.
- pub kind: MediaKind,
- /// Pixel width, when the probe found one.
- pub width: Option<u32>,
- /// Pixel height, same terms as `width`.
- pub height: Option<u32>,
- /// Frames per second as a decimal, for display.
- pub frame_rate: Option<f64>,
- /// The exact rate fraction the engine works in, e.g. "30000/1001".
- pub frame_rate_fraction: Option<String>,
- /// Codec name as probed, e.g. "h264". Informational.
- pub video_codec: Option<String>,
- /// Codec of the embedded audio, when there is any.
- pub audio_codec: Option<String>,
- /// Whether the file carries an audio stream.
- pub has_audio: bool,
- /// Every audio stream, in file order; see `MediaItem::audio_tracks`.
- /// Defaulted so a caller from before the list can still add media.
- #[serde(default)]
- pub audio_tracks: Vec<AudioTrack>,
-}
-
-/// Every edit, as the window sends it: a tagged `op` plus camelCase
-/// fields. [`apply`] is the single place each variant's meaning lives; the
-/// notes here state the contract - clamps, tolerances, what gets minted -
-/// so a caller need not read `apply` to know what a command will do.
-#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
-#[serde(tag = "op", rename_all = "camelCase", rename_all_fields = "camelCase")]
-// A clip patch carries a whole text style, which is the largest variant by
-// a couple of hundred bytes. Commands are made one at a time and kept only
-// in the undo history, where a few hundred bytes each is nothing; boxing
-// the patch would cost every caller for a saving nobody would measure.
-#[allow(clippy::large_enum_variant)]
-pub enum Command {
- /// Imports a file into the bin, minting an "m" id. A path already
- /// present is a tolerated no-op that mints nothing.
- AddMedia {
- /// The probed file, as described by the host.
- item: NewMedia,
- },
- /// Removes a bin item and every clip referencing it, on *all* timelines
- /// - a clip whose media is gone would linger as a dead reference.
- RemoveMedia {
- /// The bin item to remove. An unknown id is a no-op.
- media_id: String,
- },
- /// Marks a bin item as a template slot (or back to ordinary media),
- /// which is what [`Command::FillSlot`] requires of its target.
- SetMediaPlaceholder {
- /// The bin item to mark. An unknown id is a no-op.
- media_id: String,
- /// True to make it a slot, false to make it ordinary media again.
- placeholder: bool,
- },
- /// Swaps the user's file into a template slot in place. The slot keeps
- /// its id so clips keep working; start, duration and speed stay the
- /// template's, while the in-point resets and each clip's kind and name
- /// follow the new file, across all timelines. Errs if the id is unknown
- /// or the item is not a placeholder.
- FillSlot {
- /// The slot being filled - must have `placeholder` set.
- media_id: String,
- /// The user's file that takes the slot's place.
- item: NewMedia,
- },
- /// Several commands as one atomic edit: applied to a staged copy and
- /// committed only if every one succeeds, then recorded as a single undo
- /// step. The outcome carries the last id minted inside.
- Batch {
- /// The commands, applied in order. Nesting is legal.
- commands: Vec<Command>,
- },
- /// Places a clip of `media_id` on a named track, minting a "c" id.
- /// Duration comes from the media (five seconds for a still or unknown
- /// length); errs if the media or track no longer exists.
- AddClip {
- /// The bin item to cut from.
- media_id: String,
- /// The lane to place it on.
- track_id: String,
- /// Timeline position in seconds, floored at 0.
- start: f64,
- },
- /// [`Command::AddClip`] without naming a lane: lands on the lowest
- /// track with nothing in the clip's span, falling back to the bottom
- /// track (overlap and all) rather than refusing.
- AddClipAtFirstFree {
- /// The bin item to cut from.
- media_id: String,
- /// Timeline position in seconds, floored at 0.
- start: f64,
- },
- /// Places a title: a clip with no media behind it, named after the
- /// text's first line, minting a "c" id.
- AddTextClip {
- /// The lane to place it on. None picks the first free track like
- /// [`Command::AddClipAtFirstFree`]; naming a vanished track errs.
- track_id: Option<String>,
- /// Timeline position in seconds, floored at 0.
- start: f64,
- /// The words and their look. None means [`TextStyle::default`].
- style: Option<TextStyle>,
- /// Seconds on the timeline; the editorial default when absent. Here
- /// so a caption run can land as one batch instead of add-then-trim
- /// per clip - a batch cannot trim a clip whose id it cannot know yet.
- #[serde(default)]
- duration: Option<f64>,
- /// Vertical placement as a frame-height fraction, clamped like
- /// SetClipTransform. Lower thirds are made of this.
- #[serde(default)]
- offset_y: Option<f64>,
- },
- /// Places a layer: a look or an effect over a span of the timeline that
- /// treats everything beneath it. No media; the chain starts as the one
- /// package named, at its defaults, and the clip's opacity is how hard it
- /// is applied.
- AddLayerClip {
- /// The lane to place it on; None picks the first free track.
- track_id: Option<String>,
- /// Timeline position in seconds, floored at 0.
- start: f64,
- /// Seconds on the timeline; the editorial default when absent.
- #[serde(default)]
- duration: Option<f64>,
- /// The package the layer applies, e.g. "concat.warm".
- effect_id: String,
- /// What the lane calls it.
- name: String,
- },
- /// Gives a clip a speed curve, or takes it away. The source covered is
- /// held constant, as a speed change does, so the clip's timeline length
- /// follows the curve's mean; `speed` is kept at that mean.
- SetClipSpeedCurve {
- /// The clip to retime.
- clip_id: String,
- /// The curve, or None for a constant rate at the current mean.
- curve: Option<Vec<SpeedPoint>>,
- },
- /// Sets or clears the animation on one slot of a clip.
- SetClipAnimation {
- /// The clip.
- clip_id: String,
- /// Which end, or the whole.
- slot: AnimationSlot,
- /// The shape and its seconds, or None to take it off.
- animation: Option<ClipAnimation>,
- },
- /// Puts a key on one property at one point of a clip, replacing
- /// whichever key on that property was already within a hair of it.
- ///
- /// The value is the property's own - the number the inspector shows -
- /// not the relative factor the engine plays; see `model::ClipKey`.
- SetClipKey {
- /// The clip.
- clip_id: String,
- /// Which property is being keyed.
- property: KeyProperty,
- /// Where in the clip, `0..=1`.
- at: f64,
- /// The value there.
- value: f64,
- /// How the key is approached from the one before it.
- #[serde(default)]
- ease: KeyEase,
- },
- /// Takes the key at `at` off one property, if there is one there. The
- /// other half of the diamond: a filled diamond clicked is this.
- ClearClipKey {
- /// The clip.
- clip_id: String,
- /// Which property.
- property: KeyProperty,
- /// Where in the clip the key to remove sits, `0..=1`.
- at: f64,
- },
- /// Takes every key off one property, returning it to its constant.
- ClearClipKeys {
- /// The clip.
- clip_id: String,
- /// Which property.
- property: KeyProperty,
- },
- /// Puts a key on one parameter of one link of a clip's picture chain,
- /// replacing whichever key on it was already within a hair of `at`.
- /// The value is the parameter's own; the package's range is the
- /// caller's to keep, the model not knowing it.
- SetEffectKey {
- /// The clip.
- clip_id: String,
- /// Which link, as an index into `video_effects`. Out of range is a
- /// no-op.
- entry: usize,
- /// The parameter's manifest key.
- key: String,
- /// Where in the clip, `0..=1`.
- at: f64,
- /// The value there.
- value: f64,
- /// How the key is approached from the one before it.
- #[serde(default)]
- ease: KeyEase,
- },
- /// Takes the key at `at` off one parameter of one link, if there is one.
- ClearEffectKey {
- /// The clip.
- clip_id: String,
- /// Which link, as an index into `video_effects`.
- entry: usize,
- /// The parameter's manifest key.
- key: String,
- /// Where in the clip the key to remove sits, `0..=1`.
- at: f64,
- },
- /// Takes every key off one parameter of one link, returning it to the
- /// value it holds.
- ClearEffectKeys {
- /// The clip.
- clip_id: String,
- /// Which link, as an index into `video_effects`.
- entry: usize,
- /// The parameter's manifest key.
- key: String,
- },
- /// Sets or clears a picture's cutout: the mask that takes its
- /// background away. Tidied on the way in; see [`Cutout::tidy`].
- SetClipCutout {
- /// The clip. An unknown id is a no-op.
- clip_id: String,
- /// The cutout, or None to take it off.
- cutout: Option<Cutout>,
- },
- /// Paints one stroke onto a clip's cutout. A clip with no cutout gets a
- /// custom one; an automatic cutout becomes custom, since a stroke is a
- /// correction to it. A stroke with no points is a no-op.
- AddCutoutStroke {
- /// The clip. An unknown id is a no-op.
- clip_id: String,
- /// The stroke, in source fractions.
- stroke: Stroke,
- },
- /// Repositions any number of clips in one edit - one undo step for a
- /// whole multi-selection drag. Unknown clips and tracks are tolerated
- /// per [`ClipMove`].
- MoveClips {
- /// Where each clip is going.
- moves: Vec<ClipMove>,
- },
- /// Drags one edge of a clip. A head trim moves the in-point with the
- /// edge (scaled by speed) so the remaining pixels do not slide; either
- /// edge stops at the sixtieth-of-a-second minimum duration. An unknown
- /// clip is a no-op.
- TrimClip {
- /// The clip to trim.
- clip_id: String,
- /// Which edge is being dragged.
- edge: TrimEdge,
- /// Signed seconds of timeline the edge moves: positive drags the
- /// head right (shortening) or the tail right (lengthening).
- delta: f64,
- },
- /// Cuts each named clip in two at one playhead time. The head keeps the
- /// id and the transition; the tail is minted fresh and stays
- /// source-continuous. A clip the time misses (or grazes within the
- /// minimum duration) is skipped.
- SplitClips {
- /// The clips under the playhead - normally the selection.
- clip_ids: Vec<String>,
- /// The cut point, in timeline seconds.
- time: f64,
- },
- /// CapCut-style freeze at `time`: splits `clip_id`, inserts a still of
- /// `duration` on the same track, and ripples later clips on that track
- /// by `duration`. Video needs a probed `still` (host-extracted jpg);
- /// image clips may omit it and reuse their media. Audio and text are
- /// no-ops. `created_id` is the freeze clip.
- FreezeFrame {
- /// The picture clip under the playhead.
- clip_id: String,
- /// Timeline playhead; must fall strictly inside the clip.
- time: f64,
- /// Editorial length of the hold. Floored at [`MIN_CLIP_DURATION`];
- /// when absent or non-positive, uses [`DEFAULT_FREEZE_DURATION`].
- #[serde(default)]
- duration: Option<f64>,
- /// Probed still file. Required for video; ignored for image when
- /// reusing the existing media.
- #[serde(default)]
- still: Option<NewMedia>,
- },
- /// Rejoins split pieces into the earliest piece, which keeps its id.
- /// Errs with a user-facing sentence ([`why_not_merge`]) unless the
- /// pieces sit on one track, come from one file at one speed, touch
- /// within a microsecond, and are still in source order.
- MergeClips {
- /// The pieces to rejoin, any order.
- clip_ids: Vec<String>,
- },
- /// Deletes clips from the active timeline. Unknown ids are ignored.
- RemoveClips {
- /// The clips to delete.
- clip_ids: Vec<String>,
- },
- /// Applies a [`ClipPatch`]: only the fields present change, with the
- /// clamps documented on the patch. An unknown clip is a no-op.
- UpdateClip {
- /// The clip to patch.
- clip_id: String,
- /// Which properties change, and to what.
- patch: ClipPatch,
- },
- /// Changes playback rate while holding the amount of source covered
- /// constant - the clip's timeline duration is what stretches, which is
- /// what makes this a speed change rather than a trim.
- SetClipSpeed {
- /// The clip to retime. An unknown id is a no-op.
- clip_id: String,
- /// The new rate, clamped into 0.0625..=16 (the engine's range).
- speed: f64,
- },
- /// Adjusts the picture's placement. Each field is optional so a drag
- /// can send just the axis it moved; absent fields stay put.
- SetClipTransform {
- /// The clip to place. An unknown id is a no-op.
- clip_id: String,
- /// New scale, clamped into 0.05..=8.
- scale: Option<f64>,
- /// New horizontal offset as a frame-width fraction, clamped to ±3.
- offset_x: Option<f64>,
- /// New vertical offset as a frame-height fraction, clamped to ±3.
- offset_y: Option<f64>,
- /// New rotation in degrees, wrapped into (-180, 180] so a full drag
- /// never accumulates turns.
- rotation: Option<f64>,
- /// New width multiplier beyond the scale, clamped into 0.1..=10.
- #[serde(default)]
- stretch_x: Option<f64>,
- /// New height multiplier, on the same terms.
- #[serde(default)]
- stretch_y: Option<f64>,
- },
- /// Pulls a video clip's sound out into its own audio clip on a free
- /// lane (minting one if none is free), muting the video and moving its
- /// audio filters to the sound. A no-op unless the clip is an unmuted
- /// video whose media has audio and is not already detached.
- DetachAudio {
- /// The video clip to detach from.
- clip_id: String,
- },
- /// Undoes a detach: deletes the detached sound clip(s), unmutes the
- /// video and hands the sound's filters back. Accepts either the video's
- /// id or the sound's; a no-op when either side is gone.
- ReattachAudio {
- /// The video clip - or its detached sound.
- clip_id: String,
- },
- /// Appends a lane named after the highest "Track N" in use, minting a
- /// "t" id.
- AddTrack,
- /// Deletes a lane and every clip on it. Errs at the floor of one track.
- RemoveTrack {
- /// The lane to delete.
- track_id: String,
- },
- /// Flips one of a track's two toggles. An unknown id is a no-op.
- SetTrackFlag {
- /// The lane to change.
- track_id: String,
- /// Which toggle: visibility or mute.
- flag: TrackFlag,
- /// The new setting.
- value: bool,
- },
- /// Adds a fresh timeline - four new lanes, "Timeline N" after the
- /// highest in use - and makes it active. Mints a "tl" id.
- AddTimeline,
- /// Deletes a timeline, moving the active tab to a neighbour if it was
- /// this one. Errs at the floor of one timeline.
- RemoveTimeline {
- /// The timeline to delete. An unknown id is a no-op.
- timeline_id: String,
- },
- /// Sets a timeline's output frame and rate. A term no frame could have,
- /// such as a zero dimension or a zero rate, is refused as a no-op rather
- /// than clamped: there is no nearest real size to a zero.
- SetTimelineVideo {
- /// The timeline. An unknown id is a no-op.
- timeline_id: String,
- /// The frame and the rate, together.
- video: VideoSettings,
- },
- /// Renames a timeline tab. Whitespace-only names are ignored so a tab
- /// can never end up blank; unknown ids are tolerated.
- RenameTimeline {
- /// The timeline to rename.
- timeline_id: String,
- /// The new tab label; trimmed before it lands.
- name: String,
- },
- /// Switches which timeline subsequent commands act on. An unknown id
- /// leaves the selection where it was.
- SelectTimeline {
- /// The timeline to switch to.
- timeline_id: String,
- },
- /// Moves a timeline tab to a new position in the strip. Which timeline
- /// is active does not change - only the order of the tabs.
- MoveTimeline {
- /// The timeline to move. An unknown id is a no-op.
- timeline_id: String,
- /// Where it lands among its siblings, 0-based, counted with the
- /// timeline already removed from its old slot. Clamped to the end.
- index: usize,
- },
- /// Registers a font file for titles. A path already registered is a
- /// no-op, so re-adding cannot duplicate.
- AddFont {
- /// The family name titles will refer to.
- family: String,
- /// Where the font file lives on disk.
- path: String,
- },
- /// Unregisters a font family. Clips keep the family name: the face may
- /// come back when the file does.
- RemoveFont {
- /// The family to unregister.
- family: String,
- },
- /// Updates a media item's path on disk (relink). An unknown id is a no-op.
- UpdateMediaPath {
- /// The media item to update.
- media_id: String,
- /// The new absolute path on disk.
- new_path: String,
- },
-}
-
-/// What a command produced, beyond the new state: the ids it minted, so the
-/// UI can select what it just created, and whether anything changed at all.
-#[derive(Clone, Default, PartialEq, Debug, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct Outcome {
- /// The id of what the command created - a clip, track, timeline, or
- /// media item - or, for a batch, the last id minted inside it. Absent
- /// when nothing was created, including tolerated no-ops.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub created_id: Option<String>,
- /// Whether the command actually changed the project. A tolerated no-op -
- /// a missing id, a field set to the value it already had - succeeds but
- /// reports false, which is how the editor knows not to record an undo
- /// snapshot for it. For a batch: whether any member changed anything.
- #[serde(default)]
- pub applied: bool,
-}
-
-/// Why a command was refused. Every variant renders through `Display` as the
-/// exact user-facing sentence the UI shows - byte for byte the strings
-/// the window treats as the contract; the enum only gives
-/// those sentences names a host can match on.
-#[derive(Clone, PartialEq, Eq, Debug, thiserror::Error)]
-pub enum CommandError {
- /// [`Command::FillSlot`] named a media id no longer in the bin.
- #[error("That template slot no longer exists.")]
- SlotGone,
- /// [`Command::FillSlot`] targeted ordinary media rather than a slot.
- #[error("That media is not a template slot.")]
- NotASlot,
- /// A clip-placing command named media no longer in the bin.
- #[error("That media is no longer in the bin.")]
- MediaGone,
- /// A clip-placing command named a track no longer on the timeline.
- #[error("That track no longer exists.")]
- TrackGone,
- /// A first-free-track placement found a timeline with no tracks at all.
- #[error("There are no tracks.")]
- NoTracks,
- /// [`Command::MergeClips`] was refused, for whichever [`why_not_merge`]
- /// reason applied.
- #[error("{reason}")]
- CannotMerge {
- /// The [`why_not_merge`] sentence, verbatim.
- reason: String,
- },
- /// [`Command::RemoveTrack`] would have deleted the last track.
- #[error("A timeline needs at least one track.")]
- LastTrack,
- /// [`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
-/// id a file already uses - the collision class `adoptProject` fixed in the
-/// UI is prevented here instead.
-#[derive(Clone, Default, Debug)]
-pub struct IdMint {
- counter: u64,
-}
-
-impl IdMint {
- /// The next fresh id: the prefix ("c", "t", "tl", "m") plus a counter
- /// shared across all prefixes, so no two ids ever share a number.
- pub fn next(&mut self, prefix: &str) -> String {
- self.counter += 1;
- format!("{prefix}{}", self.counter)
- }
-
- /// Advances the counter past `id`'s numeric suffix, if it has one.
- pub fn adopt(&mut self, id: &str) {
- let digits: String = id
- .chars()
- .rev()
- .take_while(char::is_ascii_digit)
- .collect::<String>()
- .chars()
- .rev()
- .collect();
- if let Ok(value) = digits.parse::<u64>() {
- self.counter = self.counter.max(value);
- }
- }
-
- /// Adopts every id a restored project uses - media, timelines, tracks,
- /// clips - so nothing minted afterwards can collide with the file.
- pub fn adopt_project(&mut self, project: &Project) {
- for item in &project.media {
- self.adopt(&item.id);
- }
- for timeline in &project.timelines {
- self.adopt(&timeline.id);
- for track in &timeline.tracks {
- self.adopt(&track.id);
- }
- for clip in &timeline.clips {
- self.adopt(&clip.id);
- }
- }
- }
-}
-
-fn default_clip(id: String, track_id: String, media: &MediaItem, start: f64) -> Clip {
- Clip {
- id,
- track_id,
- media_id: media.id.clone(),
- name: media.name.clone(),
- kind: match media.kind {
- MediaKind::Video => ClipKind::Video,
- MediaKind::Audio => ClipKind::Audio,
- MediaKind::Image => ClipKind::Image,
- },
- start: start.max(0.0),
- duration: match media.kind {
- MediaKind::Image => DEFAULT_IMAGE_DURATION,
- _ => media.duration.unwrap_or(UNKNOWN_DURATION),
- },
- source_start: 0.0,
- volume: 1.0,
- fade_in: 0.0,
- fade_out: 0.0,
- scale: 1.0,
- offset_x: 0.0,
- offset_y: 0.0,
- rotation: 0.0,
- stretch_x: 1.0,
- stretch_y: 1.0,
- opacity: 1.0,
- speed: 1.0,
- preserve_pitch: true,
- speed_curve: None,
- reverse: false,
- animation_in: None,
- animation_out: None,
- animation_combo: None,
- keys: Vec::new(),
- flip_h: false,
- flip_v: false,
- blend: String::new(),
- crop: None,
- cutout: None,
- filters: Vec::new(),
- video_effects: Vec::new(),
- audio_stream: None,
- muted: None,
- detached_from: None,
- transition_in: None,
- text: None,
- }
-}
-
-/// The lowest track with nothing occupying `[start, start + duration)`,
-/// falling back to the bottom track.
-fn first_free_track(timeline: &Timeline, start: f64, duration: f64) -> Option<String> {
- let end = start + duration;
- timeline
- .tracks
- .iter()
- .find(|track| {
- !timeline.clips.iter().any(|clip| {
- clip.track_id == track.id && clip.start < end && start < clip.start + clip.duration
- })
- })
- .or(timeline.tracks.first())
- .map(|track| track.id.clone())
-}
-
-/// A one-line label for a block of text.
-fn first_line(content: &str) -> String {
- let line = content
- .lines()
- .find(|candidate| !candidate.trim().is_empty())
- .unwrap_or("Text")
- .trim();
- let label: String = line.chars().take(40).collect();
- if label.is_empty() {
- "Text".to_owned()
- } else {
- label
- }
-}
-
-/// "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| {
- 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 for a command that changes what the person is looking at, not
- /// the edit: which timeline tab is showing and the order of the tabs.
- /// Saved with the document, never recorded in undo history.
- pub fn is_view_state(&self) -> bool {
- matches!(
- self,
- Command::SelectTimeline { .. } | Command::MoveTimeline { .. }
- )
- }
-
- /// 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> {
- if clip_ids.len() < 2 {
- return Some("Select two or more clips to merge.".to_owned());
- }
- let clips: Vec<&Clip> = clip_ids.iter().filter_map(|id| timeline.clip(id)).collect();
- if clips.len() < 2 {
- return Some("Select two or more clips to merge.".to_owned());
- }
- if clips.iter().any(|clip| clip.track_id != clips[0].track_id) {
- return Some("Merged clips must be on the same track.".to_owned());
- }
- if clips.iter().any(|clip| clip.media_id != clips[0].media_id) {
- return Some("Merged clips must come from the same file.".to_owned());
- }
- 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));
- for pair in ordered.windows(2) {
- let (previous, current) = (pair[0], pair[1]);
- if (current.start - (previous.start + previous.duration)).abs() > JOIN_EPSILON {
- return Some("Merged clips must touch, with no gap or overlap.".to_owned());
- }
- // 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());
- }
- }
- None
-}
-
-/// Assigns `value` into `slot`, reporting whether that changed anything.
-/// This is how command arms notice a field being set to the value it already
-/// holds - which must count as "nothing happened" ([`Outcome::applied`]
-/// false), or the undo history would record phantom edits.
-fn assign<T: PartialEq>(slot: &mut T, value: T) -> bool {
- if *slot == value {
- false
- } else {
- *slot = value;
- true
- }
-}
-
-/// Applies one command. Errors are [`CommandError`]s, each rendering as a
-/// user-meaningful sentence; a command that legitimately does nothing (a
-/// no-op rename, an out-of-range split) returns Ok with no created id and
-/// [`Outcome::applied`] false.
-pub fn apply(
- project: &mut Project,
- mint: &mut IdMint,
- command: Command,
-) -> Result<Outcome, CommandError> {
- if command.has_non_finite() {
- return Err(CommandError::NotANumber);
- }
- match command {
- Command::AddMedia { item } => {
- if project
- .media
- .iter()
- .any(|existing| existing.path == item.path)
- {
- return Ok(Outcome::default());
- }
- let id = mint.next("m");
- project.media.push(MediaItem {
- id: id.clone(),
- path: item.path,
- name: item.name,
- duration: item.duration,
- kind: item.kind,
- width: item.width,
- height: item.height,
- frame_rate: item.frame_rate,
- frame_rate_fraction: item.frame_rate_fraction,
- video_codec: item.video_codec,
- audio_codec: item.audio_codec,
- has_audio: item.has_audio,
- audio_tracks: item.audio_tracks,
- placeholder: false,
- });
- Ok(Outcome {
- created_id: Some(id),
- applied: true,
- })
- }
-
- Command::SetMediaPlaceholder {
- media_id,
- placeholder,
- } => {
- let applied = project
- .media
- .iter_mut()
- .find(|item| item.id == media_id)
- .is_some_and(|item| assign(&mut item.placeholder, placeholder));
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::FillSlot { media_id, item } => {
- let media = project
- .media
- .iter_mut()
- .find(|existing| existing.id == media_id)
- .ok_or(CommandError::SlotGone)?;
- if !media.placeholder {
- return Err(CommandError::NotASlot);
- }
-
- // The slot keeps its id, so every clip that references it keeps
- // working; only the identity behind the id changes.
- media.path = item.path;
- media.name = item.name.clone();
- media.duration = item.duration;
- media.kind = item.kind;
- media.width = item.width;
- media.height = item.height;
- media.frame_rate = item.frame_rate;
- media.frame_rate_fraction = item.frame_rate_fraction;
- media.video_codec = item.video_codec;
- media.audio_codec = item.audio_codec;
- media.has_audio = item.has_audio;
- media.audio_tracks = item.audio_tracks;
- media.placeholder = false;
- let kind = match item.kind {
- MediaKind::Video => ClipKind::Video,
- MediaKind::Audio => ClipKind::Audio,
- MediaKind::Image => ClipKind::Image,
- };
-
- // Slot timing is the template's: start, duration and speed stay
- // put, which is what keeps cuts on the beat. The in-point resets
- // because it referred to the old footage; a clip shorter than its
- // slot freeze-frames on its last frame downstream, which is the
- // renderer's existing behaviour for a trim past the media's end.
- // All timelines, like RemoveMedia: slots are not per-timeline.
- for timeline in project.timelines.iter_mut().map(Arc::make_mut) {
- for clip in timeline.clips_mut() {
- if clip.media_id == media_id {
- clip.source_start = 0.0;
- clip.kind = kind;
- clip.name = item.name.clone();
- // A stream index named against the old file means
- // nothing against the new one.
- clip.audio_stream = None;
- }
- }
- }
- // Filling always changes the project: the target was a
- // placeholder and is one no longer.
- Ok(Outcome {
- created_id: None,
- applied: true,
- })
- }
-
- Command::Batch { commands } => {
- // All or nothing: apply to a staged copy and commit only a fully
- // successful run, so one bad command cannot leave a half-applied
- // batch behind (and the editor records it as one undo step).
- let mut staged = project.clone();
- let mut created = None;
- let mut applied = false;
- for command in commands {
- let outcome = apply(&mut staged, mint, command)?;
- if outcome.created_id.is_some() {
- created = outcome.created_id;
- }
- applied |= outcome.applied;
- }
- *project = staged;
- Ok(Outcome {
- created_id: created,
- applied,
- })
- }
-
- Command::RemoveMedia { media_id } => {
- // All timelines, not just the active one: a shelved clip whose
- // media is gone would linger as a dead reference.
- let media_count = project.media.len();
- project.media.retain(|item| item.id != media_id);
- let mut applied = project.media.len() != media_count;
- for timeline in project.timelines.iter_mut().map(Arc::make_mut) {
- let clip_count = timeline.clips.len();
- timeline.clips.retain(|clip| clip.media_id != media_id);
- applied |= timeline.clips.len() != clip_count;
- }
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::AddClip {
- media_id,
- track_id,
- start,
- } => {
- let media = project
- .media_by_id(&media_id)
- .ok_or(CommandError::MediaGone)?
- .clone();
- let timeline = project.active_mut();
- if timeline.track(&track_id).is_none() {
- return Err(CommandError::TrackGone);
- }
- let id = mint.next("c");
- timeline
- .clips
- .push(Arc::new(default_clip(id.clone(), track_id, &media, start)));
- Ok(Outcome {
- created_id: Some(id),
- applied: true,
- })
- }
-
- Command::AddClipAtFirstFree { media_id, start } => {
- let media = project
- .media_by_id(&media_id)
- .ok_or(CommandError::MediaGone)?
- .clone();
- let duration = match media.kind {
- MediaKind::Image => DEFAULT_IMAGE_DURATION,
- _ => media.duration.unwrap_or(UNKNOWN_DURATION),
- };
- let timeline = project.active_mut();
- let track_id =
- first_free_track(timeline, start, duration).ok_or(CommandError::NoTracks)?;
- let id = mint.next("c");
- timeline
- .clips
- .push(Arc::new(default_clip(id.clone(), track_id, &media, start)));
- Ok(Outcome {
- created_id: Some(id),
- applied: true,
- })
- }
-
- Command::AddTextClip {
- track_id,
- start,
- style,
- duration,
- offset_y,
- } => {
- let style = style.unwrap_or_default();
- let duration = duration
- .unwrap_or(DEFAULT_TEXT_DURATION)
- .max(MIN_CLIP_DURATION);
- let timeline = project.active_mut();
- let track_id = match track_id {
- Some(id) if timeline.track(&id).is_some() => id,
- Some(_) => return Err(CommandError::TrackGone),
- None => {
- first_free_track(timeline, start, duration).ok_or(CommandError::NoTracks)?
- }
- };
- let id = mint.next("c");
- timeline.clips.push(Arc::new(Clip {
- id: id.clone(),
- track_id,
- media_id: String::new(),
- name: first_line(&style.content),
- kind: ClipKind::Text,
- start: start.max(0.0),
- duration,
- source_start: 0.0,
- volume: 1.0,
- fade_in: 0.0,
- fade_out: 0.0,
- scale: 1.0,
- offset_x: 0.0,
- offset_y: offset_y.unwrap_or(0.0).clamp(-MAX_OFFSET, MAX_OFFSET),
- rotation: 0.0,
- stretch_x: 1.0,
- stretch_y: 1.0,
- opacity: 1.0,
- speed: 1.0,
- preserve_pitch: true,
- speed_curve: None,
- reverse: false,
- animation_in: None,
- animation_out: None,
- animation_combo: None,
- keys: Vec::new(),
- flip_h: false,
- flip_v: false,
- blend: String::new(),
- crop: None,
- cutout: None,
- filters: Vec::new(),
- video_effects: Vec::new(),
- audio_stream: None,
- muted: None,
- detached_from: None,
- transition_in: None,
- text: Some(style),
- }));
- Ok(Outcome {
- created_id: Some(id),
- applied: true,
- })
- }
-
- Command::AddLayerClip {
- track_id,
- start,
- duration,
- effect_id,
- name,
- } => {
- let duration = duration
- .unwrap_or(DEFAULT_LAYER_DURATION)
- .max(MIN_CLIP_DURATION);
- let timeline = project.active_mut();
- let track_id = match track_id {
- Some(id) if timeline.track(&id).is_some() => id,
- Some(_) => return Err(CommandError::TrackGone),
- None => {
- first_free_track(timeline, start, duration).ok_or(CommandError::NoTracks)?
- }
- };
- let id = mint.next("c");
- timeline.clips.push(Arc::new(Clip {
- id: id.clone(),
- track_id,
- media_id: String::new(),
- name: if name.trim().is_empty() {
- effect_id.clone()
- } else {
- name
- },
- kind: ClipKind::Layer,
- start: start.max(0.0),
- duration,
- source_start: 0.0,
- volume: 1.0,
- fade_in: 0.0,
- fade_out: 0.0,
- scale: 1.0,
- offset_x: 0.0,
- offset_y: 0.0,
- rotation: 0.0,
- stretch_x: 1.0,
- stretch_y: 1.0,
- opacity: 1.0,
- speed: 1.0,
- preserve_pitch: true,
- speed_curve: None,
- reverse: false,
- animation_in: None,
- animation_out: None,
- animation_combo: None,
- keys: Vec::new(),
- flip_h: false,
- flip_v: false,
- blend: String::new(),
- crop: None,
- cutout: None,
- filters: Vec::new(),
- video_effects: vec![AppliedFilter::new(effect_id)],
- audio_stream: None,
- muted: None,
- detached_from: None,
- transition_in: None,
- text: None,
- }));
- Ok(Outcome {
- created_id: Some(id),
- applied: true,
- })
- }
-
- Command::MoveClips { moves } => {
- let timeline = project.active_mut();
- let track_ids: HashSet<String> = timeline
- .tracks
- .iter()
- .map(|track| track.id.clone())
- .collect();
- let mut applied = false;
- for wanted in moves {
- if let Some(clip) = timeline.clip_mut(&wanted.clip_id) {
- applied |= assign(&mut clip.start, wanted.start.max(0.0));
- if track_ids.contains(&wanted.track_id) {
- applied |= assign(&mut clip.track_id, wanted.track_id);
- }
- }
- }
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::TrimClip {
- clip_id,
- edge,
- delta,
- } => {
- let timeline = project.active_mut();
- let Some(clip) = timeline.clip_mut(&clip_id) else {
- return Ok(Outcome::default());
- };
- let applied = match edge {
- TrimEdge::End => {
- let duration = (clip.duration + delta).max(MIN_CLIP_DURATION);
- assign(&mut clip.duration, duration)
- }
- TrimEdge::Start => {
- // Dragging the head moves the in-point too, so the pixels
- // 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 = 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)
- | assign(&mut clip.source_start, source_start)
- }
- };
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::SplitClips { clip_ids, time } => {
- let timeline = project.active_mut();
- let mut created = None;
- for clip_id in clip_ids {
- let Some(index) = timeline.clips.iter().position(|clip| clip.id == clip_id) else {
- continue;
- };
- {
- // 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 = timeline.clip_at_mut(index);
- let offset = time - clip.start;
- if offset > MIN_CLIP_DURATION
- && offset < clip.duration - MIN_CLIP_DURATION
- && clip.speed_curve.is_some()
- {
- clip.speed_curve = None;
- }
- }
- let clip: &Clip = &timeline.clips[index];
- let offset = time - clip.start;
- 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 = 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.clip_at_mut(index).duration = offset;
- timeline.clip_at_mut(index).source_start = head_source;
- timeline.clips.insert(index + 1, Arc::new(tail));
- }
- // A split always mints the tail, so "minted anything" and
- // "changed anything" are the same fact here.
- let applied = created.is_some();
- Ok(Outcome {
- created_id: created,
- applied,
- })
- }
-
- Command::FreezeFrame {
- clip_id,
- time,
- duration,
- still,
- } => {
- let hold = duration
- .filter(|value| *value > 0.0)
- .unwrap_or(DEFAULT_FREEZE_DURATION)
- .max(MIN_CLIP_DURATION);
-
- let (kind, media_id, track_id, start, clip_duration, speed, source_start, picture) = {
- let timeline = project.active();
- let Some(clip) = timeline.clip(&clip_id) else {
- return Ok(Outcome::default());
- };
- if clip.kind != ClipKind::Video && clip.kind != ClipKind::Image {
- return Ok(Outcome::default());
- }
- let offset = time - clip.start;
- if offset <= MIN_CLIP_DURATION || offset >= clip.duration - MIN_CLIP_DURATION {
- return Ok(Outcome::default());
- }
- (
- clip.kind,
- clip.media_id.clone(),
- clip.track_id.clone(),
- clip.start,
- clip.duration,
- clip.speed,
- clip.source_start,
- clip.clone(),
- )
- };
-
- let freeze_media_id = if kind == ClipKind::Image && still.is_none() {
- media_id
- } else {
- let Some(item) = still else {
- return Ok(Outcome::default());
- };
- if let Some(existing) = project.media.iter().find(|media| media.path == item.path) {
- existing.id.clone()
- } else {
- let id = mint.next("m");
- project.media.push(MediaItem {
- id: id.clone(),
- path: item.path,
- name: item.name,
- duration: item.duration,
- kind: MediaKind::Image,
- width: item.width,
- height: item.height,
- frame_rate: item.frame_rate,
- frame_rate_fraction: item.frame_rate_fraction,
- video_codec: item.video_codec,
- audio_codec: None,
- has_audio: false,
- audio_tracks: Vec::new(),
- placeholder: false,
- });
- id
- }
- };
-
- let timeline = project.active_mut();
- let Some(index) = timeline.clips.iter().position(|clip| clip.id == clip_id) else {
- return Ok(Outcome::default());
- };
- // The cut is a split's, so it leaves the pieces as a split does:
- // 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.clip_at_mut(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 = Clip::clone(&timeline.clips[index]);
- tail.id = mint.next("c");
- tail.start = time;
- tail.duration = clip_duration - offset;
- tail.source_start = tail_source;
- tail.transition_in = None;
- timeline.clip_at_mut(index).duration = offset;
- timeline.clip_at_mut(index).source_start = head_source;
- timeline.clips.insert(index + 1, Arc::new(tail));
-
- // Ripple every later placement on this track (including the new
- // tail) so the freeze does not sit on top of the remainder.
- for clip in timeline.clips_mut() {
- if clip.track_id == track_id && clip.start >= time {
- clip.start += hold;
- }
- }
-
- // The still is the source clip turned into a picture: cloning it
- // first carries every look field - transform, effects, crop,
- // flips, whatever the model grows - and then the hold's own
- // facts overwrite the moving ones.
- let freeze_id = mint.next("c");
- let mut frozen = picture;
- frozen.id = freeze_id.clone();
- frozen.track_id = track_id;
- frozen.kind = ClipKind::Image;
- frozen.media_id = freeze_media_id;
- frozen.start = time;
- frozen.duration = hold;
- frozen.source_start = 0.0;
- frozen.speed = 1.0;
- frozen.speed_curve = None;
- frozen.reverse = false;
- frozen.volume = 1.0;
- frozen.fade_in = 0.0;
- frozen.fade_out = 0.0;
- frozen.filters = Vec::new();
- frozen.muted = None;
- frozen.detached_from = None;
- frozen.transition_in = None;
- frozen.text = None;
- timeline.clips.push(Arc::new(frozen));
-
- Ok(Outcome {
- created_id: Some(freeze_id),
- applied: true,
- })
- }
-
- Command::MergeClips { clip_ids } => {
- let timeline = project.active_mut();
- if let Some(reason) = why_not_merge(timeline, &clip_ids) {
- return Err(CommandError::CannotMerge { reason });
- }
- let mut ordered: Vec<Clip> = clip_ids
- .iter()
- .filter_map(|id| timeline.clip(id).cloned())
- .collect();
- ordered.sort_by(|left, right| left.start.total_cmp(&right.start));
- let first = ordered.first().expect("validated above").clone();
- let last = ordered.last().expect("validated above");
- let merged_duration = last.start + last.duration - first.start;
-
- // A set, not a Vec: the retain below tests every clip on the
- // timeline against it.
- let doomed: HashSet<String> =
- ordered.iter().skip(1).map(|clip| clip.id.clone()).collect();
- timeline.clips.retain(|clip| !doomed.contains(&clip.id));
- let survivor = timeline
- .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),
- applied: true,
- })
- }
-
- Command::RemoveClips { clip_ids } => {
- let timeline = project.active_mut();
- let doomed: HashSet<&str> = clip_ids.iter().map(String::as_str).collect();
- let clip_count = timeline.clips.len();
- timeline
- .clips
- .retain(|clip| !doomed.contains(clip.id.as_str()));
- let applied = timeline.clips.len() != clip_count;
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::UpdateClip { clip_id, patch } => {
- let timeline = project.active_mut();
- let Some(clip) = timeline.clip_mut(&clip_id) else {
- return Ok(Outcome::default());
- };
- let mut applied = false;
- if let Some(name) = patch.name {
- applied |= assign(&mut clip.name, name);
- }
- if let Some(volume) = patch.volume {
- applied |= assign(&mut clip.volume, volume.max(0.0));
- }
- if let Some(fade_in) = patch.fade_in {
- applied |= assign(&mut clip.fade_in, fade_in.max(0.0));
- }
- if let Some(fade_out) = patch.fade_out {
- applied |= assign(&mut clip.fade_out, fade_out.max(0.0));
- }
- if let Some(opacity) = patch.opacity {
- applied |= assign(&mut clip.opacity, opacity.clamp(0.0, 1.0));
- }
- 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);
- }
- if let Some(flip) = patch.flip_h {
- applied |= assign(&mut clip.flip_h, flip);
- }
- if let Some(flip) = patch.flip_v {
- applied |= assign(&mut clip.flip_v, flip);
- }
- if let Some(blend) = patch.blend {
- let blend = if blend == "normal" {
- String::new()
- } else {
- blend
- };
- applied |= assign(&mut clip.blend, blend);
- }
- if let Some(crop) = patch.crop {
- let crop = crop.map(Crop::tidy).filter(|crop| !crop.is_none());
- applied |= assign(&mut clip.crop, crop);
- }
- if let Some(filters) = patch.filters {
- applied |= assign(&mut clip.filters, filters);
- }
- if let Some(effects) = patch.video_effects {
- applied |= assign(&mut clip.video_effects, effects);
- }
- if let Some(transition) = patch.transition_in {
- applied |= assign(&mut clip.transition_in, transition);
- }
- if let Some(text) = patch.text {
- // The name follows the words, like addTextClip snapshots it.
- if let Some(style) = &text {
- applied |= assign(&mut clip.name, first_line(&style.content));
- }
- applied |= assign(&mut clip.text, text);
- }
- if let Some(stream) = patch.audio_stream {
- applied |= assign(&mut clip.audio_stream, stream);
- }
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::SetClipSpeed { clip_id, speed } => {
- let timeline = project.active_mut();
- let Some(clip) = timeline.clip_mut(&clip_id) else {
- return Ok(Outcome::default());
- };
- // The amount of source covered is held constant - that is what
- // makes this a speed change rather than a trim.
- let next = speed.clamp(MIN_SPEED, MAX_SPEED);
- let source_covered = clip.duration * clip.speed;
- // Bitwise so no assignment is short-circuited away. A rate set
- // by hand is a constant rate: the curve goes.
- let applied = assign(&mut clip.speed, next)
- | assign(
- &mut clip.duration,
- (source_covered / next).max(MIN_CLIP_DURATION),
- )
- | assign(&mut clip.speed_curve, None);
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::SetClipCutout { clip_id, cutout } => {
- let timeline = project.active_mut();
- let Some(clip) = timeline.clip_mut(&clip_id) else {
- return Ok(Outcome::default());
- };
- let applied = assign(&mut clip.cutout, cutout.map(Cutout::tidy));
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::AddCutoutStroke { clip_id, stroke } => {
- let timeline = project.active_mut();
- let Some(clip) = timeline.clip_mut(&clip_id) else {
- return Ok(Outcome::default());
- };
- let Some(stroke) = stroke.tidy() else {
- return Ok(Outcome::default());
- };
- let cutout = clip.cutout.get_or_insert_with(Cutout::auto);
- cutout.mode = CutoutMode::Custom;
- cutout.strokes.push(stroke);
- Ok(Outcome {
- created_id: None,
- applied: true,
- })
- }
-
- Command::SetClipAnimation {
- clip_id,
- slot,
- animation,
- } => {
- let timeline = project.active_mut();
- let Some(clip) = timeline.clip_mut(&clip_id) else {
- return Ok(Outcome::default());
- };
- let animation = animation
- .filter(|set| crate::animation::index_of(slot, &set.preset).is_some())
- .map(|set| ClipAnimation {
- preset: set.preset,
- duration: set.duration.clamp(0.05, 60.0),
- });
- let field = match slot {
- AnimationSlot::In => &mut clip.animation_in,
- AnimationSlot::Out => &mut clip.animation_out,
- AnimationSlot::Combo => &mut clip.animation_combo,
- };
- let applied = assign(field, animation);
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::SetClipKey {
- clip_id,
- property,
- at,
- value,
- ease,
- } => {
- let timeline = project.active_mut();
- let Some(clip) = timeline.clip_mut(&clip_id) else {
- return Ok(Outcome::default());
- };
- if !at.is_finite() || !value.is_finite() {
- return Ok(Outcome::default());
- }
- // Clamped the way the field itself is, so a key can never hold a
- // value the constant would have been refused. The clamps are the
- // ones ClipPatch applies; keeping them here as well is what stops
- // a key being the back door round them.
- let value = match property {
- KeyProperty::Scale => value.clamp(MIN_SCALE, MAX_SCALE),
- KeyProperty::Opacity => value.clamp(0.0, 1.0),
- // No ceiling, matching ClipPatch: the level fader goes to
- // +24 dB because quiet material needs it, and a key is the
- // same value at a different instant.
- KeyProperty::Volume => value.max(0.0),
- KeyProperty::OffsetX | KeyProperty::OffsetY | KeyProperty::Rotation => value,
- };
- let before = clip.keys.clone();
- clip.set_key(property, at, value, ease);
- Ok(Outcome {
- created_id: None,
- applied: clip.keys != before,
- })
- }
-
- Command::ClearClipKey {
- clip_id,
- property,
- at,
- } => {
- let timeline = project.active_mut();
- let Some(clip) = timeline.clip_mut(&clip_id) else {
- return Ok(Outcome::default());
- };
- let applied = clip.clear_key(property, at);
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::ClearClipKeys { clip_id, property } => {
- let timeline = project.active_mut();
- let Some(clip) = timeline.clip_mut(&clip_id) else {
- return Ok(Outcome::default());
- };
- let applied = clip.clear_keys(property);
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::SetEffectKey {
- clip_id,
- entry,
- key,
- at,
- value,
- ease,
- } => {
- let timeline = project.active_mut();
- let Some(link) = timeline
- .clip_mut(&clip_id)
- .and_then(|clip| clip.video_effects.get_mut(entry))
- else {
- return Ok(Outcome::default());
- };
- if !at.is_finite() || !value.is_finite() {
- return Ok(Outcome::default());
- }
- let before = link.keys.clone();
- link.set_key(&key, at, value, ease);
- Ok(Outcome {
- created_id: None,
- applied: link.keys != before,
- })
- }
-
- Command::ClearEffectKey {
- clip_id,
- entry,
- key,
- at,
- } => {
- let timeline = project.active_mut();
- let Some(link) = timeline
- .clip_mut(&clip_id)
- .and_then(|clip| clip.video_effects.get_mut(entry))
- else {
- return Ok(Outcome::default());
- };
- let applied = link.clear_key(&key, at);
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::ClearEffectKeys {
- clip_id,
- entry,
- key,
- } => {
- let timeline = project.active_mut();
- let Some(link) = timeline
- .clip_mut(&clip_id)
- .and_then(|clip| clip.video_effects.get_mut(entry))
- else {
- return Ok(Outcome::default());
- };
- let applied = link.clear_keys(&key);
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::SetClipSpeedCurve { clip_id, curve } => {
- let timeline = project.active_mut();
- let Some(clip) = timeline.clip_mut(&clip_id) else {
- return Ok(Outcome::default());
- };
- let curve = curve.filter(|points| crate::speed::curve_of(points).is_some());
- let source_covered = clip.duration * clip.speed;
- let mean = curve
- .as_ref()
- .map(|points| crate::speed::mean_of(points))
- .unwrap_or(clip.speed)
- .clamp(MIN_SPEED, MAX_SPEED);
- let applied = assign(&mut clip.speed_curve, curve)
- | assign(&mut clip.speed, mean)
- | assign(
- &mut clip.duration,
- (source_covered / mean).max(MIN_CLIP_DURATION),
- );
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::SetClipTransform {
- clip_id,
- scale,
- offset_x,
- offset_y,
- rotation,
- stretch_x,
- stretch_y,
- } => {
- let timeline = project.active_mut();
- let Some(clip) = timeline.clip_mut(&clip_id) else {
- return Ok(Outcome::default());
- };
- let mut applied = false;
- if let Some(scale) = scale {
- applied |= assign(&mut clip.scale, scale.clamp(MIN_SCALE, MAX_SCALE));
- }
- if let Some(offset) = offset_x {
- applied |= assign(&mut clip.offset_x, offset.clamp(-MAX_OFFSET, MAX_OFFSET));
- }
- if let Some(offset) = offset_y {
- applied |= assign(&mut clip.offset_y, offset.clamp(-MAX_OFFSET, MAX_OFFSET));
- }
- if let Some(rotation) = rotation {
- 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));
- }
- if let Some(stretch) = stretch_y {
- applied |= assign(&mut clip.stretch_y, stretch.clamp(MIN_STRETCH, MAX_STRETCH));
- }
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::DetachAudio { clip_id } => {
- // What comes off, as `(stream, name)`: one sound clip per audio
- // track when the file lists several - a recording that kept the
- // desktop and the microphone apart stays apart, each on a lane
- // of its own - else the one stream the video clip was playing.
- let sounds: Vec<(Option<u32>, String)> = {
- let timeline = project.active();
- let Some(clip) = timeline.clip(&clip_id) else {
- return Ok(Outcome::default());
- };
- let media = project.media_by_id(&clip.media_id);
- let has_audio = clip.kind == ClipKind::Video
- && clip.muted != Some(true)
- && media.is_some_and(|media| media.has_audio)
- && !timeline
- .clips
- .iter()
- .any(|other| other.detached_from.as_deref() == Some(clip_id.as_str()));
- if !has_audio {
- return Ok(Outcome::default());
- }
- match media {
- Some(media) if media.audio_tracks.len() > 1 => media
- .audio_tracks
- .iter()
- .enumerate()
- .map(|(position, track)| {
- let label = if track.title.is_empty() {
- format!("Track {}", position + 1)
- } else {
- track.title.clone()
- };
- (Some(track.index), format!("{} · {label}", clip.name))
- })
- .collect(),
- _ => vec![(clip.audio_stream, clip.name.clone())],
- }
- };
-
- let timeline = project.active_mut();
- let clip = timeline.clip(&clip_id).expect("checked above").clone();
- let mut first_sound = None;
- for (stream, name) in sounds {
- // A lane free for the whole span, or a fresh one. Each sound
- // placed takes its lane, so the next looks past it.
- let track_id = {
- let end = clip.start + clip.duration;
- let free = timeline.tracks.iter().find(|track| {
- !timeline.clips.iter().any(|other| {
- other.track_id == track.id
- && other.start < end
- && clip.start < other.start + other.duration
- })
- });
- match free {
- Some(track) => track.id.clone(),
- None => {
- let id = mint.next("t");
- timeline.tracks.push(Track {
- id: id.clone(),
- visible: true,
- muted: false,
- });
- id
- }
- }
- };
-
- let mut sound = clip.clone();
- sound.id = mint.next("c");
- sound.track_id = track_id;
- sound.name = name;
- sound.kind = ClipKind::Audio;
- sound.video_effects = Vec::new();
- sound.transition_in = None;
- sound.detached_from = Some(clip_id.clone());
- sound.muted = None;
- sound.audio_stream = stream;
- first_sound.get_or_insert_with(|| sound.id.clone());
- timeline.clips.push(Arc::new(sound));
- }
-
- let video = timeline.clip_mut(&clip_id).expect("still present");
- video.muted = Some(true);
- video.filters = Vec::new();
- Ok(Outcome {
- created_id: first_sound,
- applied: true,
- })
- }
-
- Command::ReattachAudio { clip_id } => {
- let timeline = project.active_mut();
- let Some(clip) = timeline.clip(&clip_id) else {
- return Ok(Outcome::default());
- };
- let video_id = match (&clip.kind, &clip.detached_from) {
- (ClipKind::Audio, Some(source)) => source.clone(),
- _ => clip.id.clone(),
- };
- if timeline.clip(&video_id).is_none() {
- return Ok(Outcome::default());
- }
- let sounds: Vec<Clip> = timeline
- .clips
- .iter()
- .filter(|other| other.detached_from.as_deref() == Some(video_id.as_str()))
- .map(|other| Clip::clone(other))
- .collect();
- if sounds.is_empty() {
- return Ok(Outcome::default());
- }
- // A set, not a Vec: the retain below tests every clip on the
- // timeline against it.
- let doomed: HashSet<String> = sounds.iter().map(|sound| sound.id.clone()).collect();
- timeline.clips.retain(|other| !doomed.contains(&other.id));
- let video = timeline.clip_mut(&video_id).expect("checked above");
- video.muted = None;
- video.filters = sounds[0].filters.clone();
- // Reaching here means at least one sound clip was deleted.
- Ok(Outcome {
- created_id: None,
- applied: true,
- })
- }
-
- Command::AddTrack => {
- let timeline = project.active_mut();
- let id = mint.next("t");
- timeline.tracks.push(Track {
- id: id.clone(),
- visible: true,
- muted: false,
- });
- Ok(Outcome {
- created_id: Some(id),
- applied: true,
- })
- }
-
- Command::RemoveTrack { track_id } => {
- let timeline = project.active_mut();
- if timeline.tracks.len() <= 1 {
- return Err(CommandError::LastTrack);
- }
- let track_count = timeline.tracks.len();
- timeline.tracks.retain(|track| track.id != track_id);
- timeline.clips.retain(|clip| clip.track_id != track_id);
- // Clips only ever sit on existing tracks, so an unknown id - the
- // tolerated no-op - removes neither.
- let applied = timeline.tracks.len() != track_count;
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::SetTrackFlag {
- track_id,
- flag,
- value,
- } => {
- let timeline = project.active_mut();
- let applied = timeline
- .tracks
- .iter_mut()
- .find(|track| track.id == track_id)
- .is_some_and(|track| match flag {
- TrackFlag::Visible => assign(&mut track.visible, value),
- TrackFlag::Muted => assign(&mut track.muted, value),
- });
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::AddTimeline => {
- let id = mint.next("tl");
- let name = next_numbered(
- "Timeline",
- project
- .timelines
- .iter()
- .map(|timeline| timeline.name.clone()),
- );
- let tracks = (1..=4)
- .map(|_| Track {
- id: mint.next("t"),
- visible: true,
- muted: false,
- })
- .collect();
- // Born at the frame of the timeline you were looking at: the
- // likeliest second timeline is another cut of the same picture,
- // and the one that is not is a sheet away from being told so.
- let video = project.active().video;
- project.timelines.push(Arc::new(Timeline {
- id: id.clone(),
- name,
- video,
- tracks,
- clips: Vec::new(),
- }));
- project.active_timeline_id = id.clone();
- Ok(Outcome {
- created_id: Some(id),
- applied: true,
- })
- }
-
- Command::SetTimelineVideo { timeline_id, video } => {
- if !video.is_sane() {
- return Ok(Outcome::default());
- }
- let applied = project
- .timelines
- .iter_mut()
- .find(|timeline| timeline.id == timeline_id)
- .is_some_and(|timeline| assign(&mut Arc::make_mut(timeline).video, video));
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::RemoveTimeline { timeline_id } => {
- if project.timelines.len() <= 1 {
- return Err(CommandError::LastTimeline);
- }
- let Some(index) = project
- .timelines
- .iter()
- .position(|timeline| timeline.id == timeline_id)
- else {
- return Ok(Outcome::default());
- };
- if project.active_timeline_id == timeline_id {
- let neighbour = if index + 1 < project.timelines.len() {
- index + 1
- } else {
- index - 1
- };
- project.active_timeline_id = project.timelines[neighbour].id.clone();
- }
- project.timelines.remove(index);
- Ok(Outcome {
- created_id: None,
- applied: true,
- })
- }
-
- Command::RenameTimeline { timeline_id, name } => {
- let trimmed = name.trim();
- if trimmed.is_empty() {
- return Ok(Outcome::default());
- }
- let applied = project
- .timelines
- .iter_mut()
- .find(|timeline| timeline.id == timeline_id)
- .is_some_and(|timeline| {
- assign(&mut Arc::make_mut(timeline).name, trimmed.to_owned())
- });
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::SelectTimeline { timeline_id } => {
- // Short-circuiting is right here: an unknown id must not touch
- // the selection at all.
- let applied = project
- .timelines
- .iter()
- .any(|timeline| timeline.id == timeline_id)
- && assign(&mut project.active_timeline_id, timeline_id);
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::MoveTimeline { timeline_id, index } => {
- let Some(from) = project
- .timelines
- .iter()
- .position(|timeline| timeline.id == timeline_id)
- else {
- return Ok(Outcome::default());
- };
- let to = index.min(project.timelines.len() - 1);
- if to == from {
- return Ok(Outcome::default());
- }
- let timeline = project.timelines.remove(from);
- project.timelines.insert(to, timeline);
- Ok(Outcome {
- created_id: None,
- applied: true,
- })
- }
-
- Command::AddFont { family, path } => {
- if project.fonts.iter().any(|font| font.path == path) {
- return Ok(Outcome::default());
- }
- project.fonts.push(CustomFont { family, path });
- Ok(Outcome {
- created_id: None,
- applied: true,
- })
- }
-
- Command::RemoveFont { family } => {
- // Clips keep the family name: the face may come back when the
- // file does.
- let font_count = project.fonts.len();
- project.fonts.retain(|font| font.family != family);
- let applied = project.fonts.len() != font_count;
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
-
- Command::UpdateMediaPath { media_id, new_path } => {
- let applied = project
- .media
- .iter_mut()
- .find(|item| item.id == media_id)
- .is_some_and(|item| assign(&mut item.path, new_path));
- Ok(Outcome {
- created_id: None,
- applied,
- })
- }
- }
-}
diff --git a/src/crates/concat-project/src/commands/audio.rs b/src/crates/concat-project/src/commands/audio.rs
new file mode 100644
index 00000000..5295369f
--- /dev/null
+++ b/src/crates/concat-project/src/commands/audio.rs
@@ -0,0 +1,146 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! Taking a video's sound out onto its own lane, and putting it back.
+//!
+//! One arm per command, exactly as [`super::apply`] routes them here;
+//! everything these arms share lives in the parent module.
+
+use super::*;
+
+/// Applies one of this module's commands. Any other is a routing error.
+pub(super) fn apply(
+ project: &mut Project,
+ mint: &mut IdMint,
+ command: Command,
+) -> Result<Outcome, CommandError> {
+ match command {
+ Command::DetachAudio { clip_id } => {
+ // What comes off, as `(stream, name)`: one sound clip per audio
+ // track when the file lists several - a recording that kept the
+ // desktop and the microphone apart stays apart, each on a lane
+ // of its own - else the one stream the video clip was playing.
+ let sounds: Vec<(Option<u32>, String)> = {
+ let timeline = project.active();
+ let Some(clip) = timeline.clip(&clip_id) else {
+ return Ok(Outcome::default());
+ };
+ let media = project.media_by_id(&clip.media_id);
+ let has_audio = clip.kind == ClipKind::Video
+ && clip.muted != Some(true)
+ && media.is_some_and(|media| media.has_audio)
+ && !timeline
+ .clips
+ .iter()
+ .any(|other| other.detached_from.as_deref() == Some(clip_id.as_str()));
+ if !has_audio {
+ return Ok(Outcome::default());
+ }
+ match media {
+ Some(media) if media.audio_tracks.len() > 1 => media
+ .audio_tracks
+ .iter()
+ .enumerate()
+ .map(|(position, track)| {
+ let label = if track.title.is_empty() {
+ format!("Track {}", position + 1)
+ } else {
+ track.title.clone()
+ };
+ (Some(track.index), format!("{} · {label}", clip.name))
+ })
+ .collect(),
+ _ => vec![(clip.audio_stream, clip.name.clone())],
+ }
+ };
+
+ let timeline = project.active_mut();
+ let clip = timeline.clip(&clip_id).expect("checked above").clone();
+ let mut first_sound = None;
+ for (stream, name) in sounds {
+ // A lane free for the whole span, or a fresh one. Each sound
+ // placed takes its lane, so the next looks past it.
+ let track_id = {
+ let end = clip.start + clip.duration;
+ let free = timeline.tracks.iter().find(|track| {
+ !timeline.clips.iter().any(|other| {
+ other.track_id == track.id
+ && other.start < end
+ && clip.start < other.start + other.duration
+ })
+ });
+ match free {
+ Some(track) => track.id.clone(),
+ None => {
+ let id = mint.next("t");
+ timeline.tracks.push(Track {
+ id: id.clone(),
+ visible: true,
+ muted: false,
+ });
+ id
+ }
+ }
+ };
+
+ let mut sound = clip.clone();
+ sound.id = mint.next("c");
+ sound.track_id = track_id;
+ sound.name = name;
+ sound.kind = ClipKind::Audio;
+ sound.video_effects = Vec::new();
+ sound.transition_in = None;
+ sound.detached_from = Some(clip_id.clone());
+ sound.muted = None;
+ sound.audio_stream = stream;
+ first_sound.get_or_insert_with(|| sound.id.clone());
+ timeline.clips.push(Arc::new(sound));
+ }
+
+ let video = timeline.clip_mut(&clip_id).expect("still present");
+ video.muted = Some(true);
+ video.filters = Vec::new();
+ Ok(Outcome {
+ created_id: first_sound,
+ applied: true,
+ })
+ }
+
+ Command::ReattachAudio { clip_id } => {
+ let timeline = project.active_mut();
+ let Some(clip) = timeline.clip(&clip_id) else {
+ return Ok(Outcome::default());
+ };
+ let video_id = match (&clip.kind, &clip.detached_from) {
+ (ClipKind::Audio, Some(source)) => source.clone(),
+ _ => clip.id.clone(),
+ };
+ if timeline.clip(&video_id).is_none() {
+ return Ok(Outcome::default());
+ }
+ let sounds: Vec<Clip> = timeline
+ .clips
+ .iter()
+ .filter(|other| other.detached_from.as_deref() == Some(video_id.as_str()))
+ .map(|other| Clip::clone(other))
+ .collect();
+ if sounds.is_empty() {
+ return Ok(Outcome::default());
+ }
+ // A set, not a Vec: the retain below tests every clip on the
+ // timeline against it.
+ let doomed: HashSet<String> = sounds.iter().map(|sound| sound.id.clone()).collect();
+ timeline.clips.retain(|other| !doomed.contains(&other.id));
+ let video = timeline.clip_mut(&video_id).expect("checked above");
+ video.muted = None;
+ video.filters = sounds[0].filters.clone();
+ // Reaching here means at least one sound clip was deleted.
+ Ok(Outcome {
+ created_id: None,
+ applied: true,
+ })
+ }
+
+ _ => unreachable!("commands::apply routes only this module's commands here"),
+ }
+}
diff --git a/src/crates/concat-project/src/commands/clips.rs b/src/crates/concat-project/src/commands/clips.rs
new file mode 100644
index 00000000..6b389ce1
--- /dev/null
+++ b/src/crates/concat-project/src/commands/clips.rs
@@ -0,0 +1,546 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! Placing, moving and cutting clips: the edits that change what is on the timeline and when.
+//!
+//! One arm per command, exactly as [`super::apply`] routes them here;
+//! everything these arms share lives in the parent module.
+
+use super::*;
+
+/// Applies one of this module's commands. Any other is a routing error.
+pub(super) fn apply(
+ project: &mut Project,
+ mint: &mut IdMint,
+ command: Command,
+) -> Result<Outcome, CommandError> {
+ match command {
+ Command::AddClip {
+ media_id,
+ track_id,
+ start,
+ } => {
+ let media = project
+ .media_by_id(&media_id)
+ .ok_or(CommandError::MediaGone)?
+ .clone();
+ let timeline = project.active_mut();
+ if timeline.track(&track_id).is_none() {
+ return Err(CommandError::TrackGone);
+ }
+ let id = mint.next("c");
+ timeline
+ .clips
+ .push(Arc::new(default_clip(id.clone(), track_id, &media, start)));
+ Ok(Outcome {
+ created_id: Some(id),
+ applied: true,
+ })
+ }
+
+ Command::AddClipAtFirstFree { media_id, start } => {
+ let media = project
+ .media_by_id(&media_id)
+ .ok_or(CommandError::MediaGone)?
+ .clone();
+ let duration = match media.kind {
+ MediaKind::Image => DEFAULT_IMAGE_DURATION,
+ _ => media.duration.unwrap_or(UNKNOWN_DURATION),
+ };
+ let timeline = project.active_mut();
+ let track_id =
+ first_free_track(timeline, start, duration).ok_or(CommandError::NoTracks)?;
+ let id = mint.next("c");
+ timeline
+ .clips
+ .push(Arc::new(default_clip(id.clone(), track_id, &media, start)));
+ Ok(Outcome {
+ created_id: Some(id),
+ applied: true,
+ })
+ }
+
+ Command::AddTextClip {
+ track_id,
+ start,
+ style,
+ duration,
+ offset_y,
+ } => {
+ let style = style.unwrap_or_default();
+ let duration = duration
+ .unwrap_or(DEFAULT_TEXT_DURATION)
+ .max(MIN_CLIP_DURATION);
+ let timeline = project.active_mut();
+ let track_id = match track_id {
+ Some(id) if timeline.track(&id).is_some() => id,
+ Some(_) => return Err(CommandError::TrackGone),
+ None => {
+ first_free_track(timeline, start, duration).ok_or(CommandError::NoTracks)?
+ }
+ };
+ let id = mint.next("c");
+ let mut clip = Clip::blank(
+ id.clone(),
+ track_id,
+ ClipKind::Text,
+ first_line(&style.content),
+ start,
+ duration,
+ );
+ clip.offset_y = offset_y.unwrap_or(0.0).clamp(-MAX_OFFSET, MAX_OFFSET);
+ clip.text = Some(style);
+ timeline.clips.push(Arc::new(clip));
+ Ok(Outcome {
+ created_id: Some(id),
+ applied: true,
+ })
+ }
+
+ Command::AddLayerClip {
+ track_id,
+ start,
+ duration,
+ effect_id,
+ name,
+ } => {
+ let duration = duration
+ .unwrap_or(DEFAULT_LAYER_DURATION)
+ .max(MIN_CLIP_DURATION);
+ let timeline = project.active_mut();
+ let track_id = match track_id {
+ Some(id) if timeline.track(&id).is_some() => id,
+ Some(_) => return Err(CommandError::TrackGone),
+ None => {
+ first_free_track(timeline, start, duration).ok_or(CommandError::NoTracks)?
+ }
+ };
+ let id = mint.next("c");
+ let name = if name.trim().is_empty() {
+ effect_id.clone()
+ } else {
+ name
+ };
+ let mut clip =
+ Clip::blank(id.clone(), track_id, ClipKind::Layer, name, start, duration);
+ clip.video_effects = vec![AppliedFilter::new(effect_id)];
+ timeline.clips.push(Arc::new(clip));
+ Ok(Outcome {
+ created_id: Some(id),
+ applied: true,
+ })
+ }
+
+ Command::MoveClips { moves } => {
+ let timeline = project.active_mut();
+ let track_ids: HashSet<String> = timeline
+ .tracks
+ .iter()
+ .map(|track| track.id.clone())
+ .collect();
+ let mut applied = false;
+ for wanted in moves {
+ if let Some(clip) = timeline.clip_mut(&wanted.clip_id) {
+ applied |= assign(&mut clip.start, wanted.start.max(0.0));
+ if track_ids.contains(&wanted.track_id) {
+ applied |= assign(&mut clip.track_id, wanted.track_id);
+ }
+ }
+ }
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::TrimClip {
+ clip_id,
+ edge,
+ delta,
+ } => {
+ let timeline = project.active_mut();
+ let Some(clip) = timeline.clip_mut(&clip_id) else {
+ return Ok(Outcome::default());
+ };
+ let applied = match edge {
+ TrimEdge::End => {
+ let duration = (clip.duration + delta).max(MIN_CLIP_DURATION);
+ assign(&mut clip.duration, duration)
+ }
+ TrimEdge::Start => {
+ // Dragging the head moves the in-point too, so the pixels
+ // 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 = 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)
+ | assign(&mut clip.source_start, source_start)
+ }
+ };
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::SplitClips { clip_ids, time } => {
+ let timeline = project.active_mut();
+ let mut created = None;
+ for clip_id in clip_ids {
+ let Some(index) = timeline.clips.iter().position(|clip| clip.id == clip_id) else {
+ continue;
+ };
+ {
+ // 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 = timeline.clip_at_mut(index);
+ let offset = time - clip.start;
+ if offset > MIN_CLIP_DURATION
+ && offset < clip.duration - MIN_CLIP_DURATION
+ && clip.speed_curve.is_some()
+ {
+ clip.speed_curve = None;
+ }
+ }
+ let clip: &Clip = &timeline.clips[index];
+ let offset = time - clip.start;
+ 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 = 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.clip_at_mut(index).duration = offset;
+ timeline.clip_at_mut(index).source_start = head_source;
+ timeline.clips.insert(index + 1, Arc::new(tail));
+ }
+ // A split always mints the tail, so "minted anything" and
+ // "changed anything" are the same fact here.
+ let applied = created.is_some();
+ Ok(Outcome {
+ created_id: created,
+ applied,
+ })
+ }
+
+ Command::FreezeFrame {
+ clip_id,
+ time,
+ duration,
+ still,
+ } => {
+ let hold = duration
+ .filter(|value| *value > 0.0)
+ .unwrap_or(DEFAULT_FREEZE_DURATION)
+ .max(MIN_CLIP_DURATION);
+
+ let (kind, media_id, track_id, start, clip_duration, speed, source_start, picture) = {
+ let timeline = project.active();
+ let Some(clip) = timeline.clip(&clip_id) else {
+ return Ok(Outcome::default());
+ };
+ if clip.kind != ClipKind::Video && clip.kind != ClipKind::Image {
+ return Ok(Outcome::default());
+ }
+ let offset = time - clip.start;
+ if offset <= MIN_CLIP_DURATION || offset >= clip.duration - MIN_CLIP_DURATION {
+ return Ok(Outcome::default());
+ }
+ (
+ clip.kind,
+ clip.media_id.clone(),
+ clip.track_id.clone(),
+ clip.start,
+ clip.duration,
+ clip.speed,
+ clip.source_start,
+ clip.clone(),
+ )
+ };
+
+ let freeze_media_id = if kind == ClipKind::Image && still.is_none() {
+ media_id
+ } else {
+ let Some(item) = still else {
+ return Ok(Outcome::default());
+ };
+ if let Some(existing) = project.media.iter().find(|media| media.path == item.path) {
+ existing.id.clone()
+ } else {
+ let id = mint.next("m");
+ project.media.push(MediaItem {
+ id: id.clone(),
+ path: item.path,
+ name: item.name,
+ duration: item.duration,
+ kind: MediaKind::Image,
+ width: item.width,
+ height: item.height,
+ frame_rate: item.frame_rate,
+ frame_rate_fraction: item.frame_rate_fraction,
+ video_codec: item.video_codec,
+ audio_codec: None,
+ has_audio: false,
+ audio_tracks: Vec::new(),
+ placeholder: false,
+ });
+ id
+ }
+ };
+
+ let timeline = project.active_mut();
+ let Some(index) = timeline.clips.iter().position(|clip| clip.id == clip_id) else {
+ return Ok(Outcome::default());
+ };
+ // The cut is a split's, so it leaves the pieces as a split does:
+ // 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.clip_at_mut(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 = Clip::clone(&timeline.clips[index]);
+ tail.id = mint.next("c");
+ tail.start = time;
+ tail.duration = clip_duration - offset;
+ tail.source_start = tail_source;
+ tail.transition_in = None;
+ timeline.clip_at_mut(index).duration = offset;
+ timeline.clip_at_mut(index).source_start = head_source;
+ timeline.clips.insert(index + 1, Arc::new(tail));
+
+ // Ripple every later placement on this track (including the new
+ // tail) so the freeze does not sit on top of the remainder.
+ for clip in timeline.clips_mut() {
+ if clip.track_id == track_id && clip.start >= time {
+ clip.start += hold;
+ }
+ }
+
+ // The still is the source clip turned into a picture: cloning it
+ // first carries every look field - transform, effects, crop,
+ // flips, whatever the model grows - and then the hold's own
+ // facts overwrite the moving ones.
+ let freeze_id = mint.next("c");
+ let mut frozen = picture;
+ frozen.id = freeze_id.clone();
+ frozen.track_id = track_id;
+ frozen.kind = ClipKind::Image;
+ frozen.media_id = freeze_media_id;
+ frozen.start = time;
+ frozen.duration = hold;
+ frozen.source_start = 0.0;
+ frozen.speed = 1.0;
+ frozen.speed_curve = None;
+ frozen.reverse = false;
+ frozen.volume = 1.0;
+ frozen.fade_in = 0.0;
+ frozen.fade_out = 0.0;
+ frozen.filters = Vec::new();
+ frozen.muted = None;
+ frozen.detached_from = None;
+ frozen.transition_in = None;
+ frozen.text = None;
+ timeline.clips.push(Arc::new(frozen));
+
+ Ok(Outcome {
+ created_id: Some(freeze_id),
+ applied: true,
+ })
+ }
+
+ Command::MergeClips { clip_ids } => {
+ let timeline = project.active_mut();
+ if let Some(reason) = why_not_merge(timeline, &clip_ids) {
+ return Err(CommandError::CannotMerge { reason });
+ }
+ let mut ordered: Vec<Clip> = clip_ids
+ .iter()
+ .filter_map(|id| timeline.clip(id).cloned())
+ .collect();
+ ordered.sort_by(|left, right| left.start.total_cmp(&right.start));
+ let first = ordered.first().expect("validated above").clone();
+ let last = ordered.last().expect("validated above");
+ let merged_duration = last.start + last.duration - first.start;
+
+ // A set, not a Vec: the retain below tests every clip on the
+ // timeline against it.
+ let doomed: HashSet<String> =
+ ordered.iter().skip(1).map(|clip| clip.id.clone()).collect();
+ timeline.clips.retain(|clip| !doomed.contains(&clip.id));
+ let survivor = timeline
+ .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),
+ applied: true,
+ })
+ }
+
+ Command::RemoveClips { clip_ids } => {
+ let timeline = project.active_mut();
+ let doomed: HashSet<&str> = clip_ids.iter().map(String::as_str).collect();
+ let clip_count = timeline.clips.len();
+ timeline
+ .clips
+ .retain(|clip| !doomed.contains(clip.id.as_str()));
+ let applied = timeline.clips.len() != clip_count;
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ _ => unreachable!("commands::apply routes only this module's commands here"),
+ }
+}
+
+/// How far apart two clips may sit and still count as touching, in seconds.
+const JOIN_EPSILON: f64 = 1e-6;
+
+fn default_clip(id: String, track_id: String, media: &MediaItem, start: f64) -> Clip {
+ let kind = match media.kind {
+ MediaKind::Video => ClipKind::Video,
+ MediaKind::Audio => ClipKind::Audio,
+ MediaKind::Image => ClipKind::Image,
+ };
+ let duration = match media.kind {
+ MediaKind::Image => DEFAULT_IMAGE_DURATION,
+ _ => media.duration.unwrap_or(UNKNOWN_DURATION),
+ };
+ let mut clip = Clip::blank(id, track_id, kind, media.name.clone(), start, duration);
+ clip.media_id = media.id.clone();
+ clip
+}
+
+/// The lowest track with nothing occupying `[start, start + duration)`,
+/// falling back to the bottom track.
+fn first_free_track(timeline: &Timeline, start: f64, duration: f64) -> Option<String> {
+ let end = start + duration;
+ timeline
+ .tracks
+ .iter()
+ .find(|track| {
+ !timeline.clips.iter().any(|clip| {
+ clip.track_id == track.id && clip.start < end && start < clip.start + clip.duration
+ })
+ })
+ .or(timeline.tracks.first())
+ .map(|track| track.id.clone())
+}
+
+/// 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> {
+ if clip_ids.len() < 2 {
+ return Some("Select two or more clips to merge.".to_owned());
+ }
+ let clips: Vec<&Clip> = clip_ids.iter().filter_map(|id| timeline.clip(id)).collect();
+ if clips.len() < 2 {
+ return Some("Select two or more clips to merge.".to_owned());
+ }
+ if clips.iter().any(|clip| clip.track_id != clips[0].track_id) {
+ return Some("Merged clips must be on the same track.".to_owned());
+ }
+ if clips.iter().any(|clip| clip.media_id != clips[0].media_id) {
+ return Some("Merged clips must come from the same file.".to_owned());
+ }
+ 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));
+ for pair in ordered.windows(2) {
+ let (previous, current) = (pair[0], pair[1]);
+ if (current.start - (previous.start + previous.duration)).abs() > JOIN_EPSILON {
+ return Some("Merged clips must touch, with no gap or overlap.".to_owned());
+ }
+ // 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());
+ }
+ }
+ None
+}
diff --git a/src/crates/concat-project/src/commands/media.rs b/src/crates/concat-project/src/commands/media.rs
new file mode 100644
index 00000000..65cf59d0
--- /dev/null
+++ b/src/crates/concat-project/src/commands/media.rs
@@ -0,0 +1,175 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! The bin and the fonts: what a project can place, before anything is placed.
+//!
+//! One arm per command, exactly as [`super::apply`] routes them here;
+//! everything these arms share lives in the parent module.
+
+use super::*;
+
+/// Applies one of this module's commands. Any other is a routing error.
+pub(super) fn apply(
+ project: &mut Project,
+ mint: &mut IdMint,
+ command: Command,
+) -> Result<Outcome, CommandError> {
+ match command {
+ Command::AddMedia { item } => {
+ if project
+ .media
+ .iter()
+ .any(|existing| existing.path == item.path)
+ {
+ return Ok(Outcome::default());
+ }
+ let id = mint.next("m");
+ project.media.push(MediaItem {
+ id: id.clone(),
+ path: item.path,
+ name: item.name,
+ duration: item.duration,
+ kind: item.kind,
+ width: item.width,
+ height: item.height,
+ frame_rate: item.frame_rate,
+ frame_rate_fraction: item.frame_rate_fraction,
+ video_codec: item.video_codec,
+ audio_codec: item.audio_codec,
+ has_audio: item.has_audio,
+ audio_tracks: item.audio_tracks,
+ placeholder: false,
+ });
+ Ok(Outcome {
+ created_id: Some(id),
+ applied: true,
+ })
+ }
+
+ Command::SetMediaPlaceholder {
+ media_id,
+ placeholder,
+ } => {
+ let applied = project
+ .media
+ .iter_mut()
+ .find(|item| item.id == media_id)
+ .is_some_and(|item| assign(&mut item.placeholder, placeholder));
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::FillSlot { media_id, item } => {
+ let media = project
+ .media
+ .iter_mut()
+ .find(|existing| existing.id == media_id)
+ .ok_or(CommandError::SlotGone)?;
+ if !media.placeholder {
+ return Err(CommandError::NotASlot);
+ }
+
+ // The slot keeps its id, so every clip that references it keeps
+ // working; only the identity behind the id changes.
+ media.path = item.path;
+ media.name = item.name.clone();
+ media.duration = item.duration;
+ media.kind = item.kind;
+ media.width = item.width;
+ media.height = item.height;
+ media.frame_rate = item.frame_rate;
+ media.frame_rate_fraction = item.frame_rate_fraction;
+ media.video_codec = item.video_codec;
+ media.audio_codec = item.audio_codec;
+ media.has_audio = item.has_audio;
+ media.audio_tracks = item.audio_tracks;
+ media.placeholder = false;
+ let kind = match item.kind {
+ MediaKind::Video => ClipKind::Video,
+ MediaKind::Audio => ClipKind::Audio,
+ MediaKind::Image => ClipKind::Image,
+ };
+
+ // Slot timing is the template's: start, duration and speed stay
+ // put, which is what keeps cuts on the beat. The in-point resets
+ // because it referred to the old footage; a clip shorter than its
+ // slot freeze-frames on its last frame downstream, which is the
+ // renderer's existing behaviour for a trim past the media's end.
+ // All timelines, like RemoveMedia: slots are not per-timeline.
+ for timeline in project.timelines.iter_mut().map(Arc::make_mut) {
+ for clip in timeline.clips_mut() {
+ if clip.media_id == media_id {
+ clip.source_start = 0.0;
+ clip.kind = kind;
+ clip.name = item.name.clone();
+ // A stream index named against the old file means
+ // nothing against the new one.
+ clip.audio_stream = None;
+ }
+ }
+ }
+ // Filling always changes the project: the target was a
+ // placeholder and is one no longer.
+ Ok(Outcome {
+ created_id: None,
+ applied: true,
+ })
+ }
+
+ Command::RemoveMedia { media_id } => {
+ // All timelines, not just the active one: a shelved clip whose
+ // media is gone would linger as a dead reference.
+ let media_count = project.media.len();
+ project.media.retain(|item| item.id != media_id);
+ let mut applied = project.media.len() != media_count;
+ for timeline in project.timelines.iter_mut().map(Arc::make_mut) {
+ let clip_count = timeline.clips.len();
+ timeline.clips.retain(|clip| clip.media_id != media_id);
+ applied |= timeline.clips.len() != clip_count;
+ }
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::AddFont { family, path } => {
+ if project.fonts.iter().any(|font| font.path == path) {
+ return Ok(Outcome::default());
+ }
+ project.fonts.push(CustomFont { family, path });
+ Ok(Outcome {
+ created_id: None,
+ applied: true,
+ })
+ }
+
+ Command::RemoveFont { family } => {
+ // Clips keep the family name: the face may come back when the
+ // file does.
+ let font_count = project.fonts.len();
+ project.fonts.retain(|font| font.family != family);
+ let applied = project.fonts.len() != font_count;
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::UpdateMediaPath { media_id, new_path } => {
+ let applied = project
+ .media
+ .iter_mut()
+ .find(|item| item.id == media_id)
+ .is_some_and(|item| assign(&mut item.path, new_path));
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ _ => unreachable!("commands::apply routes only this module's commands here"),
+ }
+}
diff --git a/src/crates/concat-project/src/commands/mod.rs b/src/crates/concat-project/src/commands/mod.rs
new file mode 100644
index 00000000..13ccdee0
--- /dev/null
+++ b/src/crates/concat-project/src/commands/mod.rs
@@ -0,0 +1,952 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! Every edit operation, as data.
+//!
+//! A [`Command`] is what the window sends; [`apply`] is the one place its
+//! meaning lives. The clamps and tolerances documented on each variant are
+//! the contract the window's gesture echo mirrors and tests against.
+
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use serde::{Deserialize, Serialize};
+
+use crate::model::{
+ AnimationSlot, AppliedFilter, AudioTrack, Clip, ClipAnimation, ClipKind, Crop, CustomFont,
+ Cutout, CutoutMode, KeyEase, KeyProperty, MediaItem, MediaKind, Project, SpeedPoint, Stroke,
+ TextStyle, Timeline, Track, Transition, VideoSettings,
+};
+
+mod audio;
+mod clips;
+pub use clips::why_not_merge;
+mod media;
+mod properties;
+mod timelines;
+mod tracks;
+
+/// Fallback length for media whose container reports no duration.
+const UNKNOWN_DURATION: f64 = 5.0;
+/// How long a still lasts when first placed. Editorial default, not a fact.
+const DEFAULT_IMAGE_DURATION: f64 = 5.0;
+/// How long a title lasts when first placed.
+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;
+/// Default hold for a CapCut-style freeze when the caller omits duration.
+const DEFAULT_FREEZE_DURATION: f64 = 1.0;
+pub(crate) use crate::model::ranges::{
+ MAX_OFFSET, MAX_SCALE, MAX_SPEED, MAX_STRETCH, MIN_CLIP_DURATION, MIN_SCALE, MIN_SPEED,
+ MIN_STRETCH, wrap_rotation,
+};
+
+/// Which end of a clip a trim drags. The two are not symmetric: see
+/// [`Command::TrimClip`].
+#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum TrimEdge {
+ /// The head. Trimming here moves the in-point with the edge, so the
+ /// remaining frames stay where they were on the timeline.
+ Start,
+ /// The tail. Trimming here only lengthens or shortens the clip.
+ End,
+}
+
+/// Which per-track toggle a [`Command::SetTrackFlag`] flips.
+#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum TrackFlag {
+ /// [`Track::visible`]: whether the track's video reaches the composite.
+ Visible,
+ /// [`Track::muted`]: whether the track's audio is silenced.
+ Muted,
+}
+
+/// Where one clip is going, in a multi-clip move.
+#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ClipMove {
+ /// The clip to move. An unknown id is skipped, not an error - the rest
+ /// of the batch of moves still lands.
+ pub clip_id: String,
+ /// New timeline position in seconds, floored at 0.
+ pub start: f64,
+ /// Destination track. An unknown id moves the clip in time but leaves it
+ /// on its current track.
+ pub track_id: String,
+}
+
+/// A partial update to one clip. Every field optional; `transition_in` and
+/// `text` are double-optional so "clear it" and "leave it alone" stay
+/// distinct on the wire (absent = untouched, null = cleared).
+#[derive(Clone, Default, PartialEq, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ClipPatch {
+ /// New display name, taken verbatim. A later `text` patch overwrites it
+ /// with the title's first line.
+ pub name: Option<String>,
+ /// New gain; floored at 0, deliberately not capped at 1 - boosting quiet
+ /// footage is legitimate.
+ pub volume: Option<f64>,
+ /// New fade-in length in seconds, floored at 0.
+ pub fade_in: Option<f64>,
+ /// New fade-out length in seconds, floored at 0.
+ pub fade_out: Option<f64>,
+ /// New opacity, clamped into 0..=1.
+ 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>,
+ /// Mirror left to right.
+ #[serde(default)]
+ pub flip_h: Option<bool>,
+ /// Mirror top to bottom.
+ #[serde(default)]
+ pub flip_v: Option<bool>,
+ /// The blend mode's name; empty is normal.
+ #[serde(default)]
+ pub blend: Option<String>,
+ /// The crop; `Some(None)` takes it off.
+ #[serde(default)]
+ pub crop: Option<Option<Crop>>,
+ /// Wholesale replacement of the audio filter chain - the UI sends the
+ /// full list, not a diff.
+ pub filters: Option<Vec<AppliedFilter>>,
+ /// Wholesale replacement of the video effect chain, like `filters`.
+ pub video_effects: Option<Vec<AppliedFilter>>,
+ /// The transition on the cut into the clip: absent leaves it alone,
+ /// null clears it, a value replaces it.
+ #[serde(
+ default,
+ with = "double_option",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub transition_in: Option<Option<Transition>>,
+ /// The title styling, same three-way wire semantics as `transition_in`.
+ /// Setting a style also renames the clip after its first line.
+ #[serde(
+ default,
+ with = "double_option",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub text: Option<Option<TextStyle>>,
+ /// Which of the media's audio streams the clip plays, by stream index:
+ /// absent leaves it alone, null goes back to the file's first, a value
+ /// names one. See `Clip::audio_stream`.
+ #[serde(
+ default,
+ with = "double_option",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub audio_stream: Option<Option<u32>>,
+}
+
+/// `Option<Option<T>>` over JSON: absent → None, null → Some(None).
+mod double_option {
+ use serde::{Deserialize, Deserializer, Serialize, Serializer};
+
+ pub fn serialize<T: Serialize, S: Serializer>(
+ value: &Option<Option<T>>,
+ serializer: S,
+ ) -> Result<S::Ok, S::Error> {
+ match value {
+ Some(inner) => inner.serialize(serializer),
+ None => serializer.serialize_none(),
+ }
+ }
+
+ pub fn deserialize<'de, T: Deserialize<'de>, D: Deserializer<'de>>(
+ deserializer: D,
+ ) -> Result<Option<Option<T>>, D::Error> {
+ Option::<T>::deserialize(deserializer).map(Some)
+ }
+}
+
+/// A media item as probed by the host, before the model mints its id.
+#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NewMedia {
+ /// Absolute path on disk. Adding a path already in the bin is a no-op,
+ /// so re-imports cannot duplicate media.
+ pub path: String,
+ /// Display name for the bin, normally the file's basename.
+ pub name: String,
+ /// Seconds, or None when the container did not report one - clips of
+ /// such media get a five-second fallback length.
+ pub duration: Option<f64>,
+ /// What the host's probe decided the file is.
+ pub kind: MediaKind,
+ /// Pixel width, when the probe found one.
+ pub width: Option<u32>,
+ /// Pixel height, same terms as `width`.
+ pub height: Option<u32>,
+ /// Frames per second as a decimal, for display.
+ pub frame_rate: Option<f64>,
+ /// The exact rate fraction the engine works in, e.g. "30000/1001".
+ pub frame_rate_fraction: Option<String>,
+ /// Codec name as probed, e.g. "h264". Informational.
+ pub video_codec: Option<String>,
+ /// Codec of the embedded audio, when there is any.
+ pub audio_codec: Option<String>,
+ /// Whether the file carries an audio stream.
+ pub has_audio: bool,
+ /// Every audio stream, in file order; see `MediaItem::audio_tracks`.
+ /// Defaulted so a caller from before the list can still add media.
+ #[serde(default)]
+ pub audio_tracks: Vec<AudioTrack>,
+}
+
+/// Every edit, as the window sends it: a tagged `op` plus camelCase
+/// fields. [`apply`] is the single place each variant's meaning lives; the
+/// notes here state the contract - clamps, tolerances, what gets minted -
+/// so a caller need not read `apply` to know what a command will do.
+#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
+#[serde(tag = "op", rename_all = "camelCase", rename_all_fields = "camelCase")]
+// A clip patch carries a whole text style, which is the largest variant by
+// a couple of hundred bytes. Commands are made one at a time and kept only
+// in the undo history, where a few hundred bytes each is nothing; boxing
+// the patch would cost every caller for a saving nobody would measure.
+#[allow(clippy::large_enum_variant)]
+pub enum Command {
+ /// Imports a file into the bin, minting an "m" id. A path already
+ /// present is a tolerated no-op that mints nothing.
+ AddMedia {
+ /// The probed file, as described by the host.
+ item: NewMedia,
+ },
+ /// Removes a bin item and every clip referencing it, on *all* timelines
+ /// - a clip whose media is gone would linger as a dead reference.
+ RemoveMedia {
+ /// The bin item to remove. An unknown id is a no-op.
+ media_id: String,
+ },
+ /// Marks a bin item as a template slot (or back to ordinary media),
+ /// which is what [`Command::FillSlot`] requires of its target.
+ SetMediaPlaceholder {
+ /// The bin item to mark. An unknown id is a no-op.
+ media_id: String,
+ /// True to make it a slot, false to make it ordinary media again.
+ placeholder: bool,
+ },
+ /// Swaps the user's file into a template slot in place. The slot keeps
+ /// its id so clips keep working; start, duration and speed stay the
+ /// template's, while the in-point resets and each clip's kind and name
+ /// follow the new file, across all timelines. Errs if the id is unknown
+ /// or the item is not a placeholder.
+ FillSlot {
+ /// The slot being filled - must have `placeholder` set.
+ media_id: String,
+ /// The user's file that takes the slot's place.
+ item: NewMedia,
+ },
+ /// Several commands as one atomic edit: applied to a staged copy and
+ /// committed only if every one succeeds, then recorded as a single undo
+ /// step. The outcome carries the last id minted inside.
+ Batch {
+ /// The commands, applied in order. Nesting is legal.
+ commands: Vec<Command>,
+ },
+ /// Places a clip of `media_id` on a named track, minting a "c" id.
+ /// Duration comes from the media (five seconds for a still or unknown
+ /// length); errs if the media or track no longer exists.
+ AddClip {
+ /// The bin item to cut from.
+ media_id: String,
+ /// The lane to place it on.
+ track_id: String,
+ /// Timeline position in seconds, floored at 0.
+ start: f64,
+ },
+ /// [`Command::AddClip`] without naming a lane: lands on the lowest
+ /// track with nothing in the clip's span, falling back to the bottom
+ /// track (overlap and all) rather than refusing.
+ AddClipAtFirstFree {
+ /// The bin item to cut from.
+ media_id: String,
+ /// Timeline position in seconds, floored at 0.
+ start: f64,
+ },
+ /// Places a title: a clip with no media behind it, named after the
+ /// text's first line, minting a "c" id.
+ AddTextClip {
+ /// The lane to place it on. None picks the first free track like
+ /// [`Command::AddClipAtFirstFree`]; naming a vanished track errs.
+ track_id: Option<String>,
+ /// Timeline position in seconds, floored at 0.
+ start: f64,
+ /// The words and their look. None means [`TextStyle::default`].
+ style: Option<TextStyle>,
+ /// Seconds on the timeline; the editorial default when absent. Here
+ /// so a caption run can land as one batch instead of add-then-trim
+ /// per clip - a batch cannot trim a clip whose id it cannot know yet.
+ #[serde(default)]
+ duration: Option<f64>,
+ /// Vertical placement as a frame-height fraction, clamped like
+ /// SetClipTransform. Lower thirds are made of this.
+ #[serde(default)]
+ offset_y: Option<f64>,
+ },
+ /// Places a layer: a look or an effect over a span of the timeline that
+ /// treats everything beneath it. No media; the chain starts as the one
+ /// package named, at its defaults, and the clip's opacity is how hard it
+ /// is applied.
+ AddLayerClip {
+ /// The lane to place it on; None picks the first free track.
+ track_id: Option<String>,
+ /// Timeline position in seconds, floored at 0.
+ start: f64,
+ /// Seconds on the timeline; the editorial default when absent.
+ #[serde(default)]
+ duration: Option<f64>,
+ /// The package the layer applies, e.g. "concat.warm".
+ effect_id: String,
+ /// What the lane calls it.
+ name: String,
+ },
+ /// Gives a clip a speed curve, or takes it away. The source covered is
+ /// held constant, as a speed change does, so the clip's timeline length
+ /// follows the curve's mean; `speed` is kept at that mean.
+ SetClipSpeedCurve {
+ /// The clip to retime.
+ clip_id: String,
+ /// The curve, or None for a constant rate at the current mean.
+ curve: Option<Vec<SpeedPoint>>,
+ },
+ /// Sets or clears the animation on one slot of a clip.
+ SetClipAnimation {
+ /// The clip.
+ clip_id: String,
+ /// Which end, or the whole.
+ slot: AnimationSlot,
+ /// The shape and its seconds, or None to take it off.
+ animation: Option<ClipAnimation>,
+ },
+ /// Puts a key on one property at one point of a clip, replacing
+ /// whichever key on that property was already within a hair of it.
+ ///
+ /// The value is the property's own - the number the inspector shows -
+ /// not the relative factor the engine plays; see `model::ClipKey`.
+ SetClipKey {
+ /// The clip.
+ clip_id: String,
+ /// Which property is being keyed.
+ property: KeyProperty,
+ /// Where in the clip, `0..=1`.
+ at: f64,
+ /// The value there.
+ value: f64,
+ /// How the key is approached from the one before it.
+ #[serde(default)]
+ ease: KeyEase,
+ },
+ /// Takes the key at `at` off one property, if there is one there. The
+ /// other half of the diamond: a filled diamond clicked is this.
+ ClearClipKey {
+ /// The clip.
+ clip_id: String,
+ /// Which property.
+ property: KeyProperty,
+ /// Where in the clip the key to remove sits, `0..=1`.
+ at: f64,
+ },
+ /// Takes every key off one property, returning it to its constant.
+ ClearClipKeys {
+ /// The clip.
+ clip_id: String,
+ /// Which property.
+ property: KeyProperty,
+ },
+ /// Puts a key on one parameter of one link of a clip's picture chain,
+ /// replacing whichever key on it was already within a hair of `at`.
+ /// The value is the parameter's own; the package's range is the
+ /// caller's to keep, the model not knowing it.
+ SetEffectKey {
+ /// The clip.
+ clip_id: String,
+ /// Which link, as an index into `video_effects`. Out of range is a
+ /// no-op.
+ entry: usize,
+ /// The parameter's manifest key.
+ key: String,
+ /// Where in the clip, `0..=1`.
+ at: f64,
+ /// The value there.
+ value: f64,
+ /// How the key is approached from the one before it.
+ #[serde(default)]
+ ease: KeyEase,
+ },
+ /// Takes the key at `at` off one parameter of one link, if there is one.
+ ClearEffectKey {
+ /// The clip.
+ clip_id: String,
+ /// Which link, as an index into `video_effects`.
+ entry: usize,
+ /// The parameter's manifest key.
+ key: String,
+ /// Where in the clip the key to remove sits, `0..=1`.
+ at: f64,
+ },
+ /// Takes every key off one parameter of one link, returning it to the
+ /// value it holds.
+ ClearEffectKeys {
+ /// The clip.
+ clip_id: String,
+ /// Which link, as an index into `video_effects`.
+ entry: usize,
+ /// The parameter's manifest key.
+ key: String,
+ },
+ /// Sets or clears a picture's cutout: the mask that takes its
+ /// background away. Tidied on the way in; see [`Cutout::tidy`].
+ SetClipCutout {
+ /// The clip. An unknown id is a no-op.
+ clip_id: String,
+ /// The cutout, or None to take it off.
+ cutout: Option<Cutout>,
+ },
+ /// Paints one stroke onto a clip's cutout. A clip with no cutout gets a
+ /// custom one; an automatic cutout becomes custom, since a stroke is a
+ /// correction to it. A stroke with no points is a no-op.
+ AddCutoutStroke {
+ /// The clip. An unknown id is a no-op.
+ clip_id: String,
+ /// The stroke, in source fractions.
+ stroke: Stroke,
+ },
+ /// Repositions any number of clips in one edit - one undo step for a
+ /// whole multi-selection drag. Unknown clips and tracks are tolerated
+ /// per [`ClipMove`].
+ MoveClips {
+ /// Where each clip is going.
+ moves: Vec<ClipMove>,
+ },
+ /// Drags one edge of a clip. A head trim moves the in-point with the
+ /// edge (scaled by speed) so the remaining pixels do not slide; either
+ /// edge stops at the sixtieth-of-a-second minimum duration. An unknown
+ /// clip is a no-op.
+ TrimClip {
+ /// The clip to trim.
+ clip_id: String,
+ /// Which edge is being dragged.
+ edge: TrimEdge,
+ /// Signed seconds of timeline the edge moves: positive drags the
+ /// head right (shortening) or the tail right (lengthening).
+ delta: f64,
+ },
+ /// Cuts each named clip in two at one playhead time. The head keeps the
+ /// id and the transition; the tail is minted fresh and stays
+ /// source-continuous. A clip the time misses (or grazes within the
+ /// minimum duration) is skipped.
+ SplitClips {
+ /// The clips under the playhead - normally the selection.
+ clip_ids: Vec<String>,
+ /// The cut point, in timeline seconds.
+ time: f64,
+ },
+ /// CapCut-style freeze at `time`: splits `clip_id`, inserts a still of
+ /// `duration` on the same track, and ripples later clips on that track
+ /// by `duration`. Video needs a probed `still` (host-extracted jpg);
+ /// image clips may omit it and reuse their media. Audio and text are
+ /// no-ops. `created_id` is the freeze clip.
+ FreezeFrame {
+ /// The picture clip under the playhead.
+ clip_id: String,
+ /// Timeline playhead; must fall strictly inside the clip.
+ time: f64,
+ /// Editorial length of the hold. Floored at [`MIN_CLIP_DURATION`];
+ /// when absent or non-positive, uses [`DEFAULT_FREEZE_DURATION`].
+ #[serde(default)]
+ duration: Option<f64>,
+ /// Probed still file. Required for video; ignored for image when
+ /// reusing the existing media.
+ #[serde(default)]
+ still: Option<NewMedia>,
+ },
+ /// Rejoins split pieces into the earliest piece, which keeps its id.
+ /// Errs with a user-facing sentence ([`why_not_merge`]) unless the
+ /// pieces sit on one track, come from one file at one speed, touch
+ /// within a microsecond, and are still in source order.
+ MergeClips {
+ /// The pieces to rejoin, any order.
+ clip_ids: Vec<String>,
+ },
+ /// Deletes clips from the active timeline. Unknown ids are ignored.
+ RemoveClips {
+ /// The clips to delete.
+ clip_ids: Vec<String>,
+ },
+ /// Applies a [`ClipPatch`]: only the fields present change, with the
+ /// clamps documented on the patch. An unknown clip is a no-op.
+ UpdateClip {
+ /// The clip to patch.
+ clip_id: String,
+ /// Which properties change, and to what.
+ patch: ClipPatch,
+ },
+ /// Changes playback rate while holding the amount of source covered
+ /// constant - the clip's timeline duration is what stretches, which is
+ /// what makes this a speed change rather than a trim.
+ SetClipSpeed {
+ /// The clip to retime. An unknown id is a no-op.
+ clip_id: String,
+ /// The new rate, clamped into 0.0625..=16 (the engine's range).
+ speed: f64,
+ },
+ /// Adjusts the picture's placement. Each field is optional so a drag
+ /// can send just the axis it moved; absent fields stay put.
+ SetClipTransform {
+ /// The clip to place. An unknown id is a no-op.
+ clip_id: String,
+ /// New scale, clamped into 0.05..=8.
+ scale: Option<f64>,
+ /// New horizontal offset as a frame-width fraction, clamped to ±3.
+ offset_x: Option<f64>,
+ /// New vertical offset as a frame-height fraction, clamped to ±3.
+ offset_y: Option<f64>,
+ /// New rotation in degrees, wrapped into (-180, 180] so a full drag
+ /// never accumulates turns.
+ rotation: Option<f64>,
+ /// New width multiplier beyond the scale, clamped into 0.1..=10.
+ #[serde(default)]
+ stretch_x: Option<f64>,
+ /// New height multiplier, on the same terms.
+ #[serde(default)]
+ stretch_y: Option<f64>,
+ },
+ /// Pulls a video clip's sound out into its own audio clip on a free
+ /// lane (minting one if none is free), muting the video and moving its
+ /// audio filters to the sound. A no-op unless the clip is an unmuted
+ /// video whose media has audio and is not already detached.
+ DetachAudio {
+ /// The video clip to detach from.
+ clip_id: String,
+ },
+ /// Undoes a detach: deletes the detached sound clip(s), unmutes the
+ /// video and hands the sound's filters back. Accepts either the video's
+ /// id or the sound's; a no-op when either side is gone.
+ ReattachAudio {
+ /// The video clip - or its detached sound.
+ clip_id: String,
+ },
+ /// Appends a lane named after the highest "Track N" in use, minting a
+ /// "t" id.
+ AddTrack,
+ /// Deletes a lane and every clip on it. Errs at the floor of one track.
+ RemoveTrack {
+ /// The lane to delete.
+ track_id: String,
+ },
+ /// Flips one of a track's two toggles. An unknown id is a no-op.
+ SetTrackFlag {
+ /// The lane to change.
+ track_id: String,
+ /// Which toggle: visibility or mute.
+ flag: TrackFlag,
+ /// The new setting.
+ value: bool,
+ },
+ /// Adds a fresh timeline - four new lanes, "Timeline N" after the
+ /// highest in use - and makes it active. Mints a "tl" id.
+ AddTimeline,
+ /// Deletes a timeline, moving the active tab to a neighbour if it was
+ /// this one. Errs at the floor of one timeline.
+ RemoveTimeline {
+ /// The timeline to delete. An unknown id is a no-op.
+ timeline_id: String,
+ },
+ /// Sets a timeline's output frame and rate. A term no frame could have,
+ /// such as a zero dimension or a zero rate, is refused as a no-op rather
+ /// than clamped: there is no nearest real size to a zero.
+ SetTimelineVideo {
+ /// The timeline. An unknown id is a no-op.
+ timeline_id: String,
+ /// The frame and the rate, together.
+ video: VideoSettings,
+ },
+ /// Renames a timeline tab. Whitespace-only names are ignored so a tab
+ /// can never end up blank; unknown ids are tolerated.
+ RenameTimeline {
+ /// The timeline to rename.
+ timeline_id: String,
+ /// The new tab label; trimmed before it lands.
+ name: String,
+ },
+ /// Switches which timeline subsequent commands act on. An unknown id
+ /// leaves the selection where it was.
+ SelectTimeline {
+ /// The timeline to switch to.
+ timeline_id: String,
+ },
+ /// Moves a timeline tab to a new position in the strip. Which timeline
+ /// is active does not change - only the order of the tabs.
+ MoveTimeline {
+ /// The timeline to move. An unknown id is a no-op.
+ timeline_id: String,
+ /// Where it lands among its siblings, 0-based, counted with the
+ /// timeline already removed from its old slot. Clamped to the end.
+ index: usize,
+ },
+ /// Registers a font file for titles. A path already registered is a
+ /// no-op, so re-adding cannot duplicate.
+ AddFont {
+ /// The family name titles will refer to.
+ family: String,
+ /// Where the font file lives on disk.
+ path: String,
+ },
+ /// Unregisters a font family. Clips keep the family name: the face may
+ /// come back when the file does.
+ RemoveFont {
+ /// The family to unregister.
+ family: String,
+ },
+ /// Updates a media item's path on disk (relink). An unknown id is a no-op.
+ UpdateMediaPath {
+ /// The media item to update.
+ media_id: String,
+ /// The new absolute path on disk.
+ new_path: String,
+ },
+}
+
+/// What a command produced, beyond the new state: the ids it minted, so the
+/// UI can select what it just created, and whether anything changed at all.
+#[derive(Clone, Default, PartialEq, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Outcome {
+ /// The id of what the command created - a clip, track, timeline, or
+ /// media item - or, for a batch, the last id minted inside it. Absent
+ /// when nothing was created, including tolerated no-ops.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub created_id: Option<String>,
+ /// Whether the command actually changed the project. A tolerated no-op -
+ /// a missing id, a field set to the value it already had - succeeds but
+ /// reports false, which is how the editor knows not to record an undo
+ /// snapshot for it. For a batch: whether any member changed anything.
+ #[serde(default)]
+ pub applied: bool,
+}
+
+/// Why a command was refused. Every variant renders through `Display` as the
+/// exact user-facing sentence the UI shows - byte for byte the strings
+/// the window treats as the contract; the enum only gives
+/// those sentences names a host can match on.
+#[derive(Clone, PartialEq, Eq, Debug, thiserror::Error)]
+pub enum CommandError {
+ /// [`Command::FillSlot`] named a media id no longer in the bin.
+ #[error("That template slot no longer exists.")]
+ SlotGone,
+ /// [`Command::FillSlot`] targeted ordinary media rather than a slot.
+ #[error("That media is not a template slot.")]
+ NotASlot,
+ /// A clip-placing command named media no longer in the bin.
+ #[error("That media is no longer in the bin.")]
+ MediaGone,
+ /// A clip-placing command named a track no longer on the timeline.
+ #[error("That track no longer exists.")]
+ TrackGone,
+ /// A first-free-track placement found a timeline with no tracks at all.
+ #[error("There are no tracks.")]
+ NoTracks,
+ /// [`Command::MergeClips`] was refused, for whichever [`why_not_merge`]
+ /// reason applied.
+ #[error("{reason}")]
+ CannotMerge {
+ /// The [`why_not_merge`] sentence, verbatim.
+ reason: String,
+ },
+ /// [`Command::RemoveTrack`] would have deleted the last track.
+ #[error("A timeline needs at least one track.")]
+ LastTrack,
+ /// [`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
+/// id a file already uses - the collision class `adoptProject` fixed in the
+/// UI is prevented here instead.
+#[derive(Clone, Default, Debug)]
+pub struct IdMint {
+ counter: u64,
+}
+
+impl IdMint {
+ /// The next fresh id: the prefix ("c", "t", "tl", "m") plus a counter
+ /// shared across all prefixes, so no two ids ever share a number.
+ pub fn next(&mut self, prefix: &str) -> String {
+ self.counter += 1;
+ format!("{prefix}{}", self.counter)
+ }
+
+ /// Advances the counter past `id`'s numeric suffix, if it has one.
+ pub fn adopt(&mut self, id: &str) {
+ let digits: String = id
+ .chars()
+ .rev()
+ .take_while(char::is_ascii_digit)
+ .collect::<String>()
+ .chars()
+ .rev()
+ .collect();
+ if let Ok(value) = digits.parse::<u64>() {
+ self.counter = self.counter.max(value);
+ }
+ }
+
+ /// Adopts every id a restored project uses - media, timelines, tracks,
+ /// clips - so nothing minted afterwards can collide with the file.
+ pub fn adopt_project(&mut self, project: &Project) {
+ for item in &project.media {
+ self.adopt(&item.id);
+ }
+ for timeline in &project.timelines {
+ self.adopt(&timeline.id);
+ for track in &timeline.tracks {
+ self.adopt(&track.id);
+ }
+ for clip in &timeline.clips {
+ self.adopt(&clip.id);
+ }
+ }
+ }
+}
+
+/// A one-line label for a block of text.
+fn first_line(content: &str) -> String {
+ let line = content
+ .lines()
+ .find(|candidate| !candidate.trim().is_empty())
+ .unwrap_or("Text")
+ .trim();
+ let label: String = line.chars().take(40).collect();
+ if label.is_empty() {
+ "Text".to_owned()
+ } else {
+ label
+ }
+}
+
+/// "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| {
+ 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 for a command that changes what the person is looking at, not
+ /// the edit: which timeline tab is showing and the order of the tabs.
+ /// Saved with the document, never recorded in undo history.
+ pub fn is_view_state(&self) -> bool {
+ matches!(
+ self,
+ Command::SelectTimeline { .. } | Command::MoveTimeline { .. }
+ )
+ }
+
+ /// 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,
+ }
+ }
+}
+
+/// Assigns `value` into `slot`, reporting whether that changed anything.
+/// This is how command arms notice a field being set to the value it already
+/// holds - which must count as "nothing happened" ([`Outcome::applied`]
+/// false), or the undo history would record phantom edits.
+fn assign<T: PartialEq>(slot: &mut T, value: T) -> bool {
+ if *slot == value {
+ false
+ } else {
+ *slot = value;
+ true
+ }
+}
+
+/// Applies one command. Errors are [`CommandError`]s, each rendering as a
+/// user-meaningful sentence; a command that legitimately does nothing (a
+/// no-op rename, an out-of-range split) returns Ok with no created id and
+/// [`Outcome::applied`] false.
+pub fn apply(
+ project: &mut Project,
+ mint: &mut IdMint,
+ command: Command,
+) -> Result<Outcome, CommandError> {
+ if command.has_non_finite() {
+ return Err(CommandError::NotANumber);
+ }
+ match command {
+ Command::Batch { commands } => {
+ // All or nothing: apply to a staged copy and commit only a fully
+ // successful run, so one bad command cannot leave a half-applied
+ // batch behind (and the editor records it as one undo step).
+ let mut staged = project.clone();
+ let mut created = None;
+ let mut applied = false;
+ for command in commands {
+ let outcome = apply(&mut staged, mint, command)?;
+ if outcome.created_id.is_some() {
+ created = outcome.created_id;
+ }
+ applied |= outcome.applied;
+ }
+ *project = staged;
+ Ok(Outcome {
+ created_id: created,
+ applied,
+ })
+ }
+
+ command @ (Command::AddMedia { .. }
+ | Command::SetMediaPlaceholder { .. }
+ | Command::FillSlot { .. }
+ | Command::RemoveMedia { .. }
+ | Command::AddFont { .. }
+ | Command::RemoveFont { .. }
+ | Command::UpdateMediaPath { .. }) => media::apply(project, mint, command),
+ command @ (Command::AddClip { .. }
+ | Command::AddClipAtFirstFree { .. }
+ | Command::AddTextClip { .. }
+ | Command::AddLayerClip { .. }
+ | Command::MoveClips { .. }
+ | Command::TrimClip { .. }
+ | Command::SplitClips { .. }
+ | Command::FreezeFrame { .. }
+ | Command::MergeClips { .. }
+ | Command::RemoveClips { .. }) => clips::apply(project, mint, command),
+ command @ (Command::UpdateClip { .. }
+ | Command::SetClipSpeed { .. }
+ | Command::SetClipCutout { .. }
+ | Command::AddCutoutStroke { .. }
+ | Command::SetClipAnimation { .. }
+ | Command::SetClipKey { .. }
+ | Command::ClearClipKey { .. }
+ | Command::ClearClipKeys { .. }
+ | Command::SetEffectKey { .. }
+ | Command::ClearEffectKey { .. }
+ | Command::ClearEffectKeys { .. }
+ | Command::SetClipSpeedCurve { .. }
+ | Command::SetClipTransform { .. }) => properties::apply(project, mint, command),
+ command @ (Command::DetachAudio { .. } | Command::ReattachAudio { .. }) => {
+ audio::apply(project, mint, command)
+ }
+ command @ (Command::AddTrack
+ | Command::RemoveTrack { .. }
+ | Command::SetTrackFlag { .. }) => tracks::apply(project, mint, command),
+ command @ (Command::AddTimeline
+ | Command::SetTimelineVideo { .. }
+ | Command::RemoveTimeline { .. }
+ | Command::RenameTimeline { .. }
+ | Command::SelectTimeline { .. }
+ | Command::MoveTimeline { .. }) => timelines::apply(project, mint, command),
+ }
+}
diff --git a/src/crates/concat-project/src/commands/properties.rs b/src/crates/concat-project/src/commands/properties.rs
new file mode 100644
index 00000000..7007db46
--- /dev/null
+++ b/src/crates/concat-project/src/commands/properties.rs
@@ -0,0 +1,364 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! What a placed clip looks and sounds like: its patchable fields, speed, transform, keys, cutout and animation.
+//!
+//! One arm per command, exactly as [`super::apply`] routes them here;
+//! everything these arms share lives in the parent module.
+
+use super::*;
+
+/// Applies one of this module's commands. Any other is a routing error.
+pub(super) fn apply(
+ project: &mut Project,
+ _mint: &mut IdMint,
+ command: Command,
+) -> Result<Outcome, CommandError> {
+ match command {
+ Command::UpdateClip { clip_id, patch } => {
+ let timeline = project.active_mut();
+ let Some(clip) = timeline.clip_mut(&clip_id) else {
+ return Ok(Outcome::default());
+ };
+ let mut applied = false;
+ if let Some(name) = patch.name {
+ applied |= assign(&mut clip.name, name);
+ }
+ if let Some(volume) = patch.volume {
+ applied |= assign(&mut clip.volume, volume.max(0.0));
+ }
+ if let Some(fade_in) = patch.fade_in {
+ applied |= assign(&mut clip.fade_in, fade_in.max(0.0));
+ }
+ if let Some(fade_out) = patch.fade_out {
+ applied |= assign(&mut clip.fade_out, fade_out.max(0.0));
+ }
+ if let Some(opacity) = patch.opacity {
+ applied |= assign(&mut clip.opacity, opacity.clamp(0.0, 1.0));
+ }
+ 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);
+ }
+ if let Some(flip) = patch.flip_h {
+ applied |= assign(&mut clip.flip_h, flip);
+ }
+ if let Some(flip) = patch.flip_v {
+ applied |= assign(&mut clip.flip_v, flip);
+ }
+ if let Some(blend) = patch.blend {
+ let blend = if blend == "normal" {
+ String::new()
+ } else {
+ blend
+ };
+ applied |= assign(&mut clip.blend, blend);
+ }
+ if let Some(crop) = patch.crop {
+ let crop = crop.map(Crop::tidy).filter(|crop| !crop.is_none());
+ applied |= assign(&mut clip.crop, crop);
+ }
+ if let Some(filters) = patch.filters {
+ applied |= assign(&mut clip.filters, filters);
+ }
+ if let Some(effects) = patch.video_effects {
+ applied |= assign(&mut clip.video_effects, effects);
+ }
+ if let Some(transition) = patch.transition_in {
+ applied |= assign(&mut clip.transition_in, transition);
+ }
+ if let Some(text) = patch.text {
+ // The name follows the words, like addTextClip snapshots it.
+ if let Some(style) = &text {
+ applied |= assign(&mut clip.name, first_line(&style.content));
+ }
+ applied |= assign(&mut clip.text, text);
+ }
+ if let Some(stream) = patch.audio_stream {
+ applied |= assign(&mut clip.audio_stream, stream);
+ }
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::SetClipSpeed { clip_id, speed } => {
+ let timeline = project.active_mut();
+ let Some(clip) = timeline.clip_mut(&clip_id) else {
+ return Ok(Outcome::default());
+ };
+ // The amount of source covered is held constant - that is what
+ // makes this a speed change rather than a trim.
+ let next = speed.clamp(MIN_SPEED, MAX_SPEED);
+ let source_covered = clip.duration * clip.speed;
+ // Bitwise so no assignment is short-circuited away. A rate set
+ // by hand is a constant rate: the curve goes.
+ let applied = assign(&mut clip.speed, next)
+ | assign(
+ &mut clip.duration,
+ (source_covered / next).max(MIN_CLIP_DURATION),
+ )
+ | assign(&mut clip.speed_curve, None);
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::SetClipCutout { clip_id, cutout } => {
+ let timeline = project.active_mut();
+ let Some(clip) = timeline.clip_mut(&clip_id) else {
+ return Ok(Outcome::default());
+ };
+ let applied = assign(&mut clip.cutout, cutout.map(Cutout::tidy));
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::AddCutoutStroke { clip_id, stroke } => {
+ let timeline = project.active_mut();
+ let Some(clip) = timeline.clip_mut(&clip_id) else {
+ return Ok(Outcome::default());
+ };
+ let Some(stroke) = stroke.tidy() else {
+ return Ok(Outcome::default());
+ };
+ let cutout = clip.cutout.get_or_insert_with(Cutout::auto);
+ cutout.mode = CutoutMode::Custom;
+ cutout.strokes.push(stroke);
+ Ok(Outcome {
+ created_id: None,
+ applied: true,
+ })
+ }
+
+ Command::SetClipAnimation {
+ clip_id,
+ slot,
+ animation,
+ } => {
+ let timeline = project.active_mut();
+ let Some(clip) = timeline.clip_mut(&clip_id) else {
+ return Ok(Outcome::default());
+ };
+ let animation = animation
+ .filter(|set| crate::animation::index_of(slot, &set.preset).is_some())
+ .map(|set| ClipAnimation {
+ preset: set.preset,
+ duration: set.duration.clamp(0.05, 60.0),
+ });
+ let field = match slot {
+ AnimationSlot::In => &mut clip.animation_in,
+ AnimationSlot::Out => &mut clip.animation_out,
+ AnimationSlot::Combo => &mut clip.animation_combo,
+ };
+ let applied = assign(field, animation);
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::SetClipKey {
+ clip_id,
+ property,
+ at,
+ value,
+ ease,
+ } => {
+ let timeline = project.active_mut();
+ let Some(clip) = timeline.clip_mut(&clip_id) else {
+ return Ok(Outcome::default());
+ };
+ if !at.is_finite() || !value.is_finite() {
+ return Ok(Outcome::default());
+ }
+ // Clamped the way the field itself is, so a key can never hold a
+ // value the constant would have been refused. The clamps are the
+ // ones ClipPatch applies; keeping them here as well is what stops
+ // a key being the back door round them.
+ let value = match property {
+ KeyProperty::Scale => value.clamp(MIN_SCALE, MAX_SCALE),
+ KeyProperty::Opacity => value.clamp(0.0, 1.0),
+ // No ceiling, matching ClipPatch: the level fader goes to
+ // +24 dB because quiet material needs it, and a key is the
+ // same value at a different instant.
+ KeyProperty::Volume => value.max(0.0),
+ KeyProperty::OffsetX | KeyProperty::OffsetY | KeyProperty::Rotation => value,
+ };
+ let before = clip.keys.clone();
+ clip.set_key(property, at, value, ease);
+ Ok(Outcome {
+ created_id: None,
+ applied: clip.keys != before,
+ })
+ }
+
+ Command::ClearClipKey {
+ clip_id,
+ property,
+ at,
+ } => {
+ let timeline = project.active_mut();
+ let Some(clip) = timeline.clip_mut(&clip_id) else {
+ return Ok(Outcome::default());
+ };
+ let applied = clip.clear_key(property, at);
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::ClearClipKeys { clip_id, property } => {
+ let timeline = project.active_mut();
+ let Some(clip) = timeline.clip_mut(&clip_id) else {
+ return Ok(Outcome::default());
+ };
+ let applied = clip.clear_keys(property);
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::SetEffectKey {
+ clip_id,
+ entry,
+ key,
+ at,
+ value,
+ ease,
+ } => {
+ let timeline = project.active_mut();
+ let Some(link) = timeline
+ .clip_mut(&clip_id)
+ .and_then(|clip| clip.video_effects.get_mut(entry))
+ else {
+ return Ok(Outcome::default());
+ };
+ if !at.is_finite() || !value.is_finite() {
+ return Ok(Outcome::default());
+ }
+ let before = link.keys.clone();
+ link.set_key(&key, at, value, ease);
+ Ok(Outcome {
+ created_id: None,
+ applied: link.keys != before,
+ })
+ }
+
+ Command::ClearEffectKey {
+ clip_id,
+ entry,
+ key,
+ at,
+ } => {
+ let timeline = project.active_mut();
+ let Some(link) = timeline
+ .clip_mut(&clip_id)
+ .and_then(|clip| clip.video_effects.get_mut(entry))
+ else {
+ return Ok(Outcome::default());
+ };
+ let applied = link.clear_key(&key, at);
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::ClearEffectKeys {
+ clip_id,
+ entry,
+ key,
+ } => {
+ let timeline = project.active_mut();
+ let Some(link) = timeline
+ .clip_mut(&clip_id)
+ .and_then(|clip| clip.video_effects.get_mut(entry))
+ else {
+ return Ok(Outcome::default());
+ };
+ let applied = link.clear_keys(&key);
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::SetClipSpeedCurve { clip_id, curve } => {
+ let timeline = project.active_mut();
+ let Some(clip) = timeline.clip_mut(&clip_id) else {
+ return Ok(Outcome::default());
+ };
+ let curve = curve.filter(|points| crate::speed::curve_of(points).is_some());
+ let source_covered = clip.duration * clip.speed;
+ let mean = curve
+ .as_ref()
+ .map(|points| crate::speed::mean_of(points))
+ .unwrap_or(clip.speed)
+ .clamp(MIN_SPEED, MAX_SPEED);
+ let applied = assign(&mut clip.speed_curve, curve)
+ | assign(&mut clip.speed, mean)
+ | assign(
+ &mut clip.duration,
+ (source_covered / mean).max(MIN_CLIP_DURATION),
+ );
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::SetClipTransform {
+ clip_id,
+ scale,
+ offset_x,
+ offset_y,
+ rotation,
+ stretch_x,
+ stretch_y,
+ } => {
+ let timeline = project.active_mut();
+ let Some(clip) = timeline.clip_mut(&clip_id) else {
+ return Ok(Outcome::default());
+ };
+ let mut applied = false;
+ if let Some(scale) = scale {
+ applied |= assign(&mut clip.scale, scale.clamp(MIN_SCALE, MAX_SCALE));
+ }
+ if let Some(offset) = offset_x {
+ applied |= assign(&mut clip.offset_x, offset.clamp(-MAX_OFFSET, MAX_OFFSET));
+ }
+ if let Some(offset) = offset_y {
+ applied |= assign(&mut clip.offset_y, offset.clamp(-MAX_OFFSET, MAX_OFFSET));
+ }
+ if let Some(rotation) = rotation {
+ 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));
+ }
+ if let Some(stretch) = stretch_y {
+ applied |= assign(&mut clip.stretch_y, stretch.clamp(MIN_STRETCH, MAX_STRETCH));
+ }
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ _ => unreachable!("commands::apply routes only this module's commands here"),
+ }
+}
diff --git a/src/crates/concat-project/src/commands/timelines.rs b/src/crates/concat-project/src/commands/timelines.rs
new file mode 100644
index 00000000..1458a6f2
--- /dev/null
+++ b/src/crates/concat-project/src/commands/timelines.rs
@@ -0,0 +1,147 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! Timelines: the tabs a project holds, their frames, names, order and which one is showing.
+//!
+//! One arm per command, exactly as [`super::apply`] routes them here;
+//! everything these arms share lives in the parent module.
+
+use super::*;
+
+/// Applies one of this module's commands. Any other is a routing error.
+pub(super) fn apply(
+ project: &mut Project,
+ mint: &mut IdMint,
+ command: Command,
+) -> Result<Outcome, CommandError> {
+ match command {
+ Command::AddTimeline => {
+ let id = mint.next("tl");
+ let name = next_numbered(
+ "Timeline",
+ project
+ .timelines
+ .iter()
+ .map(|timeline| timeline.name.clone()),
+ );
+ let tracks = (1..=4)
+ .map(|_| Track {
+ id: mint.next("t"),
+ visible: true,
+ muted: false,
+ })
+ .collect();
+ // Born at the frame of the timeline you were looking at: the
+ // likeliest second timeline is another cut of the same picture,
+ // and the one that is not is a sheet away from being told so.
+ let video = project.active().video;
+ project.timelines.push(Arc::new(Timeline {
+ id: id.clone(),
+ name,
+ video,
+ tracks,
+ clips: Vec::new(),
+ }));
+ project.active_timeline_id = id.clone();
+ Ok(Outcome {
+ created_id: Some(id),
+ applied: true,
+ })
+ }
+
+ Command::SetTimelineVideo { timeline_id, video } => {
+ if !video.is_sane() {
+ return Ok(Outcome::default());
+ }
+ let applied = project
+ .timelines
+ .iter_mut()
+ .find(|timeline| timeline.id == timeline_id)
+ .is_some_and(|timeline| assign(&mut Arc::make_mut(timeline).video, video));
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::RemoveTimeline { timeline_id } => {
+ if project.timelines.len() <= 1 {
+ return Err(CommandError::LastTimeline);
+ }
+ let Some(index) = project
+ .timelines
+ .iter()
+ .position(|timeline| timeline.id == timeline_id)
+ else {
+ return Ok(Outcome::default());
+ };
+ if project.active_timeline_id == timeline_id {
+ let neighbour = if index + 1 < project.timelines.len() {
+ index + 1
+ } else {
+ index - 1
+ };
+ project.active_timeline_id = project.timelines[neighbour].id.clone();
+ }
+ project.timelines.remove(index);
+ Ok(Outcome {
+ created_id: None,
+ applied: true,
+ })
+ }
+
+ Command::RenameTimeline { timeline_id, name } => {
+ let trimmed = name.trim();
+ if trimmed.is_empty() {
+ return Ok(Outcome::default());
+ }
+ let applied = project
+ .timelines
+ .iter_mut()
+ .find(|timeline| timeline.id == timeline_id)
+ .is_some_and(|timeline| {
+ assign(&mut Arc::make_mut(timeline).name, trimmed.to_owned())
+ });
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::SelectTimeline { timeline_id } => {
+ // Short-circuiting is right here: an unknown id must not touch
+ // the selection at all.
+ let applied = project
+ .timelines
+ .iter()
+ .any(|timeline| timeline.id == timeline_id)
+ && assign(&mut project.active_timeline_id, timeline_id);
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::MoveTimeline { timeline_id, index } => {
+ let Some(from) = project
+ .timelines
+ .iter()
+ .position(|timeline| timeline.id == timeline_id)
+ else {
+ return Ok(Outcome::default());
+ };
+ let to = index.min(project.timelines.len() - 1);
+ if to == from {
+ return Ok(Outcome::default());
+ }
+ let timeline = project.timelines.remove(from);
+ project.timelines.insert(to, timeline);
+ Ok(Outcome {
+ created_id: None,
+ applied: true,
+ })
+ }
+
+ _ => unreachable!("commands::apply routes only this module's commands here"),
+ }
+}
diff --git a/src/crates/concat-project/src/commands/tracks.rs b/src/crates/concat-project/src/commands/tracks.rs
new file mode 100644
index 00000000..9a4f2b11
--- /dev/null
+++ b/src/crates/concat-project/src/commands/tracks.rs
@@ -0,0 +1,71 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! Lanes: adding, removing and muting or hiding them.
+//!
+//! One arm per command, exactly as [`super::apply`] routes them here;
+//! everything these arms share lives in the parent module.
+
+use super::*;
+
+/// Applies one of this module's commands. Any other is a routing error.
+pub(super) fn apply(
+ project: &mut Project,
+ mint: &mut IdMint,
+ command: Command,
+) -> Result<Outcome, CommandError> {
+ match command {
+ Command::AddTrack => {
+ let timeline = project.active_mut();
+ let id = mint.next("t");
+ timeline.tracks.push(Track {
+ id: id.clone(),
+ visible: true,
+ muted: false,
+ });
+ Ok(Outcome {
+ created_id: Some(id),
+ applied: true,
+ })
+ }
+
+ Command::RemoveTrack { track_id } => {
+ let timeline = project.active_mut();
+ if timeline.tracks.len() <= 1 {
+ return Err(CommandError::LastTrack);
+ }
+ let track_count = timeline.tracks.len();
+ timeline.tracks.retain(|track| track.id != track_id);
+ timeline.clips.retain(|clip| clip.track_id != track_id);
+ // Clips only ever sit on existing tracks, so an unknown id - the
+ // tolerated no-op - removes neither.
+ let applied = timeline.tracks.len() != track_count;
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::SetTrackFlag {
+ track_id,
+ flag,
+ value,
+ } => {
+ let timeline = project.active_mut();
+ let applied = timeline
+ .tracks
+ .iter_mut()
+ .find(|track| track.id == track_id)
+ .is_some_and(|track| match flag {
+ TrackFlag::Visible => assign(&mut track.visible, value),
+ TrackFlag::Muted => assign(&mut track.muted, value),
+ });
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ _ => unreachable!("commands::apply routes only this module's commands here"),
+ }
+}
diff --git a/src/crates/concat-project/src/doc.rs b/src/crates/concat-project/src/doc.rs
index 30f29f85..7e32d299 100644
--- a/src/crates/concat-project/src/doc.rs
+++ b/src/crates/concat-project/src/doc.rs
@@ -24,10 +24,6 @@ use std::sync::Arc;
use serde_json::{Map, Value, json};
-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,
@@ -258,33 +254,27 @@ 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),
- // 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),
+ 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).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(MIN_SPEED, MAX_SPEED),
+ 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).clamp(MIN_SPEED, MAX_SPEED),
+ speed: number(point.get("speed"), 1.0),
})
- .filter(|point| (0.0..=1.0).contains(&point.at))
.collect();
(!points.is_empty()).then_some(points)
}),
@@ -296,21 +286,17 @@ fn read_clips(raw: Option<&Value>, tracks: &[Track], media: &[MediaItem]) -> Vec
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),
- }
- .tidy()
+ 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())
- .map(Cutout::tidy),
+ .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")),
@@ -320,7 +306,7 @@ fn read_clips(raw: Option<&Value>, tracks: &[Track], media: &[MediaItem]) -> Vec
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).max(0.1),
+ duration: number(transition.get("duration"), 1.0),
})
}),
text: is_text.then(|| read_text_style(entry.get("text"))),
@@ -329,6 +315,9 @@ fn read_clips(raw: Option<&Value>, tracks: &[Track], media: &[MediaItem]) -> Vec
media_id,
})
})
+ // 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()
}
diff --git a/src/crates/concat-project/src/model.rs b/src/crates/concat-project/src/model.rs
index 03ec6204..2f712870 100644
--- a/src/crates/concat-project/src/model.rs
+++ b/src/crates/concat-project/src/model.rs
@@ -834,6 +834,39 @@ impl Default for TextStyle {
}
}
+/// 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
+/// in range.
+pub mod ranges {
+ /// The shortest a clip can be: one frame at sixty.
+ pub const MIN_CLIP_DURATION: f64 = 1.0 / 60.0;
+ /// The engine's speed range (concat-media `SPEED_RANGE`), verbatim.
+ pub const MIN_SPEED: f64 = 0.0625;
+ /// The top of the engine's speed range.
+ pub const MAX_SPEED: f64 = 16.0;
+ /// The smallest a picture can be scaled to.
+ pub const MIN_SCALE: f64 = 0.05;
+ /// The largest a picture can be scaled to.
+ pub 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 const MIN_STRETCH: f64 = 0.1;
+ /// The most a picture may be stretched along one axis.
+ pub const MAX_STRETCH: f64 = 10.0;
+ /// How far off centre a picture may be moved, in frame widths.
+ pub const MAX_OFFSET: f64 = 3.0;
+ /// A transition can be no shorter than this, in seconds.
+ pub const MIN_TRANSITION: f64 = 0.1;
+
+ /// A rotation kept in (-180, 180] so a full drag never accumulates
+ /// turns.
+ pub 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 }
+ }
+}
+
/// One placed piece of a timeline: a stretch of media (or a title) with its
/// timing, mix, transform, and effects. Everything an edit decision touches
/// lives here, which is why most commands are clip commands.
@@ -960,6 +993,111 @@ pub struct Clip {
}
impl Clip {
+ /// A clip with nothing set but what names and places it: unity gain,
+ /// scale and speed, no fades, no effects, no keys. Every constructor
+ /// starts here and sets the few fields its kind needs, so a field added
+ /// to the model is added in one place.
+ pub fn blank(
+ id: impl Into<String>,
+ track_id: impl Into<String>,
+ kind: ClipKind,
+ name: impl Into<String>,
+ start: f64,
+ duration: f64,
+ ) -> Clip {
+ Clip {
+ id: id.into(),
+ track_id: track_id.into(),
+ media_id: String::new(),
+ name: name.into(),
+ kind,
+ start: start.max(0.0),
+ duration: duration.max(ranges::MIN_CLIP_DURATION),
+ source_start: 0.0,
+ volume: 1.0,
+ fade_in: 0.0,
+ fade_out: 0.0,
+ scale: 1.0,
+ offset_x: 0.0,
+ offset_y: 0.0,
+ rotation: 0.0,
+ stretch_x: 1.0,
+ stretch_y: 1.0,
+ opacity: 1.0,
+ speed: 1.0,
+ preserve_pitch: true,
+ speed_curve: None,
+ reverse: false,
+ animation_in: None,
+ animation_out: None,
+ animation_combo: None,
+ keys: Vec::new(),
+ flip_h: false,
+ flip_v: false,
+ blend: String::new(),
+ crop: None,
+ cutout: None,
+ filters: Vec::new(),
+ video_effects: Vec::new(),
+ audio_stream: None,
+ muted: None,
+ detached_from: None,
+ transition_in: None,
+ text: None,
+ }
+ }
+
+ /// Pulls every number back into the range a command would have held
+ /// it to: the floors and ceilings in [`ranges`], the rotation wrapped,
+ /// non-finite values replaced by their neutral, the crop and the cutout
+ /// tidied, the keys sorted. What the document reader runs over a clip
+ /// it has just read, so a hand-edited or older file holds nothing an
+ /// edit could not have produced.
+ pub fn tidy(mut self) -> Clip {
+ use ranges::*;
+ fn finite(value: f64, fallback: f64) -> f64 {
+ if value.is_finite() { value } else { fallback }
+ }
+ self.start = finite(self.start, 0.0).max(0.0);
+ self.duration = finite(self.duration, 1.0).max(MIN_CLIP_DURATION);
+ self.source_start = finite(self.source_start, 0.0).max(0.0);
+ self.volume = finite(self.volume, 1.0).max(0.0);
+ self.fade_in = finite(self.fade_in, 0.0).max(0.0);
+ self.fade_out = finite(self.fade_out, 0.0).max(0.0);
+ self.scale = finite(self.scale, 1.0).clamp(MIN_SCALE, MAX_SCALE);
+ self.offset_x = finite(self.offset_x, 0.0).clamp(-MAX_OFFSET, MAX_OFFSET);
+ self.offset_y = finite(self.offset_y, 0.0).clamp(-MAX_OFFSET, MAX_OFFSET);
+ self.rotation = wrap_rotation(finite(self.rotation, 0.0));
+ self.stretch_x = finite(self.stretch_x, 1.0).clamp(MIN_STRETCH, MAX_STRETCH);
+ self.stretch_y = finite(self.stretch_y, 1.0).clamp(MIN_STRETCH, MAX_STRETCH);
+ self.opacity = finite(self.opacity, 1.0).clamp(0.0, 1.0);
+ self.speed = finite(self.speed, 1.0).clamp(MIN_SPEED, MAX_SPEED);
+ self.speed_curve = self.speed_curve.take().and_then(|points| {
+ let points: Vec<SpeedPoint> = points
+ .into_iter()
+ .filter(|point| point.at.is_finite() && (0.0..=1.0).contains(&point.at))
+ .map(|point| SpeedPoint {
+ at: point.at,
+ speed: finite(point.speed, 1.0).clamp(MIN_SPEED, MAX_SPEED),
+ })
+ .collect();
+ (!points.is_empty()).then_some(points)
+ });
+ self.crop = self
+ .crop
+ .take()
+ .map(Crop::tidy)
+ .filter(|crop| !crop.is_none());
+ self.cutout = self.cutout.take().map(Cutout::tidy);
+ if let Some(transition) = self.transition_in.as_mut() {
+ transition.duration = finite(transition.duration, 1.0).max(MIN_TRANSITION);
+ }
+ self.keys
+ .retain(|key| key.at.is_finite() && key.value.is_finite());
+ self.sort_keys();
+ self
+ }
+
/// The clip's own constant for a keyable property - what the property is
/// worth everywhere its track is silent.
pub fn constant(&self, property: KeyProperty) -> f64 {