forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

edit.rs14267 lines, 715.2 KiBHistoryRawDownload
1//! Edit tools: the batched `edit` verb, and `undo` / `redo` over its ledger.
2//!
3//! `edit` runs its ops in order against the engine session. Each op's engine
4//! history steps are counted; an op that fails rolls the batch back by that many
5//! undos, so a refused batch changes nothing. A kept batch is one entry in
6//! `Server::ledger` (the number of engine steps it pushed), which `undo` pops
7//! whole. A batch is counted by the engine's `history_pushes`, not its undo
8//! depth: depth stops growing at the 100-step cap, so a batch there would count
9//! as zero. Ledger entries the cap has evicted are trimmed (`Server::trim_ledger`). Addresses are `LANE@START`, re-read after every op.
10
11use std::path::{Path, PathBuf};
12
13use engine::beats::{self, Found};
14use engine::project::{Edge, Lane, LaneKind, RedoCheckpoint, WallBound};
15use engine::scale::FitPolicy;
16use engine::transitions::{Dir, TransitionKind};
17use engine::{AudioSession, Clip, PlaybackSession, SourceEdit, Speed};
18use serde_json::{json, Value};
19
20use super::edit_fx::{self, Applied};
21use super::edit_subs;
22use super::generated;
23use crate::parse;
24use crate::server::{arg_str, opt_bool, opt_str, tri, Entry, Reply, Server, Tool};
25
26const NO_PROJECT: &str = "no project open — call project_open or project_new first";
27/// Undo and redo with no project open: there is no history to walk, and no checkpoint to name.
28const NO_PROJECT_UNDO: &str = "no project is open, so there is nothing to undo; call project_open or project_new first";
29const NO_PROJECT_REDO: &str = "no project is open, so there is nothing to redo; call project_open or project_new first";
30
31/// Ops this module answers. Anything else goes to `edit_fx::apply`, then `edit_subs::apply`.
32const OWN_OPS: &[&str] = &[
33 "chapter_add", "chapter_set", "chapter_remove", "marker_add", "marker_set", "marker_remove", "beats",
34 "place", "insert", "overwrite", "append", "keep", "assemble", "split", "trim", "split_edit", "roll", "slip", "slide", "move", "delete", "lift", "ripple_delete",
35 "close_gaps", "cut_regions", "insert_time", "remove_time", "freeze", "speed", "speed_ramp", "reverse", "fade", "dissolve", "transition", "crossfade", "visualizer",
36 "swap", "copy_look", "replace", "nudge", "regroup", "copy_paste", "close_gap", "solo",
37];
38
39/// Ops `edit_fx` answers.
40const FX_OPS: &[&str] = &[
41 "color", "lut", "wheels", "curves", "look", "auto_color", "transform", "transform_keys", "opacity_keys", "mask_keys", "effect_keys", "color_keys", "fit", "eq", "gain", "gain_keys", "gain_key", "gain_key_remove", "gain_ramp",
42 "gain_dip", "lane_gain", "pan", "pitch", "lane_pan", "limiter", "lane_add", "lane_remove",
43 "lane_move", "lane_flags", "lane_name", "deinterlace", "group", "ungroup", "subtitles_import", "duck", "dynamics", "stabilize", "reframe", "nest", "break_apart", "place_sequence", "angle", "title_add", "title_set", "title_remove",
44 "generator_add", "generator_set", "adjustment_add", "label", "enable",
45];
46
47/// Ops `edit_subs` answers (captions).
48const SUB_OPS: &[&str] = edit_subs::OPS;
49
50/// Most shifted clips one op's reply lists; the rest are counted.
51const SHIFT_CAP: usize = 20;
52/// The most ops whose lines a batch reply prints; the rest are counted.
53const OP_LINES_CAP: usize = 40;
54
55/// A still can be trimmed out to STILL_MAX_SECS (the engine's IMAGE_MAX_SECS). How long it is placed
56/// for when no length is given is the project's still length (`project_settings still_secs`).
57const STILL_MAX_SECS: f64 = 600.0;
58
59const EDIT_DOC: &str = r#"Batched edit: ops run in order as one undo step; if op k fails, all roll back.
60- Clip: V1@450 (lane@start) or V1#0. Lanes: V1.. A1.. S1.. (S = captions).
61- Timeline times (at, to, frames, gap): 450f, 15.0s, 15, 00:00:15:00, end.
62- Signed distances (by, in roll, slip, slide): the same forms with a sign, -15f, +0.5s, -00:00:01:00. A bare number is seconds. `end` is not a distance.
63- Source times (in/out/ranges): seconds or 450f of the FILE's own fps.
64- [group] = the whole linked take (V1+A1, or the one clip when it has no partners); [clip] = this clip alone: its partners are not moved, and it leaves the take while the partners stay linked to each other (a locked partner refuses).
65- Off-frame times round, and the line says so: (1.53s → 38f).
66- A locked lane is never changed: an op that would change it refuses and names the lane (lane_flags unlocks it). A ripple that only reaches a locked caption lane through the picture skips it with a note.
67- dry_run:true applies, reports, rolls back; undo and redo history are left as they were.
68- An op takes only the keys listed for it; any other key refuses the batch, naming the keys it takes.
69- A shifted clip is listed as old→new (shifted: V1@40→V1@20), up to 20.
70- Addresses refer to the timeline as left by the previous op: ops run in order, so after a ripple the clips after it have new addresses (use the shifted lists). Delete from the end of a lane, or re-read the addresses.
71- Every reply lists the side effects of each op: effects: (clips split, holes left, takes detached) and the shifted clips.
72- RIPPLE RULE (delete, ripple_delete, speed ripple:true, cut_regions, insert_time, remove_time): the scope is the edited lane(s), plus the lanes of clips linked or grouped to the edited clip(s) (a take moves whole), closed over what the ripple reaches. On a picture lane, captions and titles over the moved picture move too; a locked caption lane in that default is skipped with a note, never refused. Lanes outside the scope never move and are never split. `lanes:[...]` replaces the default scope and must name the edited lane (cut_regions, insert_time and remove_time default to every unlocked lane).
73PLACE
74place {source, at, lane?, in?, out?, length?, stretch?, audio?, audio_lane?, overwrite?, audio_track?} — audio_track:N picks the sound track of a multi-audio file (0-based, the numbers media_probe lists as audio track N; the reply names it); a track other than the source's own places the whole track: in/out, length and stretch apply to that track, and the file's others are not touched. length is the duration from in (instead of out; not both). stretch:true with length plays the whole source from in (to out, or its end) in that length: the speed is set to fit, and the reply says it (speed 0.25–4). No lane: linked V1+A1; a video lane takes the picture, and a source with sound also puts its sound on A1 (or audio_lane), grouped with the picture. audio:false = picture only. An occupied lane refuses the op and names the clip in the way; overwrite:true replaces what is there and the reply lists it. A still (the project's still length, 5.0 s by default, up to 600 s) takes no in/out: trim its out edge afterwards to change its length.
75append {source, in?, out?, length?, audio?, lane?, until?, audio_track?} — audio_track as place's (in/out and length apply to the track; not with until). length is one copy's duration from in (instead of out). With no at it starts at the end of V1 (0 for an empty V1), or of `lane` when given, not the timeline end; sound pairs on A1 as place pairs it, and a busy A1 there refuses (audio:false = picture only, on V1). until:"25s" LOOPS the source (its in..out range, or the whole file) back to back from the end of the lane until that time, the last copy trimmed to end there; one undo step. Music bed: append {source, lane:"A2", until:"25s"}.
76insert {source, in?, out?, at, to?, length?, lanes?} — three-point edit of a source range (in..out, the whole file when none; `src` also spells `source`) at timeline `at`; the length is the range, or `to` (a timeline out mark: duration = to − at, from `in`) or `length` (not with out). The take lands on `lanes` (at most one video and one audio lane: V gets the picture, A the sound; a lone V or A gives picture or sound alone), else on the first unlocked video and audio lanes the source has (V1+A1), linked as one take; a still takes the video lane and `length`/`to` (default 5.0 s), a song the audio lane only. insert RIPPLES: on those lanes the clip `at` falls inside is cut there and everything from `at` on moves later by the take's length; a lane not in the take never moves or splits, so an insert that would pull a linked take apart (the other half on a lane outside the take, e.g. an audio-only insert into V1+A1 material) is refused by name: add the partner lane to `lanes`, or detach. Captions and titles keep their time. A locked lane refuses; one undo step.
77overwrite {source, in?, out?, at, to?, length?, lanes?} — insert's other half: the same range, `at`, `to`/`length`, `lanes` and take (see insert), but it replaces what is there for the duration, trimming or splitting the clips it covers (the reply lists each), and nothing moves; past the end it keeps the gap. A locked lane refuses; one undo step. (place {overwrite:true} is the per-lane form with speed/stretch/audio_track.)
78keep {source, ranges:[[in,out]...], lane?, at?, audio?, audio_lane?, overwrite?} — ranges back to back (rough cut). With no at it starts at the end of V1 (or lane). A video lane pairs sound as place does.
79assemble {items:[{source,in?,out?}...], lane?, at?, gap?, audio?, audio_lane?, overwrite?} — keep, mixed sources. With no at it starts at the end of V1 (or lane). A video lane pairs sound as place does. Stills are refused here (no in/out to cut): add a still with place {source, at:"end"} or append {source}.
80CUT
81split {at, lanes?} — cut the clips at `at`. With `lanes`, only those lanes are cut; the other lanes keep their clip running across `at` unbroken. A linked partner of a clip cut is cut too, and the reply names it.
82trim {clip, edge:in|out, to, scope?} — move an edge to `to`. [group]; scope:"clip" unlinks.
83split_edit {clip, side:audio|video, edge:in|out, to} — the split edit (a J or L cut): the `edge` of the `side` half of the clip's take moves to `to`, and the other half stays where it is. The pair is unlinked first, so the halves can part; `clip` may name either half. Refused when `to` would pass the other edge of that half. One undo step.
84roll {clip, by|to, edge?=out} — move the CUT between two clips that butt: the out edge of `clip` and the in edge of the clip after it move together (edge:"in" rolls the cut before `clip` instead), so nothing else moves and the timeline's length stays. `to` is the new cut place, `by` a signed distance (-15f, +0.5s). Clamped to the source media of both clips and a frame each; the reply says so. A gap or no clip there refuses. [group] a take rolls its cuts together.
85slip {clip, by} — the clip keeps its place and length and plays footage `by` later in its source (negative: earlier); `by` is timeline frames, so at speed 2 a +10f slip moves the source 20 frames, and the reply says so. Clamped to the file's ends; a still refuses. [group]
86slide {clip, by} — move the clip along its lane by `by` (signed) between its neighbours with its content unchanged: the clip before it ends later/earlier and the clip after it starts later/earlier, so the timeline's length stays. Needs a clip on each side; clamped to what the neighbours can give. [group]
87move {clip, at, to_lane?, titles?, insert?, split_captions?} — slide to `at`, same kind (V to V); into occupied space it refuses and names the clip in the way. insert:true is a RIPPLE move: the clip (its take, with linked partners) leaves its slot, which closes on the ripple scope as ripple_delete closes one, and lands at `at` with the later clips on those lanes pushed to make room (`at` is where it starts once its old slot has closed). A caption spanning the clip's old edges is refused by name unless split_captions:true, which splits it at the edge and reports both halves. [group] A title wholly over the moved picture moves with it; titles:true also carries one it only partly covers, titles:false carries none (the reply names each that stays).
88swap {a, b, ripple?=true} — two clips on one lane trade places: b takes a's start, what lies between them ripples by the difference in their lengths, and a lands where b was; the reply lists the moves. ripple:false moves nothing else (the two trade slots). [clip] A take is refused: ungroup it first.
89delete {clip} — remove and ripple: the later clips in its ripple scope move up to close the gap (help {topic:"ripple"}). A later take moves whole on any lane, even one the delete did not name; if the ripple would cut a clip that is not in the deleted clip's take (a detached picture under a detached sound, say), delete refuses and names it: lift the clip, or lift that one too and close_gaps. [group]
90lift {clip} — remove the clip alone and leave a gap; nothing moves. [clip]
91ripple_delete {clip, lanes?} — cut its span out of the ripple scope (see help {topic:"ripple"}) · close_gaps {lane} — close its gaps. delete and ripple_delete move the titles after the cut with the picture (a title inside the cut lands at the cut point).
92cut_regions {regions:[[from,to]...], lanes?} — ripple-cut spans (silence scans); titles move with the cut too.
93copy_look {from, to:[addrs] | to_lane, what?=["color"]} — copies the look of clip `from` onto each clip in `to` (or every clip on `to_lane`), one undo step; the reply lists each target. what: "color", "transform", "fit" and "effects" come from a picture clip and land on picture clips; "eq" and "gain" (the clip's dB) come from a sound clip and land on sound clips; "speed" (speed, ramp and reverse) comes from either and lands on any media clip, refused for a clip with no room for the new length. Each target gets the source's exact setting (a source with no colour clears its targets'); a target the part does not fit is named as skipped.
94replace {clip, source, in?} — overwrite the clip (and its linked sound/picture half when it covers the same frames) with `source` from `in` (default its start), keeping the clip's place and length; nothing moves. nudge {clips:[addrs], by} — move the clips and their groups by a signed distance (-1f, +0.5s) as one move, refused when a neighbour blocks it outright, and stopped short at the room there is.
95insert_time {at, duration, lanes?} — ripple empty time in at `at`: clips, captions and titles starting at/after it move `duration` later on the unlocked lanes (or `lanes`). A clip `at` falls inside is cut there first; a take moves with its partners. Black lead-in: insert_time {at:0, duration:"3s"}, then title_add at 0.
96remove_time {at, duration, lanes?} — ripple a span out of the unlocked lanes (or `lanes`): the cut_regions cut for one span. Titles after it move back; a title wholly inside the span is removed and one straddling an edge is trimmed to the part outside (both named in the reply).
97TIME
98speed {clip, x, ripple?, lanes?} — rate 0.25..4. [group] Its length changes, so a neighbour in its way refuses; ripple:true moves the later items in the RIPPLE RULE scope (titles too) by the length change: slower pushes them later, faster closes the gap. A clip on another lane that spans the change is never cut: outside the scope it is left in place and the reply names it; a scope lane (named in lanes) that holds one refuses, naming it. One undo step.
99speed_ramp {clip, keys:[{at, speed}...], ripple?, lanes?} [group] — a speed that changes over the clip: each key sets a speed 0.25–4 at a clip-relative time `at` ("0s", "2s", "end" or frames), linear between keys and held before the first and after the last. Keys must be in increasing `at`, at most 64, and keys:[] clears the ramp back to the clip's constant speed. The clip's length follows the ramp, and ripple:true moves the later items as speed does. preset:"speed_up"|"slow_down"|"fast_middle"|"slow_middle" lays one of the speed card's shapes across the clip's length instead of keys (speed_up: 1x to 2x; slow_down: 2x to 1x; fast_middle: slow–fast–slow; slow_middle: fast–slow–fast); not with keys.
100regroup {at} — rejoins the clips that meet at `at` in every lane and puts them back in one group: the inverse of split (metadata only, one undo step; refused when no cut sits there).
101copy_paste {clips:[addr,...], at, lane?} — pastes copies of the named clips at `at`, with their effects, keys and volume, keeping their spacing. A paste past the end appends at the end, and the reply says where the copies landed. One clip splits and ripples the room open as the GUI's paste does; several (or any with `lane`) land as one set on their own lanes, refused whole when a landing would overlap. `lane` puts every copy on that lane (the same kind, V or A, as each copy). Links come back among the copies: copied clips that were one take (a picture and its sound, say) land as one new take, while a clip whose partner was not copied comes back unlinked. A set with a `lane` override keeps a take only where its members land on different lanes.
102close_gap {lane, at} — closes the one gap on `lane` that `at` stands in (the GUI's Close gap): a gap that borders a linked take closes with the take's other lane too; nothing else moves. Refused for a clip at `at`, the time past the lane's last clip, and the empty lead-in before its first clip. Captions use close_gaps.
103solo {lane, on} — solos an audio lane for listening: while any is soloed, the other audio lanes are silent in this session's playback. It is monitoring only: not project state, not saved, never exported, and it leaves no undo step.
104reverse {clip, on?} — the clip plays backward, picture and sound: on true/false, or omit `on` to toggle. [group] Its length and place do not change, so nothing ripples, and it composes with speed and a speed ramp. Fades stay on the timeline's ends and gain and transform keys keep their time on the timeline. A trim, split or join follows the footage (a reversed clip's start edge trims its source's end). A still refuses. One undo step. clip_info and timeline say "reversed". Limits: a reversed clip decodes at 8 bits (a 10-bit source loses its low 2 bits on a 10-bit export; banding is possible on HDR), hardware decode is off for it, a dissolve's B side plays forward, and waveforms and thumbnails draw forward.
105fade {clip, in?, out?, linked?} — ramp lengths: int = frames, "0.5s" = time. A linked partner (V1+A1) gets the same ramp; linked:false = this clip only.
106dissolve {clip, frames, linked?} — VIDEO transition into the next clip. A linked sound partner crossfades into its next clip when they meet; linked:false = picture only.
107transition {clip, kind?=dissolve, length?, direction?, linked?} — dissolve with a look: kind dissolve|dip-black|dip-white|wipe|slide|push|zoom. wipe/slide/push take direction left|right|up|down (default left; the way things move: wipe-left reveals the next clip from the right edge, slide-left brings it in over the old one, push-left pushes the old one out). length (or frames) is the overlap; omitted keeps the clip's current one. The sound is the same crossfade whatever the kind. `dissolve` also takes kind/direction.
108crossfade {clip, frames} — AUDIO crossfade into the next clip. [clip]
109visualizer {clip, on?, style?, fast?} — the clip becomes a sound picture: on true/false; style fill|ribbon|ring|wave (one of them, not toggles); fast true = the quicker peak painting. style/fast need the clip on, or on:true with them. On a sound clip, on:true places a waveform picture on a video lane grouped with it (so moves, trims and deletes carry it), and style/fast set that picture's look. Omitted keys keep their setting; on:false turns it off. One undo step.
110freeze {at, duration, lane?=V1 (insert:false with no lane: a new top video lane), insert?=true} — hold the picture at `at` for `duration`. The composed frame at `at` is saved as <project>/freeze/<stem>-<frame>-<hash8>.png (needs a project path: project_new with a path, or project_save once; the hash is of the pixels, so an identical frame reuses its file and source) and placed as a still on `lane`. insert=true ripples first, as insert_time: everything after moves `duration` later, audio gets silence. insert=false overwrites `lane` for `duration`; with no `lane` the still goes on a new top video lane over the picture instead.
111LOOK
112color {clip, brightness?, contrast?, saturation?, tint?, reset?} — grade.
113look {clip, name} — the whole grade becomes a look: a built-in (Warm, Cool, Teal & orange, Bleach bypass, Black & white, Faded film, High contrast, Vintage) or a saved one; one undo step. An unknown name is refused with the list.
114auto_color {clip} — reads the clip's middle frame as shot and sets white balance and brightness/contrast so the luma percentiles land near 0.02 and 0.98; saturation, tint, curves and LUT kept; one undo step.
115wheels {clip, lift?, gamma?, gain?, reset?} — lift (blacks), gamma (mids), gain (whites): each [master, red, green, blue], -1..1, 0 neutral (or one number: master). Runs first.
116curves {clip, master?, red?, green?, blue?, reset?} — each up to 16 [input, output] points in 0..1, inputs rising, joined by a monotone spline; [] straightens one. After the wheels.
117lut {clip, path?, mix?, clear?} — a .cube file (1D or 3D, size up to 65) after the curves, mix 0..1 (default 1); a missing or broken file is refused. lut {relink, path} points every clip using LUT `relink` at `path`. The four color sliders run last.
118transform {clip, x?, y?, scale?, rotate?, crop?:[l,r,t,b], opacity?, reset?} — position, size, crop, opacity (0 clear to 1 opaque).
119transform_keys {clip, keys?:[{at, x?, y?, scale?, rotate?, opacity?, ease?}...], clear?} — animates the transform over the clip's own time (at is a clip-relative time, e.g. "0s" or "end"); clear:true takes the keys off, back to the single transform. ease (on every kind of key, the segment that leaves the key): linear (default), ease_in, ease_out, ease_in_out, hold (a step), or bezier(x1,y1,x2,y2) / [x1,y1,x2,y2] for a custom curve (each point 0 to 1).
120opacity_keys {clip, keys?:[{at, opacity, ease?}...], clear?} — opacity (0..1) over the clip's own time; the fades multiply on top.
121mask_keys {clip, effect, keys?:[{at, x?, y?, w?, h?, feather?, ease?}...], clear?} — a rect or ellipse mask's position, size and soft edge over the clip's own time; effect is its stack position.
122effect_keys {clip, effect, keys?:[{at, <parameter>?: value, ease?}...], clear?} — animates any numeric parameter of the effect at stack position effect over the clip's own time, named as the effect names it (a blur's radius, a vignette's amount and softness, a mask's x, y, width, height and feather). A switch or a choice (a blend's mode, a mask's invert) cannot be keyed. A parameter a key leaves out takes the value the effect shows at that time. ease as transform_keys.
123color_keys {clip, keys?:[{at, brightness?, contrast?, saturation?, tint?, ease?}...], clear?} — the grade over the clip's own time; fields a key leaves out keep the previous key's value.
124fit {clip, policy: fit|fill|stretch|center} — canvas fit.
125deinterlace {clip, mode: frame|field|off} — how a video clip's interlaced source is made progressive (default frame); stored on the clip, and only matters for an interlaced source (media_probe says interlaced). field (double rate) and off are stored; the render acts on frame for now.
126lane_name {lane, name} — the lane's display label (empty clears it); the address (V1, A2) is unchanged, timeline shows the name.
127stabilize {clip, on?, strength?=0.5, crop?=zoom|full, off?, cancel?} — takes the camera shake out of a video clip (a steady pan is kept); the analysis runs in the background, stabilize_status shows it.
128reframe {clip, aspect?=fit, smoothness?=0.5} — auto reframe: follows the subject of a wide clip and writes transform keys so it fills the project canvas (a 16:9 shot in a 9:16 project); replaces the clip's transform keys and sets fit to fit; adjust with transform_keys.
129SEQUENCES (several timelines in one project; the sequence tool manages them; every edit tool argument `sequence` acts on another one)
130nest {clips:[addr,...], name?} — fold the picked clips into a new sequence and leave one compound clip in their place · break_apart {clips} — put a compound clip's contents back on the timeline · place_sequence {sequence, at, lane?=V1} — play a sequence as a compound clip · angle {clip, at?, angle?, audio?} — cut a multicam clip (multicam_create) at `at` and show another camera from there on. One undo step each; help {topic:"sequences"}, help {topic:"multicam"}. A compound clip takes no speed, ramp or reverse.
131SOUND
132eq {clip, bands:[{f,db,q,kind}] (max 10), reset?} — kind: low_shelf|peak|...
133gain {clip, db (-60..24) | add_db} — the clip's own volume, on top of its lane's; audio clips only (a video clip's gain is set on its audio clip).
134gain_keys {clip, keys:[[time, db, ease?],...]} — the clip's volume envelope (audio): points at timeline times inside the clip, dB linear (or eased, see ease above) between them, held beyond the ends, added to gain and fades. Replaces all points; keys:[] clears. Max 256.
135gain_key {clip, at, db, ease?} — one point (a point at that frame is replaced) · gain_key_remove {clip, at} — takes out the point within a frame of at
136gain_ramp {clip, from, to, to_db, from_db?} — a straight dB ramp from from to to; from_db defaults to the envelope's level at from. Points inside from..to are replaced.
137gain_dip {clip, from, to, db, ramp?=0.5s} — dips to db over from..to with ramps in and out; the ramps start from the level there now and clamp to the clip. Points inside the dip are replaced. For a dip that follows speech by itself, use duck.
138pan {clip, pan (-1..1)} — the audio clip's place between the speakers, -1 left, 0 middle, 1 right (a balance: the far side is turned down) · pitch {clip, semitones (-12..12)} — the audio clip's pitch in semitones, fractions allowed (0.37), 12 an octave up, -12 down, 0 the original; its length and speed are kept · lane_pan {lane, pan (-1..1)} — the same for a whole audio lane, on top of the clips' own
139lane_gain {lane, db (-60..12)} — level · limiter {on, ceiling_db?} — the master limiter on the output: ceiling_db -24..0 dB, the highest level the output may reach (default -1 dB)
140duck {lane, under, depth_db?=-12, threshold_db?=-40, attack_ms?=80, release_ms?=400, off?} — music lane dips while the key lane speaks
141dynamics {lane, gate?, nr?, compressor?, deesser?, reset?} — an audio lane's voice processors: each of gate, nr, compressor, deesser is true, false (bypass) or an object of settings; clean_voice sets the whole chain at once
142LANES
143lane_add {kind} · lane_remove {lane} · lane_move {lane, to} (`to` is the 1-based position; lanes are named by position, so they renumber after a move) · lane_flags {lane, hidden?, muted?, locked?}
144group {clips:[addr,...]} · ungroup {clip}
145CAPTIONS
146subtitles_import {path, lang?} — adds the file's tracks; they have no lane until captions_place. lang (ISO 639-2, e.g. fra) overrides the guess from the file name (talk.fr.srt, fra.srt).
147subtitles_lang {track, lang} — sets a subtitle track's language (ISO 639-2, e.g. fra; "und" clears it). Exports write it on the mp4/MKV track. One undo step.
148captions_place {track, lane?, at?} — the whole track as one placement from its first cue: optional `lane` (default S1, made if missing) and `at` (a frame, default 0).
149sub_move {clip, at, to_lane?} [group] · sub_trim {clip, edge, to} · sub_delete {clip}
150cue_text {track, index, text} — retype a cue (\n = line break; empty text removes the cue).
151cue_add {track, at, to, text, overwrite?, track_clock?, extend?} — add a cue to a subtitle track; at and to are timeline times (seconds exact), mapped through the placement, or the track's own clock with track_clock:true. On an unplaced track the cue is kept and nothing shows until captions_place puts the track on a caption lane, and over an existing cue unless overwrite:true, which replaces the cues it overlaps. A cue past its caption's end does not show: extend:true lengthens that caption to cover it.
152captions_remove {track, force?} — remove a caption track (its name and cues) as one step. A track with placements on the timeline is refused, naming them; force:true deletes those placements with it (a grouped placement is refused: ungroup it first).
153cue_delete {track, index} or {at, lane?} — remove one caption cue (as captions lists it, or the one shown at that time); it leaves every placement of its track and nothing moves.
154cue_time {track, index, at?, to?} — trim or move one cue: its new start (at) and/or end (to) as timeline times; it stays inside its neighbours and at least 0.1 s long. One undo step.
155cue_merge {track, index} — join a cue with the next one. cue_split {track, index, at} — divide a cue in two at a timeline time.
156cue_replace {track?, find, replace, case_sensitive?} — replace a word or phrase in every cue of a track (all tracks when track is omitted); case-insensitive unless case_sensitive. Reports occurrences and cues; one undo step.
157TITLES
158title_add {at, duration, text, preset?=lower_third|centered|caption_bar, size?=80, outline?=thin|none|thick, boxed?=false, place?=centre|top|bottom, hplace?=centre|left|right, color?=#ffffff, weight?=regular|bold, align?=centre|left|right, box_color?=#000000 (or #rrggbbaa), box_opacity?=0.6 (0..1), fade_in?, fade_out?, in_anim?, out_anim?, anim_secs?, keys?=[{at, x?, y?, scale?, opacity?, ease?}]} — a card over the picture (black where no clip plays). place is the vertical position, hplace the side the block sits against (a lower third is place:bottom, hplace:left), align how its lines line up inside it. preset gives the app's one-click look (lower_third: bold, bottom left, boxed; centered: large, outlined, middle; caption_bar: boxed, bottom, no fades); the fields given with it win over its look, and title_set applies a preset to a title and keeps its words and timing. A look off the default saves as format v49. at and duration are times (a bare number is seconds). Fades: int = frames, "0.5s" = time. Past the last clip it extends the timeline. Named T1.. in start order.
159title_set {title:"T1" or "T@45", ...any of the same fields} — merged onto the title. A title is named T1.. in start order, or by its start frame as T@45 (the form a reply prints after each title op, which stays right when titles renumber). title_remove {title} — takes it off.
160Title keys animate the title over its own length: keys:[{at:"0s", opacity:0}, {at:"1s", opacity:1, x:0.1, scale:1.2, y:-0.05, ease:"ease_out"}]. at is a time from the title's first frame (a bare number is seconds, "50%" or "end" also work); a key past the title's end holds its value. x and y shift the title as a share of the picture (-1..1, y down is positive), scale multiplies its size (0.05..10), opacity multiplies its alpha (0..1). A missing field is x 0, y 0, scale 1, opacity 1, and ease is the segment's easing as for transform_keys. keys:[] takes the animation off. Titles with keys save as format v56.
161GENERATED
162generator_add {kind: solid|gradient|countdown|bars|tone|rectangle|ellipse|line|arrow, color?, color2?, angle?, from?, fill?, stroke?, width?, radius?, lane?=V1, at?, duration?=5s} — a clip made from numbers, not a file, on a video lane that exists (else lane_add first). color is hex such as ff3366 or #ff3366 (solid; gradient start), color2 the gradient end, angle 0..359 degrees (0 left to right, 90 top to bottom), from the countdown's seconds (1..3600; its duration defaults to the count). Shapes (rectangle, ellipse, line, arrow) draw on a transparent canvas and land at 40% scale over the lanes below: fill and stroke are hex or none, width the stroke in pixels (0..400), radius rounds a rectangle; size and place come from the transform op. at defaults to the end of the lane. It trims, moves, grades and takes effects like any clip; it overwrites what it lands on, as a still does.
163generator_set {clip, color?, color2?, angle?, from?, fill?, stroke?, width?, radius?} — change a generator clip's params, keeping its place and length; a clip that plays a file is refused.
164adjustment_add {lane?=V2, at?, duration?=5s} — an adjustment layer: no picture, its color grade and effects reach everything composed beneath it. With no lane it goes on V2, added when the timeline has only V1.
165label {clip | clips, value} — the clip's colour label: a name from the palette (Violet, Iris, Caribbean, …, any case), 1..8, or none. enable {clip | clips, on} — on:false switches the clip off (it stays, but picture and sound skip it), on:true brings it back. One undo step each.
166CHAPTERS
167chapter_add {at, title} — a chapter marker at `at` (a time or frame), named `title` (at most 100 characters). One per frame. Chapters are the list a video platform jumps through; `timeline` prints them as a YouTube description.
168chapter_set {chapter:"C@150" or "C#2", title?, at?} — renames the chapter and/or moves it to `at`. A chapter is named C@<frame>, the frame it starts on (bare digits are frames, as T@ is), or C#n, its place in the list (1 first). Moving onto a frame another chapter holds is refused.
169chapter_remove {chapter} — takes the chapter off. Chapters move with the picture: a cut, a ripple or an insert moves them as it moves titles, and one inside a cut lands at the cut point.
170MARKERS (comment markers, separate from chapters: a name, a note, a colour, and a length that makes a range)
171marker_add {at, name, note?, color?=blue, length?} — a marker at `at`, named `name` (at most 100 characters). color is red, orange, yellow, green, blue or purple. length (a duration) makes it a range from `at`; without it the marker is a point. Several markers may share a frame.
172marker_set {marker:"M@150" or "M#2", name?, note?, color?, at?, length?} — changes the marker. A marker is named M@<frame> (the first one on that frame) or M#n, its place in frame order (1 first). note:"" clears the note and length:0 turns a range back into a point.
173marker_remove {marker} — takes the marker off. Markers move with the picture as chapters do (a ripple, cut or insert moves them; a range grows or shrinks with it); `timeline` lists them.
174beats {clip, every?=1} — listens to a sound clip for its beat and marks every `every`th beat (1 for each beat, 2 or 4 for bars) as a yellow comment marker noted "Beat". The reply gives the tempo, the count and the M@ addresses. The clip's earlier beat markers are replaced in the same undo step. A picture-only clip, a silent one or one with no steady pulse is refused.
175"#;
176const UNDO_DOC: &str = "Take back the last `steps` edit batches (default 1), each as one undo step. Reports each batch taken back by its label (the batch `label`, else a summary of its ops), the undo and redo depth, and the next undo.";
177const CHECKPOINT_DOC: &str = "Save the whole project under a name (letters, digits, - and _), as a copy in `<project dir>/checkpoints/<project stem>/<name>.edith`; the open project file is not touched and the project stays as it is. \
178Trade-off: a checkpoint is a full copy, so it is not limited by the engine's undo history (100 steps), it survives a server restart, and each one costs a save of the whole project. Saving the same name again replaces it. With no project path yet (project_save first) the copy goes to the temp directory and is lost on reboot.";
179const RESTORE_DOC: &str = "Replace the open project with checkpoint `name` from this project's checkpoint folder (any checkpoint on disk, made by this server or an earlier one): its timeline, captions, tracks and settings come back, and the project is dirty afterwards (save it to keep the restored state). \
180Trade-off: restore reloads the checkpoint, so the undo and redo history is cleared and restore itself cannot be undone; a checkpoint taken before a later restore stays available.";
181const CHECKPOINTS_DOC: &str = "List the checkpoints on disk in this project's checkpoint folder (<project dir>/checkpoints/<project stem>/), by name, so ones made by an earlier server run show too.";
182const REDO_DOC: &str = "Redo the last `steps` batches taken back by undo (default 1). An edit clears redo history.";
183
184/// What one op did: its report text and the clips it left at new addresses.
185struct Done {
186 text: String,
187 touched: Vec<(Lane, u32)>,
188 /// Lanes to digest even when no clip is named (a lift leaves none to name).
189 lanes: Vec<Lane>,
190}
191
192impl From<Applied> for Done {
193 fn from(a: Applied) -> Self {
194 Done { text: a.text, touched: a.touched, lanes: Vec::new() }
195 }
196}
197
198fn plain(text: String, touched: Vec<(Lane, u32)>) -> Done {
199 Done { text, touched, lanes: Vec::new() }
200}
201
202// ---- schemas --------------------------------------------------------------
203
204fn edit_schema() -> Value {
205 let ops: Vec<&str> = OWN_OPS.iter().chain(FX_OPS.iter()).chain(SUB_OPS.iter()).copied().collect();
206 json!({
207 "type": "object",
208 "properties": {
209 "ops": {
210 "type": "array",
211 "minItems": 1,
212 "description": "Ops applied in order; each is {op, ...} with the arguments listed in this tool's description.",
213 "items": {
214 "type": "object",
215 "properties": { "op": { "type": "string", "enum": ops } },
216 "required": ["op"],
217 "additionalProperties": true
218 }
219 },
220 "sequence": super::sequence::prop(),
221 "dry_run": { "type": "boolean", "description": "Apply, report, then roll back. Undo and redo history are left as they were." },
222 "label": { "type": "string", "maxLength": 60, "description": "A short name for the batch, e.g. \"Draft cut\"." }
223 },
224 "required": ["ops"]
225 })
226}
227
228fn checkpoint_schema() -> Value {
229 json!({
230 "type": "object",
231 "properties": { "name": { "type": "string", "maxLength": 40, "description": "A checkpoint name: letters, digits, - and _." } },
232 "required": ["name"]
233 })
234}
235
236fn empty_schema() -> Value {
237 json!({ "type": "object", "properties": {} })
238}
239
240fn undo_schema() -> Value {
241 // The type is an array, not "integer": rpc's argument check reads a single type name and would
242 // refuse 1.5 in its own words. steps_arg refuses it instead, with the whole-number message.
243 json!({
244 "type": "object",
245 "properties": { "steps": { "type": ["integer"], "minimum": 1, "description": "Batches to take back or redo (default 1)." } }
246 })
247}
248
249/// Ops an agent tends to guess the argument name of: (op, the argument it takes, the guessed one).
250const KEY_SWAPS: &[(&str, &str, &str)] = &[("move", "at", "to"), ("trim", "to", "at"), ("speed", "x", "speed")];
251
252/// When an op is missing its argument and was given the guessed one from KEY_SWAPS, the
253/// refusal names the right one: "missing `at` (move takes `at`, not `to`): give ...".
254fn missing_key_hint(name: &str, op: &Value, err: String) -> String {
255 let Some(rest) = err.strip_prefix("missing `") else { return err };
256 let Some((key, tail)) = rest.split_once('`') else { return err };
257 let Some(&(_, _, given)) = KEY_SWAPS.iter().find(|&&(o, k, _)| o == name && k == key) else { return err };
258 if op.get(key).is_some_and(|v| !v.is_null()) || op.get(given).is_none() {
259 return err;
260 }
261 format!("missing `{key}` ({name} takes `{key}`, not `{given}`){tail}")
262}
263
264/// The keys each op reads, its own `op` name aside. An op carrying any other key is refused
265/// by name, so a misspelt one (`clipp`) cannot be silently ignored. Keep each list in step with
266/// the keys its op function reads (`op.get`, `opt_time`, `lane_arg`, and the helpers they call).
267/// None for a name no group answers.
268fn accepted_keys(name: &str) -> Option<&'static [&'static str]> {
269 Some(match name {
270 "insert" | "overwrite" => &["source", "src", "in", "out", "at", "to", "length", "lanes"],
271 "place" => &["source", "lane", "at", "in", "out", "length", "stretch", "audio", "audio_lane", "overwrite", "audio_track"],
272 "append" => &["source", "in", "out", "length", "audio", "lane", "until", "audio_track"],
273 "keep" => &["source", "ranges", "lane", "at", "audio", "audio_lane", "overwrite"],
274 "assemble" => &["items", "lane", "at", "gap", "audio", "audio_lane", "overwrite"],
275 "split" => &["at", "lanes"],
276 "regroup" => &["at"],
277 "copy_paste" => &["clips", "at", "lane"],
278 "close_gap" => &["lane", "at"],
279 "solo" => &["lane", "on"],
280 "trim" => &["clip", "edge", "to", "scope", "ripple"],
281 "roll" => &["clip", "by", "to", "edge"],
282 "split_edit" => &["clip", "side", "edge", "to"],
283 "slip" | "slide" => &["clip", "by"],
284 "move" => &["clip", "at", "to_lane", "titles", "insert", "split_captions"],
285 "copy_look" => &["from", "to", "to_lane", "what"],
286 "replace" => &["clip", "source", "src", "in"],
287 "nudge" => &["clips", "by"],
288 "delete" | "ripple_delete" => &["clip", "lanes"],
289 "lift" => &["clip"],
290 "swap" => &["a", "b", "ripple"],
291 "close_gaps" => &["lane"],
292 "cut_regions" => &["regions", "lanes"],
293 "insert_time" | "remove_time" => &["at", "duration", "lanes"],
294 "freeze" => &["at", "duration", "lane", "insert"],
295 "speed" => &["clip", "x", "ripple", "lanes"],
296 "speed_ramp" => &["clip", "keys", "preset", "ripple", "lanes"],
297 "reverse" => &["clip", "on"],
298 "fade" => &["clip", "in", "out", "linked"],
299 "dissolve" | "transition" => &["clip", "frames", "length", "kind", "direction", "linked"],
300 "crossfade" => &["clip", "frames"],
301 "visualizer" => &["clip", "on", "style", "fast"],
302 "color" => &["clip", "brightness", "contrast", "saturation", "tint", "reset"],
303 "lut" => &["clip", "path", "mix", "clear", "relink"],
304 "wheels" => &["clip", "lift", "gamma", "gain", "reset"],
305 "curves" => &["clip", "master", "red", "green", "blue", "reset"],
306 "look" => &["clip", "name", "save"],
307 "auto_color" => &["clip"],
308 "transform" => &["clip", "x", "y", "corner", "margin", "scale", "rotate", "crop", "reset", "opacity"],
309 "transform_keys" => &["clip", "keys", "clear"],
310 "opacity_keys" | "color_keys" => &["clip", "keys", "clear"],
311 "mask_keys" | "effect_keys" => &["clip", "effect", "keys", "clear"],
312 "fit" => &["clip", "policy"],
313 "eq" => &["clip", "bands", "reset"],
314 "gain" => &["clip", "db", "add_db"],
315 "gain_keys" => &["clip", "keys"],
316 "gain_key" => &["clip", "at", "db", "ease"],
317 "gain_key_remove" => &["clip", "at"],
318 "gain_ramp" => &["clip", "from", "to", "to_db", "from_db"],
319 "gain_dip" => &["clip", "from", "to", "db", "ramp"],
320 "lane_gain" => &["lane", "db"],
321 "pan" => &["clip", "pan"],
322 "pitch" => &["clip", "semitones"],
323 "lane_pan" => &["lane", "pan"],
324 "limiter" => &["on", "ceiling_db"],
325 "duck" => &["lane", "under", "depth_db", "threshold_db", "attack_ms", "release_ms", "off"],
326 "dynamics" => &["lane", "gate", "nr", "compressor", "deesser", "reset"],
327 "stabilize" => &["clip", "on", "strength", "crop", "off", "cancel"],
328 "reframe" => &["clip", "aspect", "smoothness"],
329 "nest" => &["clips", "name"],
330 "break_apart" => &["clips"],
331 "angle" => &["clip", "at", "angle", "audio"],
332 "place_sequence" => &["sequence", "at", "lane"],
333 "lane_add" => &["kind"],
334 "lane_remove" => &["lane"],
335 "lane_move" => &["lane", "to"],
336 "lane_flags" => &["lane", "hidden", "muted", "locked"],
337 "lane_name" => &["lane", "name"],
338 "deinterlace" => &["clip", "mode"],
339 "generator_add" => &["kind", "color", "color2", "angle", "from", "fill", "stroke", "width", "radius", "hz", "level", "lane", "at", "duration"],
340 "generator_set" => &["clip", "color", "color2", "angle", "from", "fill", "stroke", "width", "radius"],
341 "adjustment_add" => &["lane", "at", "duration"],
342 "label" => &["clip", "clips", "value"],
343 "enable" => &["clip", "clips", "on"],
344 "group" => &["clips"],
345 "ungroup" => &["clip"],
346 "subtitles_import" => &["path", "lang"],
347 "title_add" => &["at", "duration", "text", "preset", "size", "outline", "boxed", "place", "hplace", "color", "colour", "weight", "align", "box_color", "box_colour", "box_opacity", "fade_in", "fade_out", "in_anim", "out_anim", "anim_secs", "keys"],
348 "title_set" => &["title", "at", "duration", "text", "preset", "size", "outline", "boxed", "place", "hplace", "color", "colour", "weight", "align", "box_color", "box_colour", "box_opacity", "fade_in", "fade_out", "in_anim", "out_anim", "anim_secs", "keys"],
349 "title_remove" => &["title"],
350 "chapter_add" => &["at", "title"],
351 "chapter_set" => &["chapter", "title", "at"],
352 "chapter_remove" => &["chapter"],
353 "marker_add" => &["at", "name", "note", "color", "length"],
354 "marker_set" => &["marker", "name", "note", "color", "at", "length"],
355 "marker_remove" => &["marker"],
356 "beats" => &["clip", "every"],
357 "captions_place" => &["track", "lane", "at"],
358 "sub_move" => &["clip", "to_lane", "at"],
359 "sub_trim" => &["clip", "edge", "to"],
360 "sub_delete" => &["clip"],
361 "cue_text" => &["track", "index", "text"],
362 "cue_add" => &["track", "at", "to", "text", "overwrite", "track_clock", "extend"],
363 "cue_replace" => &["track", "find", "replace", "case_sensitive"],
364 "cue_delete" => &["track", "index", "at", "lane"],
365 "cue_time" => &["track", "index", "at", "to"],
366 "cue_merge" => &["track", "index"],
367 "cue_split" => &["track", "index", "at"],
368 "subtitles_lang" => &["track", "lang"],
369 "captions_remove" => &["track", "force"],
370 _ => return None,
371 })
372}
373
374/// Refuses an op that carries a key it does not read, naming the keys it takes and the
375/// nearest one when the key looks like a misspelling of it.
376fn check_keys(name: &str, op: &Value) -> Result<(), String> {
377 let (Some(accepted), Some(obj)) = (accepted_keys(name), op.as_object()) else {
378 return Ok(());
379 };
380 for key in obj.keys().filter(|k| k.as_str() != "op") {
381 if accepted.contains(&key.as_str()) {
382 continue;
383 }
384 // A guessed name for an argument the op is missing (`to` for move's `at`): missing_key_hint
385 // names the right one when the op fails for that argument.
386 if KEY_SWAPS.iter().any(|&(o, real, given)| o == name && given == key && !obj.contains_key(real)) {
387 continue;
388 }
389 let near = accepted
390 .iter()
391 .map(|&k| (edit_distance(key, k), k))
392 .filter(|&(d, k)| d * 3 <= key.len().max(k.len()))
393 .min();
394 let hint = near.map_or(String::new(), |(_, k)| format!(" (did you mean `{k}`?)"));
395 return Err(format!("unknown key `{key}`; {name} takes {}{hint}", accepted.join(", ")));
396 }
397 Ok(())
398}
399
400/// Levenshtein distance between two keys, for the "did you mean" hint.
401fn edit_distance(a: &str, b: &str) -> usize {
402 let b: Vec<char> = b.chars().collect();
403 let mut prev: Vec<usize> = (0..=b.len()).collect();
404 for (i, ca) in a.chars().enumerate() {
405 let mut cur = vec![i + 1; b.len() + 1];
406 for (j, &cb) in b.iter().enumerate() {
407 cur[j + 1] = (prev[j] + usize::from(ca != cb)).min(prev[j + 1] + 1).min(cur[j] + 1);
408 }
409 prev = cur;
410 }
411 prev[b.len()]
412}
413
414pub fn tools() -> Vec<Tool> {
415 vec![
416 Tool { name: "edit", description: EDIT_DOC, schema: edit_schema, run: run_edit },
417 Tool { name: "undo", description: UNDO_DOC, schema: undo_schema, run: run_undo },
418 Tool { name: "redo", description: REDO_DOC, schema: undo_schema, run: run_redo },
419 Tool { name: "checkpoint", description: CHECKPOINT_DOC, schema: checkpoint_schema, run: run_checkpoint },
420 Tool { name: "restore", description: RESTORE_DOC, schema: checkpoint_schema, run: run_restore },
421 Tool { name: "checkpoints", description: CHECKPOINTS_DOC, schema: empty_schema, run: run_checkpoints },
422 ]
423}
424
425// ---- argument helpers -----------------------------------------------------
426
427pub(super) fn need(op: &Value, key: &str, fps: f64, end: u32) -> Result<u32, String> {
428 opt_time(op, key, fps, end)?.ok_or_else(|| format!("missing `{key}`: give a time such as 450f, 15.0s or end"))
429}
430
431pub(super) fn opt_time(op: &Value, key: &str, fps: f64, end: u32) -> Result<Option<u32>, String> {
432 match op.get(key) {
433 None | Some(Value::Null) => Ok(None),
434 Some(v) => parse::frame(v, fps, end).map(Some).map_err(|e| format!("`{key}`: {e}")),
435 }
436}
437
438/// A length: an integer is frames, a string is a time (`12f`, `0.5s`).
439pub(super) fn length(op: &Value, key: &str, fps: f64) -> Result<Option<u32>, String> {
440 match op.get(key) {
441 None | Some(Value::Null) => Ok(None),
442 Some(v) if v.is_u64() => {
443 let n = v.as_u64().unwrap_or(0);
444 u32::try_from(n).map(Some).map_err(|_| format!("`{key}`: {n} frames is too many"))
445 }
446 Some(v) => parse::frame(v, fps, u32::MAX).map(Some).map_err(|e| format!("`{key}`: {e}")),
447 }
448}
449
450fn lane_arg(op: &Value, key: &str) -> Result<Option<Lane>, String> {
451 match op.get(key) {
452 None | Some(Value::Null) => Ok(None),
453 Some(Value::String(t)) => parse::lane(t).map(Some),
454 Some(v) => Err(format!("`{key}` must be a lane name such as \"V1\" or \"A1\", got {}", parse::kind_of(v))),
455 }
456}
457
458fn lane_list(op: &Value, key: &str) -> Result<Option<Vec<Lane>>, String> {
459 match op.get(key) {
460 None | Some(Value::Null) => Ok(None),
461 Some(Value::Array(a)) => a
462 .iter()
463 .map(|x| {
464 x.as_str()
465 .ok_or_else(|| format!("`{key}` lists lane names such as V1"))
466 .and_then(parse::lane)
467 })
468 .collect::<Result<Vec<_>, _>>()
469 .map(Some),
470 Some(_) => Err(format!("`{key}` must be a list of lane names such as [\"V1\", \"A1\"]")),
471 }
472}
473
474/// An address (`V1@450`, `V1#0`) resolved against the timeline's lanes. A lane the project does not
475/// have is named as such, with the lanes it has; `parse::clip` would call it an empty lane.
476pub(super) fn clip_addr(s: &PlaybackSession, raw: &str) -> Result<(Lane, usize), String> {
477 let a = raw.trim();
478 if let Some(split) = a.find(['@', '#']) {
479 let lane = parse::lane(&a[..split])?;
480 if !s.lanes().contains(&lane) {
481 let names: Vec<String> = s.lanes().into_iter().map(parse::lane_name).collect();
482 return Err(format!(
483 "{} is not a lane in this project; the lanes are {}",
484 parse::lane_name(lane),
485 names.join(", ")
486 ));
487 }
488 }
489 parse::clip(s, raw)
490}
491
492fn clip_arg(s: &PlaybackSession, op: &Value) -> Result<(Lane, usize), String> {
493 let addr = parse::addr_str(op, "clip", "\"V1@0\"")?;
494 let (lane, idx) = clip_addr(s, addr)?;
495 if lane.kind == LaneKind::Subtitle {
496 return Err(format!("{addr} is a caption lane; these ops edit media clips, not captions"));
497 }
498 Ok((lane, idx))
499}
500
501/// `V1@450` for the clip at `idx`, or `V1#idx` when there is no such clip.
502fn addr_of(s: &PlaybackSession, lane: Lane, idx: usize) -> String {
503 match s.lane_clips(lane).get(idx) {
504 Some(c) => parse::addr(lane, c.start),
505 None => format!("{}#{idx}", parse::lane_name(lane)),
506 }
507}
508
509/// A source index from `src:N`, `N`, or a number. Must be on the timeline.
510fn source_arg(s: &PlaybackSession, op: &Value) -> Result<usize, String> {
511 let n = match op.get("source") {
512 Some(Value::Number(n)) => n
513 .as_u64()
514 .map(|n| n as usize)
515 .ok_or("`source` must be a whole number or src:N")?,
516 Some(Value::String(t)) => {
517 let t = t.trim();
518 let t = t.strip_prefix("src:").unwrap_or(t).trim_start();
519 let digits: String = t.chars().take_while(char::is_ascii_digit).collect();
520 digits
521 .parse::<usize>()
522 .map_err(|_| format!("`source` `{t}` is not a source: write src:N"))?
523 }
524 _ => return Err("missing `source`: give src:N, the number the timeline lists its media by".into()),
525 };
526 let count = s.sources().len();
527 if n >= count {
528 let have = if count == 0 {
529 "no media is imported yet (media_import adds it)".to_string()
530 } else {
531 format!("media_list shows src:0–{}", count - 1)
532 };
533 return Err(format!("there is no src:{n} ({have})"));
534 }
535 Ok(n)
536}
537
538fn source_name(s: &PlaybackSession, n: usize) -> String {
539 s.sources()
540 .get(n)
541 .and_then(|src| src.path.file_name())
542 .map(|f| f.to_string_lossy().into_owned())
543 .unwrap_or_default()
544}
545
546// ---- time bases ----------------------------------------------------------
547
548/// A source's own frames against the timeline's. The engine keeps a clip's
549/// `in_frame`/`out_frame` in timeline-rate frames (a 30 fps file on a 25 fps
550/// timeline is conformed), so source positions are converted here with the
551/// pair `engine::project::Rate` uses: native frame `n` is first shown at
552/// timeline frame `ceil(n * tl / src)`, and timeline frame `c` shows native
553/// frame `floor(c * src / tl)`.
554#[derive(Clone, Copy)]
555struct Base {
556 /// Frames per second in millionths, so 23.976 stays within a micro-frame of exact.
557 src: u128,
558 tl: u128,
559 /// The file's real duration in seconds (`f64::MAX` when unknown): a frame that rounds past
560 /// the last frame is shown at the end, not after it.
561 dur: f64,
562}
563
564impl Base {
565 fn of(s: &PlaybackSession, path: &Path) -> Self {
566 let micro = |fps: f64| (fps * 1e6).round().max(1.0) as u128;
567 let dur = engine::probe_media(path).duration_secs.filter(|d| *d > 0.0).unwrap_or(f64::MAX);
568 Base { src: micro(s.file_fps(path)), tl: micro(parse::session_fps(s)), dur }
569 }
570
571 fn src_fps(self) -> f64 {
572 self.src as f64 / 1e6
573 }
574
575 /// Timeline-rate frame to the source frame it shows.
576 fn native(self, c: u32) -> u32 {
577 (u128::from(c) * self.src / self.tl) as u32
578 }
579
580 /// Source frame to the first timeline-rate frame that shows it.
581 fn conform(self, n: u32) -> u32 {
582 (u128::from(n) * self.tl).div_ceil(self.src) as u32
583 }
584
585 /// A source frame as a source time, `2.000s`, capped at the file's real duration: the reply's
586 /// source ranges are source time, so they are never printed as timeline frames.
587 fn pos(self, native: u32) -> String {
588 self.secs_text(f64::from(native) / self.src_fps())
589 }
590
591 /// A source time in seconds, `2.000s`, capped at the file's real duration.
592 fn secs_text(self, secs: f64) -> String {
593 format!("{:.3}s", secs.min(self.dur))
594 }
595
596 /// A source range `src 0.000s–2.000s`, in source time, for the timeline frames `a..z`. The same range
597 /// the timeline prints (look.rs `src_range_secs`): it starts at the source frame the in shows, and the
598 /// end is the source frame after the last one shown, over the file's own rate, so 48 frames of a
599 /// 23.976 fps file read `0.0s–2.002s`.
600 fn span(self, a: u32, z: u32) -> String {
601 let start = f64::from(self.native(a)) / self.src_fps();
602 let end = f64::from(self.native(z.saturating_sub(1)) + 1) / self.src_fps();
603 format!("src {}–{}", self.secs_text(start), self.secs_text(end))
604 }
605}
606
607/// A source-time argument (`in`, `out`, a range end, an item's bound): seconds
608/// are the file's own, `450f` is the file's own frames. Returns the
609/// timeline-rate frame the engine stores and the rounding note, if any.
610///
611/// The snap happens once. Seconds round to the nearest source frame (ties up:
612/// `0.5s` at 25 fps is 12.5, so frame 13, 0.520s) and the first timeline frame
613/// that shows that source frame is stored, so the stored frame reads back as the
614/// source time the reply prints, with no second rounding. Same-rate sources keep
615/// the frame-count rounding they always had.
616fn source_time(v: &Value, b: Base, conformed_end: u32, key: &str) -> Result<(u32, String), String> {
617 if v.as_str().is_some_and(|t| t.trim().eq_ignore_ascii_case("end")) {
618 return Ok((conformed_end, String::new()));
619 }
620 if let (Some(secs), true) = (seconds_arg(v), b.src != b.tl) {
621 // The +1e-6 keeps a tie that float arithmetic put just under .5 on the upper frame.
622 let n = (secs * b.src_fps() + 0.5 + 1e-6).floor() as u32;
623 let c = b.conform(n);
624 // A timeline frame shows one source frame; when the source is faster the source
625 // frame `n` may be skipped, and the frame that shows its neighbour is what is stored.
626 let shown = b.native(c);
627 if (f64::from(shown) / b.src_fps() - secs).abs() < 1e-6 {
628 return Ok((c, String::new()));
629 }
630 let shown_secs = format!("{}s", trim_secs(secs));
631 return Ok((c, format!(" ({shown_secs} → src {shown}f {})", b.pos(shown))));
632 }
633 let n = parse::frame(v, b.src_fps(), u32::MAX).map_err(|e| format!("`{key}`: {e}"))?;
634 Ok((b.conform(n), exact_note(v, b.src_fps(), n, " src")))
635}
636
637/// The seconds a time argument names, when it is seconds (a bare number or `1.5s`);
638/// None for frames, timecodes, `end` or anything else.
639fn seconds_arg(v: &Value) -> Option<f64> {
640 let secs = match v {
641 Value::Number(n) => n.as_f64()?,
642 Value::String(t) => {
643 let t = t.trim();
644 if t.ends_with(['f', 'F']) || t.contains(':') {
645 return None;
646 }
647 t.strip_suffix(['s', 'S']).unwrap_or(t).trim().parse::<f64>().ok()?
648 }
649 _ => return None,
650 };
651 (secs.is_finite() && secs >= 0.0).then_some(secs)
652}
653
654/// A source time as seconds of the file, from seconds, frames or a timecode (at the file's rate).
655fn source_secs(v: &Value, b: Base) -> Option<f64> {
656 seconds_arg(v).or_else(|| parse::frame(v, b.src_fps(), u32::MAX).ok().map(|n| f64::from(n) / b.src_fps()))
657}
658
659/// The timeline frame a source range `[in, out)` ends at. Each end is still snapped to a source frame
660/// on its own (`conformed` is the out's own snap, used for `end` and when a bound is not readable), but
661/// the length is the range's duration in timeline frames: `round((out - in) × timeline fps)`. So 0s to
662/// 12s is 360f at 30 fps from a 23.976 source, where the two snapped ends alone would give 361f.
663fn range_end(in_v: Option<&Value>, out_v: &Value, b: Base, fps: f64, frames: u32, in_f: u32, conformed: u32) -> u32 {
664 if out_v.as_str().is_some_and(|t| t.trim().eq_ignore_ascii_case("end")) {
665 return conformed;
666 }
667 let Some(out_s) = source_secs(out_v, b) else {
668 return conformed;
669 };
670 let in_s = match in_v {
671 None | Some(Value::Null) => 0.0,
672 Some(v) => match source_secs(v, b) {
673 Some(s) => s,
674 None => return conformed,
675 },
676 };
677 let len = ((out_s - in_s) * fps).round();
678 if !(len.is_finite() && len >= 1.0) {
679 return conformed;
680 }
681 // Past the file's end the snapped end stands, so the range is refused as it was before.
682 let end = in_f.saturating_add(len as u32);
683 if end > frames { conformed } else { end }
684}
685
686/// `0.5` as `0.5`, `2` as `2`, without trailing zeros.
687fn trim_secs(secs: f64) -> String {
688 let s = format!("{secs:.3}");
689 s.trim_end_matches('0').trim_end_matches('.').to_string()
690}
691
692fn opt_source_time(op: &Value, key: &str, b: Base, conformed_end: u32) -> Result<Option<(u32, String)>, String> {
693 match op.get(key) {
694 None | Some(Value::Null) => Ok(None),
695 Some(v) => source_time(v, b, conformed_end, key).map(Some),
696 }
697}
698
699/// `" (1.53s → 38f)"` when a seconds value does not land on a frame of `fps`,
700/// naming the frame it was rounded to. Empty for frames, timecodes and exact seconds.
701fn exact_note(v: &Value, fps: f64, frame: u32, unit: &str) -> String {
702 let (secs, shown) = match v {
703 Value::Number(n) => (n.as_f64(), format!("{n}s")),
704 Value::String(t) => {
705 let t = t.trim();
706 if t.ends_with(['f', 'F']) || t.contains(':') {
707 return String::new();
708 }
709 let bare = t.strip_suffix(['s', 'S']).unwrap_or(t).trim();
710 (bare.parse::<f64>().ok(), format!("{bare}s"))
711 }
712 _ => return String::new(),
713 };
714 let Some(secs) = secs.filter(|x| x.is_finite() && *x >= 0.0) else {
715 return String::new();
716 };
717 let exact = secs * fps;
718 if (exact - exact.round()).abs() < 1e-6 {
719 return String::new();
720 }
721 format!(" ({shown} → {frame}f{unit})")
722}
723
724/// A trim's asked time, shown once with where it landed: `asked 6.070s → 182f (6.067s)` when the asked
725/// seconds do not land on a frame, None when they do (the plain landing is then the whole reply).
726fn asked_arrow(asked: Option<&Value>, fps: f64, landed: u32) -> Option<String> {
727 let note = exact_note(asked?, fps, landed, "");
728 if note.is_empty() {
729 return None;
730 }
731 let inner = note.trim().trim_start_matches('(').trim_end_matches(')');
732 Some(format!("asked {inner} ({:.3}s)", parse::secs(landed, fps)))
733}
734
735/// Rounding notes for the timeline times an op took (its `at`, `to`, `frames`,
736/// `gap`; a fade's `in` and `out`), appended to the op's line.
737fn time_notes(name: &str, op: &Value, fps: f64) -> String {
738 // A trim words its asked time itself (`asked … → 182f (6.067s)`), so it gets no note here.
739 if name == "trim" {
740 return String::new();
741 }
742 let keys: &[&str] = if name == "fade" { &["in", "out"] } else { &["at", "to", "frames", "gap"] };
743 let mut out = String::new();
744 for key in keys {
745 let Some(v) = op.get(*key) else { continue };
746 // A whole JSON number is a frame count for the length keys, seconds for `at`/`to`.
747 if v.is_u64() && matches!(*key, "frames" | "gap" | "in" | "out") {
748 continue;
749 }
750 if let Ok(f) = parse::frame(v, fps, u32::MAX) {
751 out.push_str(&exact_note(v, fps, f, ""));
752 }
753 }
754 out
755}
756
757// ---- locks and overlaps ---------------------------------------------------
758
759fn lock_msg(l: Lane) -> String {
760 let n = parse::lane_name(l);
761 format!("lane {n} is locked: unlock it first with lane_flags {{lane:\"{n}\", locked:false}}")
762}
763
764/// Refuses an edit that would touch a locked lane. The engine does not check
765/// locks itself, so every edit that changes a lane is checked here first.
766pub(super) fn check_unlocked(s: &PlaybackSession, lanes: &[Lane]) -> Result<(), String> {
767 match lanes.iter().find(|&&l| s.lane_locked(l)) {
768 Some(&l) => Err(lock_msg(l)),
769 None => Ok(()),
770 }
771}
772
773/// Every clip on `lane` that `start..end` runs into, in the words a refusal uses:
774/// `V1@105 (3.500–4.000)`. `moving` holds the (lane, start) of clips that are travelling;
775/// they do not count against their own new spot.
776fn overlapping(s: &PlaybackSession, lane: Lane, start: u32, end: u32, moving: &[(Lane, u32)], fps: f64) -> Vec<String> {
777 s.lane_clips(lane)
778 .iter()
779 .filter(|c| !moving.contains(&(lane, c.start)) && c.start < end && start < c.end())
780 .map(|c| {
781 format!(
782 "{} ({:.3}–{:.3})",
783 parse::addr(lane, c.start),
784 parse::secs(c.start, fps),
785 parse::secs(c.end(), fps)
786 )
787 })
788 .collect()
789}
790
791/// The media clips of the take `(lane, idx)` belongs to, the clicked one first.
792/// Just the clicked clip when it is not linked.
793fn take_of(s: &PlaybackSession, lane: Lane, idx: usize) -> Vec<(Lane, usize)> {
794 let mut out = vec![(lane, idx)];
795 let Some(link) = s.lane_clips(lane).get(idx).and_then(|c| c.link) else {
796 return out;
797 };
798 for l in s.lanes() {
799 if l.kind == LaneKind::Subtitle {
800 continue;
801 }
802 for (i, c) in s.lane_clips(l).iter().enumerate() {
803 if c.link == Some(link) && (l, i) != (lane, idx) {
804 out.push((l, i));
805 }
806 }
807 }
808 out
809}
810
811fn media_lanes(s: &PlaybackSession) -> Vec<Lane> {
812 s.lanes().into_iter().filter(|l| l.kind != LaneKind::Subtitle).collect()
813}
814
815// ---- placement ------------------------------------------------------------
816
817fn clip_of(source: usize, in_frame: u32, out_frame: u32) -> Clip {
818 Clip {
819 speed_keys: Vec::new(),
820 reversed: false,
821 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
822 angle: Default::default(),
823 start: 0,
824 in_frame,
825 out_frame,
826 source,
827 link: None,
828 eq: None,
829 color: None,
830 transform: None,
831 transform_keys: Vec::new(),
832 opacity_keys: Vec::new(),
833 color_keys: Vec::new(),
834 effects: Vec::new(),
835 fit: FitPolicy::default(),
836 speed: Speed::NORMAL,
837 fade_in: 0,
838 fade_out: 0,
839 transition_out: 0,
840 transition_kind: Default::default(),
841 visualizer: 0,
842 viz_paint: 0,
843 gain_db: 0.0,
844 gain_keys: Vec::new(),
845 pan: 0,
846 pitch: 0.0,
847 }
848}
849
850/// A refusal for a lane the timeline does not have: lists the lanes it has and the
851/// `lane_add` that makes the missing one.
852fn missing_lane(s: &PlaybackSession, l: Lane) -> String {
853 let have: Vec<String> = s.lanes().into_iter().map(parse::lane_name).collect();
854 let kind = match l.kind {
855 LaneKind::Video => "video",
856 LaneKind::Audio => "audio",
857 LaneKind::Subtitle => "subtitle",
858 };
859 format!(
860 "lane {} is not on this timeline; the lanes are {}. Add it first with {{\"op\":\"lane_add\",\"kind\":\"{kind}\"}}",
861 parse::lane_name(l),
862 have.join(", ")
863 )
864}
865
866/// Where a placed range lands: the timeline frame it starts at, the lane its picture takes, the
867/// lane its sound takes, and whether it may overwrite what is there.
868#[derive(Clone, Copy)]
869struct Dest {
870 at: u32,
871 lane: Option<Lane>,
872 audio: Option<Lane>,
873 overwrite: bool,
874}
875
876/// Places source `n`'s `in_f..out_f` at timeline frame `at`. With no lane it
877/// lands as a linked V1+A1 pair (whichever halves the file has), refused on
878/// overlap. With a video lane it overwrites that lane, and when the source has
879/// sound its sound half goes on `audio` (see `audio_arg`), grouped with it and
880/// refused on overlap. With any other lane it overwrites that one lane.
881/// Returns the new addresses. An occupied lane refuses unless `overwrite`; with it the clips
882/// the placement lands on are named in `replaced`.
883/// Places a range of source `n` at `dest.at` (see [`place_range_body`]), and says what an overwrite
884/// did to what was there: each clip cut, trimmed or removed, with the ranges it is left with.
885fn place_range(
886 s: &mut PlaybackSession,
887 n: usize,
888 in_f: u32,
889 out_f: u32,
890 dest: Dest,
891 speed: Speed,
892 replaced: &mut Vec<String>,
893) -> Result<Vec<(Lane, u32)>, String> {
894 let Dest { at, .. } = dest;
895 let before: Vec<(Lane, Vec<Clip>)> = s
896 .lanes()
897 .into_iter()
898 .filter(|l| l.kind != LaneKind::Subtitle)
899 .map(|l| (l, s.lane_clips(l).to_vec()))
900 .collect();
901 let out = place_range_body(s, n, in_f, out_f, dest, speed)?;
902 let fps = parse::session_fps(s);
903 // Only the lanes the placement landed on are reported, each over the span its own clip covers:
904 // a clip on another lane that the span merely overlaps is not touched, so it is not named.
905 for &(l, _) in &out {
906 let end = s.lane_clips(l).iter().filter(|c| c.start == at && c.source == n).map(|c| c.end()).max();
907 if let Some(end) = end {
908 let landed: Vec<(Lane, Vec<Clip>)> = before.iter().filter(|(b, _)| *b == l).cloned().collect();
909 replaced.extend(overwrite_notes(&landed, at, end, fps));
910 }
911 }
912 Ok(out)
913}
914
915/// What a placed span `[at, end)` did to the clips it covered, per lane, read from the lanes
916/// before the placement: a clip cut at its head keeps its address, a tail kept past the span is
917/// named by its new address, and a clip wholly inside the span is removed.
918fn overwrite_notes(before: &[(Lane, Vec<Clip>)], at: u32, end: u32, fps: f64) -> Vec<String> {
919 let mut out = Vec::new();
920 for (lane, clips) in before {
921 for c in clips.iter().filter(|c| c.start < end && at < c.end()) {
922 let addr = parse::addr(*lane, c.start);
923 let head = c.start < at;
924 let tail = c.end() > end;
925 let span = |a: u32, b: u32| format!("{:.3}–{:.3}", parse::secs(a, fps), parse::secs(b, fps));
926 out.push(match (head, tail) {
927 (true, true) => format!(
928 "{addr} cut to {}; {} kept as {}",
929 span(c.start, at),
930 span(end, c.end()),
931 parse::addr(*lane, end)
932 ),
933 (true, false) => format!("{addr} cut to {}", span(c.start, at)),
934 (false, true) => format!("{addr} cut to {} (kept as {})", span(end, c.end()), parse::addr(*lane, end)),
935 (false, false) => format!("{addr} removed ({})", span(c.start, c.end())),
936 });
937 }
938 }
939 out
940}
941
942#[allow(clippy::too_many_arguments)]
943fn place_range_body(
944 s: &mut PlaybackSession,
945 n: usize,
946 in_f: u32,
947 out_f: u32,
948 dest: Dest,
949 speed: Speed,
950) -> Result<Vec<(Lane, u32)>, String> {
951 let Dest { at, lane, audio, overwrite } = dest;
952 let path: PathBuf = s.sources()[n].path.clone();
953 let fps = parse::session_fps(s);
954 let frames = source_frames(s, n, lane, fps);
955 let b = Base::of(s, &path);
956 if out_f <= in_f || out_f > frames {
957 return Err(format!(
958 "src:{n} {} plays {} to {}; the range {} to {} is not inside it",
959 source_name(s, n),
960 b.pos(0),
961 b.pos(b.native(frames)),
962 b.pos(b.native(in_f)),
963 b.pos(b.native(out_f)),
964 ));
965 }
966 // The picture is what the file's header says it has, not its extension: an mp4 may hold sound alone.
967 let picture = engine::probe_media(&path).video.is_some() || engine::is_image(&path);
968 let sound = !AudioSession::probe_streams(&path)
969 .map_err(|e| format!("src:{n}: cannot read its sound: {e}"))?
970 .is_empty();
971 // A picture and its sound placed as one take run the same length. The sound's length is in the
972 // same timeline frames as the picture's, and the longer half is cut to the shorter: left alone,
973 // the engine would clamp only the sound to its own wall, leaving the two a frame or more apart.
974 let take = picture
975 && sound
976 && match lane
977 {
978 None => true,
979 Some(l) => l.kind == LaneKind::Video && audio.is_some(),
980 };
981 let out_f = match sound_frames(s, n, fps) {
982 Some(wall) if take && wall < out_f => {
983 if wall <= in_f {
984 return Err(format!(
985 "src:{n} has {} of sound, so the range from {} starts past its end: give an earlier in, or place the picture alone with audio:false",
986 secs_text(wall, fps),
987 secs_text(in_f, fps)
988 ));
989 }
990 wall
991 }
992 _ => out_f,
993 };
994 // The clip as it will sit: a stretched placement is placed already at its speed, so its
995 // timeline span (what the overlap checks and the landed check measure) is the stretched one.
996 let proto = Clip { speed, ..clip_of(n, in_f, out_f) };
997
998 match lane {
999 Some(l) => {
1000 match l.kind {
1001 LaneKind::Video if !picture => {
1002 return Err(format!("src:{n} has no picture; place its sound on an audio lane (A1..)"))
1003 }
1004 LaneKind::Audio if !sound => {
1005 return Err(format!("src:{n} has no sound; place it on a video lane (V1..)"))
1006 }
1007 LaneKind::Subtitle => return Err("a source cannot go on a caption lane (S1..)".into()),
1008 _ => {}
1009 }
1010 if !s.lanes().contains(&l) {
1011 return Err(missing_lane(s, l));
1012 }
1013 // A video lane with sound also takes the sound half on `audio`, grouped with the
1014 // picture as the no-lane path does, so the clip is not silent and can be ducked.
1015 let pair = audio.filter(|_| l.kind == LaneKind::Video && sound);
1016 let mut lanes = vec![l];
1017 if let Some(a) = pair {
1018 if !s.lanes().contains(&a) {
1019 return Err(missing_lane(s, a));
1020 }
1021 lanes.push(a);
1022 }
1023 check_unlocked(s, &lanes)?;
1024 // An occupied lane refuses, naming the clip in the way, so an explicit `lane` never
1025 // silently replaces clips; overwrite:true replaces them and the reply lists them.
1026 let len = speed.frames(out_f - in_f);
1027 // Every collision is named, the picture's and the sound's, so one refusal shows them all.
1028 let pic_hit = overlapping(s, l, at, at + len, &[], fps);
1029 let snd_hit: Vec<String> = pair.map(|a| overlapping(s, a, at, at + len, &[], fps)).unwrap_or_default();
1030 if !overwrite && (!pic_hit.is_empty() || !snd_hit.is_empty()) {
1031 let fix = "give overwrite:true to replace what is there, put the picture alone with audio:false, or give another audio_lane";
1032 // The fix leads each refusal: the reader sees what to do before what is in the way.
1033 return Err(match (pic_hit.is_empty(), pair) {
1034 // Only the sound collides.
1035 (true, Some(a)) => format!(
1036 "to place src:{n} here: put the picture alone with audio:false, give another audio_lane, or lift the clip in the way. Its sound on {} at {} would overlap {}",
1037 parse::lane_name(a),
1038 parse::tc(at, fps),
1039 snd_hit.join(", ")
1040 ),
1041 // Only the picture collides.
1042 (false, _) if snd_hit.is_empty() => format!(
1043 "{} at {} is taken: src:{n} would overwrite {}. Give overwrite:true to replace what is there, or another at or lane",
1044 parse::lane_name(l),
1045 parse::tc(at, fps),
1046 pic_hit.join(", ")
1047 ),
1048 // Both collide: every collision is named.
1049 _ => {
1050 let a = pair.map(parse::lane_name).unwrap_or_default();
1051 format!(
1052 "to place src:{n} here: {fix}. {} at {} would overlap {}; {a} at {} would overlap {}",
1053 parse::lane_name(l),
1054 parse::tc(at, fps),
1055 pic_hit.join(", "),
1056 parse::tc(at, fps),
1057 snd_hit.join(", ")
1058 )
1059 }
1060 });
1061 }
1062 if !s.place_at(l, parse::secs(at, fps), proto.clone()) {
1063 return Err(format!("{} at {} refused: the engine would not place it there", parse::lane_name(l), parse::tc(at, fps)));
1064 }
1065 // The engine clamps a clip to the picture's length, so a sound longer than its picture
1066 // lands short. That is refused by name (the batch rolls back) rather than reported as placed.
1067 let landed = s.lane_clips(l).iter().find(|c| c.start == at && c.source == n).map(|c| c.frames());
1068 if landed != Some(len) {
1069 return Err(format!(
1070 "{} at {}: src:{n} lands {} long, not the {} asked for: the engine reads this source's length from its picture ({}), so its sound cannot be placed {} long on {} yet; a shorter length or a video lane for it",
1071 parse::lane_name(l),
1072 parse::tc(at, fps),
1073 secs_text(landed.unwrap_or(0), fps),
1074 secs_text(len, fps),
1075 secs_text(s.file_frames(&path), fps),
1076 secs_text(len, fps),
1077 parse::lane_name(l)
1078 ));
1079 }
1080 if let Some(a) = pair {
1081 if !s.place_at(a, parse::secs(at, fps), proto.clone()) {
1082 return Err(format!("{} at {} refused: the engine would not place the sound there", parse::lane_name(a), parse::tc(at, fps)));
1083 }
1084 let picks: Vec<(Lane, usize)> = lanes
1085 .iter()
1086 .filter_map(|&x| s.lane_clips(x).iter().position(|c| c.start == at && c.source == n).map(|i| (x, i)))
1087 .collect();
1088 if picks.len() > 1 {
1089 s.group_all(&picks).map_err(|e| e.to_string())?;
1090 }
1091 }
1092 Ok(lanes.iter().map(|&x| (x, at)).collect())
1093 }
1094 None => {
1095 let mut items: Vec<(Lane, Clip)> = Vec::new();
1096 if picture {
1097 items.push((Lane::V1, proto.clone()));
1098 }
1099 if sound {
1100 items.push((Lane::A1, proto.clone()));
1101 }
1102 if items.is_empty() {
1103 return Err(format!("src:{n} has neither picture nor sound"));
1104 }
1105 let lanes: Vec<Lane> = items.iter().map(|(l, _)| *l).collect();
1106 check_unlocked(s, &lanes)?;
1107 // Each half goes down on its own lane at `at`, which a lane places exactly, even
1108 // past the end (the gap is kept). Refused before anything is written on overlap.
1109 let len = speed.frames(out_f - in_f);
1110 for &l in &lanes {
1111 if !s.lanes().contains(&l) {
1112 return Err(missing_lane(s, l));
1113 }
1114 let hit = overlapping(s, l, at, at + len, &[], fps);
1115 if hit.is_empty() {
1116 continue;
1117 }
1118 if !overwrite {
1119 return Err(if l.kind == LaneKind::Audio && picture {
1120 format!(
1121 "src:{n}'s sound does not fit on {} at {}: it would overlap {}. Put the picture alone with audio:false, or give another at",
1122 parse::lane_name(l),
1123 parse::tc(at, fps),
1124 hit.join(", ")
1125 )
1126 } else {
1127 format!(
1128 "src:{n} does not fit at {}: it would overlap {}; split or lift there first, give `lane`, or overwrite:true",
1129 parse::tc(at, fps),
1130 hit.join(", ")
1131 )
1132 });
1133 }
1134 }
1135 for (l, clip) in items {
1136 if !s.place_at(l, parse::secs(at, fps), clip) {
1137 return Err(format!("src:{n} does not fit at {}: the engine refused the placement at that frame", parse::tc(at, fps)));
1138 }
1139 }
1140 // A pair placed without a lane is one take, as the GUI drops it: linked, so
1141 // trim, move and delete carry the picture and the sound together.
1142 let picks: Vec<(Lane, usize)> = lanes
1143 .iter()
1144 .filter_map(|&l| s.lane_clips(l).iter().position(|c| c.start == at && c.source == n).map(|i| (l, i)))
1145 .collect();
1146 if picks.len() > 1 {
1147 s.group_all(&picks).map_err(|e| e.to_string())?;
1148 }
1149 Ok(lanes.iter().map(|&l| (l, at)).collect())
1150 }
1151 }
1152}
1153
1154/// The audio lane a placement's sound half goes on: `audio_lane` (default A1) when
1155/// the placement is on a video lane and `audio` is not false; None otherwise. The
1156/// audio options only mean something with a video `lane`, so they are refused elsewhere.
1157fn audio_arg(op: &Value, lane: Option<Lane>) -> Result<Option<Lane>, String> {
1158 let audio = match op.get("audio") {
1159 None | Some(Value::Null) => None,
1160 Some(Value::Bool(b)) => Some(*b),
1161 Some(_) => return Err("`audio` must be true or false".into()),
1162 };
1163 let given = lane_arg(op, "audio_lane")?;
1164 if let Some(a) = given
1165 && a.kind != LaneKind::Audio
1166 {
1167 return Err(format!("`audio_lane` must be an audio lane such as A1, not {}", parse::lane_name(a)));
1168 }
1169 if !matches!(lane, Some(l) if l.kind == LaneKind::Video) {
1170 if audio.is_some() || given.is_some() {
1171 return Err("`audio` and `audio_lane` apply to the sound of a video lane placement: give `lane` a video lane such as V1, or drop them".into());
1172 }
1173 return Ok(None);
1174 }
1175 if audio == Some(false) {
1176 if given.is_some() {
1177 return Err("`audio_lane` and `audio:false` contradict each other: drop one".into());
1178 }
1179 return Ok(None);
1180 }
1181 Ok(Some(given.unwrap_or(Lane::A1)))
1182}
1183
1184/// The audio tracks of a file as `(track, language)`, numbered the way `audio_track` takes them:
1185/// 0-based, file order among the audio tracks (the numbers media_probe lists). `und` where the file names none.
1186pub(crate) fn audio_tracks(path: &Path) -> Vec<(usize, String)> {
1187 engine::probe_media(path)
1188 .streams
1189 .iter()
1190 .filter(|st| st.kind == engine::demux::StreamKind::Audio)
1191 .map(|st| (st.index, st.language.clone().unwrap_or_else(|| "und".to_string())))
1192 .collect()
1193}
1194
1195/// `audio_track` as the track number the op gave; `None` when it gives none.
1196fn audio_track_arg(op: &Value) -> Result<Option<usize>, String> {
1197 match op.get("audio_track") {
1198 None | Some(Value::Null) => Ok(None),
1199 Some(Value::Number(n)) => n
1200 .as_u64()
1201 .map(|t| Some(t as usize))
1202 .ok_or_else(|| "`audio_track` must be a whole number: the 0-based audio track media_probe lists".into()),
1203 Some(_) => Err("`audio_track` must be a whole number: the 0-based audio track media_probe lists, e.g. 1".into()),
1204 }
1205}
1206
1207/// Checks that `src:n`'s file has audio track `track`, returning its language. The refusal names the
1208/// tracks the file has, so the fix is to read them off it.
1209fn track_language(path: &Path, n: usize, track: usize) -> Result<String, String> {
1210 let tracks = audio_tracks(path);
1211 if let Some((_, lang)) = tracks.iter().find(|(t, _)| *t == track) {
1212 return Ok(lang.clone());
1213 }
1214 if tracks.is_empty() {
1215 return Err(format!("audio_track:{track}: src:{n} has no audio track"));
1216 }
1217 // One track is named by its parts, so its parentheses do not nest in the list form.
1218 if let [(t, l)] = tracks.as_slice() {
1219 return Err(format!("audio_track:{track}: src:{n} has one audio track ({t}, {l})"));
1220 }
1221 let list: Vec<String> = tracks.iter().map(|(t, l)| format!("{t} ({l})")).collect();
1222 Err(format!("audio_track:{track}: src:{n} has audio tracks {}", list.join(", ")))
1223}
1224
1225/// Takes `path`'s audio track `track` in as a source of its own, the way a library row is taken. The
1226/// engine can only place a track with `place_stream_at`, which pastes the picture where it lands and
1227/// ripples what follows, so the track goes down at the end of the timeline (nothing to ripple there)
1228/// and its scratch clips are deleted again, leaving the source. The placement that follows is then an
1229/// ordinary placement of that source.
1230fn register_track(s: &mut PlaybackSession, path: &Path, track: usize, fps: f64) -> Result<usize, String> {
1231 let end = parse::session_end(s);
1232 let placed = s
1233 .place_stream_at(parse::secs(end, fps), path, track, None)
1234 .map_err(|e| format!("audio_track:{track}: {e}"))?;
1235 if !placed {
1236 return Err(format!("audio_track:{track}: the track did not come in at {}", parse::tc(end, fps)));
1237 }
1238 let m = s
1239 .sources()
1240 .iter()
1241 .position(|x| x.path == path && x.audio_stream == track)
1242 .ok_or_else(|| format!("audio_track:{track}: the track did not become a source"))?;
1243 // A delete takes the clip's linked half with it, so the clips are found again after each one.
1244 loop {
1245 let mut next = None;
1246 for l in s.lanes() {
1247 if l.kind == LaneKind::Subtitle {
1248 continue;
1249 }
1250 if let Some(i) = s.lane_clips(l).iter().position(|c| c.source == m) {
1251 next = Some((l, i));
1252 break;
1253 }
1254 }
1255 let Some((l, i)) = next else { break };
1256 if !s.delete_clip(l, i) {
1257 return Err(format!("audio_track:{track}: could not clear the track's scratch clip on {}", parse::lane_name(l)));
1258 }
1259 }
1260 Ok(m)
1261}
1262
1263#[allow(clippy::too_many_arguments)]
1264/// A track other than the source's own. The track is registered as a source of its own (`register_track`)
1265/// and the placement is the ordinary one for that source, so in, out, length, stretch, lanes, overwrite,
1266/// audio and the reply all behave as they do for any source.
1267fn place_track_op(s: &mut PlaybackSession, verb: &str, n: usize, op: &Value, dest: (u32, Option<Lane>), track: usize, fps: f64) -> Result<Done, String> {
1268 let (at, lane) = dest;
1269 let path: PathBuf = s.sources()[n].path.clone();
1270 let (m, added) = match s.sources().iter().position(|x| x.path == path && x.audio_stream == track) {
1271 Some(m) => (m, false),
1272 None => (register_track(s, &path, track, fps)?, true),
1273 };
1274 let mut done = place_op(s, verb, m, op, at, lane, fps)?;
1275 // A track taken in for the first time is a new source: the reply says so, with its file and track.
1276 if added {
1277 let file = source_name(s, m);
1278 done.text = format!("added src:{m} ({file} audio track {track}); {}", done.text);
1279 }
1280 Ok(done)
1281}
1282
1283/// Stills are placed by the engine's own rule (their own length, no in/out).
1284fn place_op(
1285 s: &mut PlaybackSession,
1286 verb: &str,
1287 n: usize,
1288 op: &Value,
1289 at: u32,
1290 lane: Option<Lane>,
1291 fps: f64,
1292) -> Result<Done, String> {
1293 let path: PathBuf = s.sources()[n].path.clone();
1294 if engine::is_image(&path) {
1295 let still = s.still_secs();
1296 if op.get("audio_track").is_some() {
1297 return Err(format!("src:{n} is a still image; it has no audio track to choose"));
1298 }
1299 if op.get("in").is_some() || op.get("out").is_some() {
1300 return Err(format!(
1301 "src:{n} is a still image, which takes no in/out: give `length` for how long it shows (default {still:.1} s, the project's still length, up to {STILL_MAX_SECS:.0} s), or trim its out edge after placing it: trim {{clip, edge:\"out\", to}}"
1302 ));
1303 }
1304 if matches!(lane, Some(l) if l.kind == LaneKind::Audio) {
1305 return Err(format!("src:{n} is a still image; it goes on a video lane"));
1306 }
1307 // A lane the timeline does not have is named as missing, the way a clip's placement names it.
1308 if let Some(l) = lane.filter(|l| !s.lanes().contains(l)) {
1309 return Err(missing_lane(s, l));
1310 }
1311 // `length` sets how long the still shows; omitted, it is the project's still length.
1312 let asked = length(op, "length", fps)?;
1313 let run = (!engine::is_still(&path)).then(|| s.file_frames(&path));
1314 let len = match asked {
1315 None => run.unwrap_or_else(|| (still * fps).ceil().max(1.0) as u32),
1316 Some(0) => return Err(format!("place src:{n}: a still's length must be more than 0")),
1317 Some(l) if run.is_some_and(|r| l > r) => {
1318 return Err(format!("place src:{n}: length {} is past the sequence's {}", secs_text(l, fps), secs_text(run.unwrap_or(0), fps)))
1319 }
1320 Some(l) if f64::from(l) > STILL_MAX_SECS * fps => {
1321 return Err(format!(
1322 "place src:{n}: length {} is past the {STILL_MAX_SECS:.0} s a still may run",
1323 secs_text(l, fps)
1324 ))
1325 }
1326 Some(l) => l,
1327 };
1328 // A still takes the picture lane it is asked for (V1 when none), so that lane is what it can overwrite.
1329 let overwrite = overwrite_arg(op)?;
1330 let target = lane.unwrap_or(Lane::V1);
1331 let hit = if s.lanes().contains(&target) { overlapping(s, target, at, at + len, &[], fps) } else { Vec::new() };
1332 if !hit.is_empty() && !overwrite {
1333 return Err(format!(
1334 "{} at {} is taken: src:{n} would overwrite {}. Give overwrite:true to replace what is there, or another at or lane",
1335 parse::lane_name(target),
1336 parse::tc(at, fps),
1337 hit.join(", ")
1338 ));
1339 }
1340 let stream = s.sources()[n].audio_stream;
1341 // The clips of this still already at `at`, on any lane: the one this placement makes is the
1342 // one that is not among them (a second lane can hold the same still at the same start).
1343 let already = clips_of_source_at(s, n, at);
1344 let placed = s
1345 .place_stream_at(parse::secs(at, fps), &path, stream, lane)
1346 .map_err(|e| e.to_string())?;
1347 if !placed {
1348 return Err(format!("src:{n} did not place at {}", parse::tc(at, fps)));
1349 }
1350 // The engine places a still at its default length; a `length` trims the out edge to it.
1351 if asked.is_some() {
1352 let made: Vec<(Lane, u32)> = clips_of_source_at(s, n, at).into_iter().filter(|x| !already.contains(x)).collect();
1353 let idx = match made.as_slice() {
1354 [(l, _)] => s.lane_clips(*l).iter().position(|c| c.start == at && c.source == n).map(|i| (*l, i)),
1355 _ => None,
1356 };
1357 match idx {
1358 // Already that long (the default is five seconds): nothing to trim.
1359 Some((l, i)) if s.lane_clips(l)[i].end() == at + len => {}
1360 Some((l, i)) if s.trim_clip(l, i, Edge::End, at + len) => {}
1361 _ => return Err(format!("place src:{n}: the still could not be given length {} at {}", secs_text(len, fps), parse::tc(at, fps))),
1362 }
1363 }
1364 let touched = clips_of_source_at(s, n, at);
1365 let kind = if run.is_some() { "sequence" } else { "still" };
1366 let mut text = format!("{verb} src:{n} ({kind}) @{at}f");
1367 if asked.is_some() {
1368 text.push_str(&format!(" for {}", secs_text(len, fps)));
1369 }
1370 if !hit.is_empty() {
1371 text.push_str(&format!(" — overwrote {}", hit.join(", ")));
1372 }
1373 return Ok(plain(text, touched));
1374 }
1375 // `audio_track` picks the sound of a multi-audio file. The source's own track is placed as any
1376 // other; a different one is a whole track of its own (place_track_op).
1377 let track = match audio_track_arg(op)? {
1378 Some(t) => Some((t, track_language(&path, n, t)?)),
1379 None => None,
1380 };
1381 if let Some((t, _)) = &track
1382 && *t != s.sources()[n].audio_stream
1383 {
1384 return place_track_op(s, verb, n, op, (at, lane), *t, fps);
1385 }
1386 let b = Base::of(s, &path);
1387 let frames = source_frames(s, n, lane, fps);
1388 let given_in = opt_source_time(op, "in", b, frames)?;
1389 let given_out = opt_source_time(op, "out", b, frames)?;
1390 let in_f = given_in.as_ref().map_or(0, |p| p.0);
1391 // `length` sets the out point from in, so a B-roll cut to a duration needs no speed math.
1392 let len_f = length(op, "length", fps)?;
1393 let stretch = stretch_arg(op)?;
1394 if stretch && len_f.is_none() {
1395 return Err(format!("place src:{n}: stretch:true needs length, the duration the source is fitted into"));
1396 }
1397 // `stretch` plays the whole source (from in, to out or its end) over `length`: the placement
1398 // takes the source's length and is then sped up or slowed to fill `length`.
1399 let (out_f, stretch_to) = match (len_f, &given_out) {
1400 (Some(len), _) if stretch => {
1401 let end_f = given_out.as_ref().map_or(frames, |p| p.0);
1402 if end_f <= in_f {
1403 return Err(format!("place src:{n}: out must be after in"));
1404 }
1405 let x = f64::from(end_f - in_f) / f64::from(len.max(1));
1406 if !(0.25..=4.0).contains(&x) {
1407 return Err(format!(
1408 "place src:{n} stretch to {}: fitting {} of source into it needs speed ×{}, outside 0.25–4; a length nearer the source's, or a different in/out",
1409 parse::tc(len, fps),
1410 parse::tc(end_f - in_f, fps),
1411 compact(x)
1412 ));
1413 }
1414 (end_f, Some((len, x)))
1415 }
1416 (Some(_), Some(_)) => {
1417 return Err(format!(
1418 "place src:{n}: give out or length, not both: length sets the out point from in"
1419 ))
1420 }
1421 (Some(len), None) => {
1422 let end_f = in_f.saturating_add(len);
1423 if end_f > frames {
1424 return Err(format!(
1425 "place src:{n} length {}: from in {} it runs past the source end at {}; a shorter length, an earlier in, or stretch:true to fit the source into that length",
1426 parse::tc(len, fps),
1427 b.pos(b.native(in_f)),
1428 b.pos(b.native(frames))
1429 ));
1430 }
1431 (end_f, None)
1432 }
1433 (None, Some(out)) => (range_end(op.get("in"), op.get("out").unwrap_or(&Value::Null), b, fps, frames, in_f, out.0), None),
1434 (None, None) => (frames, None),
1435 };
1436 let audio = audio_arg(op, lane)?;
1437 let overwrite = overwrite_arg(op)?;
1438 let mut replaced = Vec::new();
1439 // A stretch is placed at its speed, so the clip fills `length` and the overlap check sees that span.
1440 let speed = match stretch_to {
1441 Some((_, x)) => Speed::from_permille((x * 1000.0).round() as u16),
1442 None => Speed::NORMAL,
1443 };
1444 let mut touched = place_range(s, n, in_f, out_f, Dest { at, lane, audio, overwrite }, speed, &mut replaced)
1445 .map_err(|e| overlap_rounding_note(e, op, at, len_f, b.src_fps(), fps))?;
1446 // The reply names where the clip landed, which is `at` unless the engine moved it, and the source
1447 // range it landed with: a take is cut to its shorter half, so that can be shorter than asked.
1448 let landed = touched.first().map_or(at, |t| t.1);
1449 let (in_f, out_f) = landed_span(s, &touched, n).unwrap_or((in_f, out_f));
1450 let mut text = format!("{verb} src:{n} {} at timeline {landed}f", b.span(in_f, out_f));
1451 for (_, note) in [given_in, given_out].into_iter().flatten() {
1452 text.push_str(&note);
1453 }
1454 if let Some((len, x)) = stretch_to {
1455 // The clip was placed at its speed (a linked sound with it), so it already fills `length`.
1456 let &(l, st) = touched.first().ok_or_else(|| format!("place src:{n}: nothing placed to stretch"))?;
1457 let idx = s.lane_clips(l).iter().position(|c| c.start == st).ok_or_else(|| format!("place src:{n}: nothing placed to stretch"))?;
1458 let now = s.lane_clips(l).get(idx).map_or(len, |c| c.frames());
1459 touched = s.lane_clips(l).get(idx).map(|c| vec![(l, c.start)]).unwrap_or(touched);
1460 text.push_str(&format!("; stretched ×{} to {} ({}f){}", speed_text(x), secs_text(now, fps), now, speed_note(x)));
1461 }
1462 if let Some((t, lang)) = &track {
1463 text.push_str(&format!(" with audio track {t} ({lang})"));
1464 }
1465 text.push_str(&fit_note(s, n, &touched));
1466 if !replaced.is_empty() {
1467 text.push_str(&format!(" — overwrote {}", replaced.join(", ")));
1468 }
1469 Ok(plain(text, touched))
1470}
1471
1472/// The note a placed picture owes when its aspect differs from the project canvas and it is
1473/// fitted (the default): the bars it gets, and the policy that crops instead. Empty for sound,
1474/// a still, a matching aspect, or a clip on another fit policy.
1475fn fit_note(s: &PlaybackSession, n: usize, touched: &[(Lane, u32)]) -> String {
1476 let Some(&(l, st)) = touched.first() else { return String::new() };
1477 if l.kind != LaneKind::Video {
1478 return String::new();
1479 }
1480 let Some(idx) = s.lane_clips(l).iter().position(|c| c.start == st) else { return String::new() };
1481 if !matches!(s.fit_of(l, idx), FitPolicy::Fit) {
1482 return String::new();
1483 }
1484 let Some(v) = engine::probe_media(&s.sources()[n].path).video else { return String::new() };
1485 let (cw, ch) = s.resolution();
1486 if cw == 0 || ch == 0 || v.width == 0 || v.height == 0 {
1487 return String::new();
1488 }
1489 let (src, canvas) = (f64::from(v.width) / f64::from(v.height), f64::from(cw) / f64::from(ch));
1490 if (src / canvas - 1.0).abs() < 0.01 {
1491 return String::new();
1492 }
1493 let bars = if src > canvas { "letterbox" } else { "pillarbox" };
1494 // The displayed size (a turn already applied), as the frame shows it: the bars sit at the sides for a
1495 // narrower picture and at the top and bottom for a wider one.
1496 format!("; fitted with {bars} (displayed {}×{} on {cw}×{ch}); fit {{clip, policy:\"fill\"}} crops to the frame instead", v.width, v.height)
1497}
1498
1499/// `stretch` on a place: true fits the whole source into `length` by changing its speed.
1500fn stretch_arg(op: &Value) -> Result<bool, String> {
1501 match op.get("stretch") {
1502 None | Some(Value::Null) => Ok(false),
1503 Some(Value::Bool(b)) => Ok(*b),
1504 Some(_) => Err("`stretch` must be true or false".into()),
1505 }
1506}
1507
1508/// The length of source `n` a placement on `lane` reads, in timeline frames. An audio lane takes
1509/// the sound, so a video file's audio stream sets the length there (a 2 s picture with 60 s of
1510/// sound places 60 s); every other lane takes the picture, whose frame count is the file's length.
1511fn source_frames(s: &PlaybackSession, n: usize, lane: Option<Lane>, fps: f64) -> u32 {
1512 if lane.is_some_and(|l| l.kind == LaneKind::Audio)
1513 && let Some(frames) = sound_frames(s, n, fps)
1514 {
1515 return frames;
1516 }
1517 s.file_frames(&s.sources()[n].path)
1518}
1519
1520/// The length of source `n`'s sound in timeline frames, rounded up: the wall an audio-lane clip of
1521/// it is held to (the engine's `wall_table`). None when it has no sound or its length cannot be read.
1522fn sound_frames(s: &PlaybackSession, n: usize, fps: f64) -> Option<u32> {
1523 let src = &s.sources()[n];
1524 let secs = engine::AudioSession::stream_duration_secs(&src.path, src.audio_stream).ok().flatten()?;
1525 let frames = (secs * fps).ceil();
1526 (frames.is_finite() && (1.0..=f64::from(u32::MAX)).contains(&frames)).then_some(frames as u32)
1527}
1528
1529/// The source range `[in, out)` of the clip a placement landed with, read back from the lanes it
1530/// touched: the clip of source `n` at the start the placement reports. None when none is there.
1531fn landed_span(s: &PlaybackSession, got: &[(Lane, u32)], n: usize) -> Option<(u32, u32)> {
1532 got.iter().find_map(|&(l, st)| {
1533 s.lane_clips(l).iter().find(|c| c.start == st && c.source == n).map(|c| (c.in_frame, c.out_frame))
1534 })
1535}
1536
1537/// `overwrite`: true lets a placement replace the clips it lands on. Off when not given.
1538fn overwrite_arg(op: &Value) -> Result<bool, String> {
1539 match op.get("overwrite") {
1540 None | Some(Value::Null) => Ok(false),
1541 Some(Value::Bool(b)) => Ok(*b),
1542 Some(_) => Err("`overwrite` must be true or false".into()),
1543 }
1544}
1545
1546/// Where an append, keep or assemble starts when it gives no `at`: the end of the lane it
1547/// writes (`lane`, or V1 where the picture goes), so an empty V1 starts at 0 whatever the sound holds.
1548fn tail_start(s: &PlaybackSession, lane: Option<Lane>) -> u32 {
1549 let l = lane.unwrap_or(Lane::V1);
1550 if !s.lanes().contains(&l) {
1551 return 0;
1552 }
1553 s.lane_clips(l).iter().map(|c| c.end()).max().unwrap_or(0)
1554}
1555
1556fn op_place(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Done, String> {
1557 let n = source_arg(s, op)?;
1558 let at = need(op, "at", fps, end)?;
1559 let lane = lane_arg(op, "lane")?;
1560 place_op(s, "place", n, op, at, lane, fps)
1561}
1562
1563/// `insert {source, in?, out?, at, to?, length?, lanes?}` and `overwrite {…}`: the three-point edit.
1564/// The source's `in`..`out` (the whole file when none) is put at timeline `at`. The length is the
1565/// source range, or `to` (the timeline out mark: duration = to − at, from `in`), or `length`.
1566/// `insert` opens room on the lanes the take lands on (a clip `at` falls inside is cut there, the
1567/// rest moves later); `overwrite` replaces what is there and moves nothing. The take lands on
1568/// `lanes` (one video lane for the picture, one audio lane for the sound), else the first
1569/// unlocked video and audio lanes. One engine edit, so one undo step.
1570fn op_three_point(s: &mut PlaybackSession, kind: SourceEdit, op: &Value, fps: f64, end: u32) -> Result<Done, String> {
1571 let verb = if kind == SourceEdit::Insert { "insert" } else { "overwrite" };
1572 // `src` is the short spelling of `source`.
1573 let mut aliased = op.clone();
1574 if let Some(o) = aliased.as_object_mut()
1575 && let Some(v) = o.remove("src")
1576 {
1577 if o.contains_key("source") {
1578 return Err(format!("{verb}: give source or src, not both"));
1579 }
1580 o.insert("source".into(), v);
1581 }
1582 let op = &aliased;
1583 let n = source_arg(s, op)?;
1584 let at = need(op, "at", fps, end)?;
1585 let to = opt_time(op, "to", fps, end)?;
1586 let len_arg = length(op, "length", fps)?;
1587 let path: PathBuf = s.sources()[n].path.clone();
1588 let still = engine::is_image(&path);
1589 let picture = still || engine::probe_media(&path).video.is_some();
1590 let sound = !still
1591 && !AudioSession::probe_streams(&path)
1592 .map_err(|e| format!("src:{n}: cannot read its sound: {e}"))?
1593 .is_empty();
1594 if !picture && !sound {
1595 return Err(format!("src:{n} has neither picture nor sound"));
1596 }
1597 // The lanes the take lands on: those named, else the first unlocked of each kind it has.
1598 let first_free = |kind: LaneKind| s.lanes().into_iter().find(|l| l.kind == kind && !s.lane_locked(*l));
1599 let (vl, al) = match lane_list(op, "lanes")? {
1600 Some(list) => {
1601 if list.is_empty() {
1602 return Err(format!("{verb}: `lanes` is empty: name a video lane, an audio lane, or both, e.g. [\"V1\",\"A1\"]"));
1603 }
1604 for &l in &list {
1605 if l.kind == LaneKind::Subtitle {
1606 return Err(format!("{verb}: a source cannot go on a caption lane ({})", parse::lane_name(l)));
1607 }
1608 if !s.lanes().contains(&l) {
1609 return Err(missing_lane(s, l));
1610 }
1611 }
1612 let pick = |kind: LaneKind| -> Result<Option<Lane>, String> {
1613 let of: Vec<Lane> = list.iter().copied().filter(|l| l.kind == kind).collect();
1614 match of.as_slice() {
1615 [] => Ok(None),
1616 [l] => Ok(Some(*l)),
1617 _ => Err(format!("{verb}: `lanes` names two lanes of one kind; a take lands on at most one video and one audio lane")),
1618 }
1619 };
1620 (pick(LaneKind::Video)?, pick(LaneKind::Audio)?)
1621 }
1622 None => {
1623 let v = if picture { Some(first_free(LaneKind::Video).ok_or("every video lane is locked: unlock one, or name lanes")?) } else { None };
1624 let a = if sound { Some(first_free(LaneKind::Audio).ok_or("every audio lane is locked: unlock one, or name lanes")?) } else { None };
1625 (v, a)
1626 }
1627 };
1628 if let Some(l) = vl.filter(|_| !picture) {
1629 return Err(format!("src:{n} has no picture; it cannot go on {}: name an audio lane (A1..)", parse::lane_name(l)));
1630 }
1631 if let Some(l) = al.filter(|_| !sound) {
1632 return Err(format!("src:{n} has no sound; it cannot go on {}: name a video lane (V1..)", parse::lane_name(l)));
1633 }
1634 let lanes: Vec<Lane> = vl.into_iter().chain(al).collect();
1635 check_unlocked(s, &lanes)?;
1636
1637 // The duration a timeline out mark or a length asks for.
1638 let dur = match (to, len_arg) {
1639 (Some(_), Some(_)) => return Err(format!("{verb} src:{n}: give `to` or `length`, not both")),
1640 (Some(t), None) if t <= at => {
1641 return Err(format!("{verb} src:{n}: `to` ({}) must be after `at` ({})", parse::tc(t, fps), parse::tc(at, fps)))
1642 }
1643 (Some(t), None) => Some(t - at),
1644 (None, Some(0)) => return Err(format!("{verb} src:{n}: length must be more than 0")),
1645 (None, l) => l,
1646 };
1647 let (in_f, out_f, note) = if still {
1648 let still = s.still_secs();
1649 if op.get("in").is_some() || op.get("out").is_some() {
1650 return Err(format!(
1651 "src:{n} is a still image, which takes no in/out: give `to` or `length` for how long it shows (default {still:.1} s, the project's still length, up to {STILL_MAX_SECS:.0} s)"
1652 ));
1653 }
1654 let run = (!engine::is_still(&path)).then(|| s.file_frames(&path));
1655 let len = dur.or(run).unwrap_or_else(|| (still * fps).ceil().max(1.0) as u32);
1656 if run.is_some_and(|r| len > r) {
1657 return Err(format!("{verb} src:{n}: {} is past the sequence's {}", secs_text(len, fps), secs_text(run.unwrap_or(0), fps)));
1658 }
1659 if f64::from(len) > STILL_MAX_SECS * fps {
1660 return Err(format!("{verb} src:{n}: {} is past the {STILL_MAX_SECS:.0} s a still may run", secs_text(len, fps)));
1661 }
1662 (0, len, String::new())
1663 } else {
1664 let b = Base::of(s, &path);
1665 let frames = source_frames(s, n, vl.is_none().then_some(al).flatten(), fps);
1666 let given_in = opt_source_time(op, "in", b, frames)?;
1667 let given_out = opt_source_time(op, "out", b, frames)?;
1668 let in_f = given_in.as_ref().map_or(0, |p| p.0);
1669 let out_f = match (dur, &given_out) {
1670 (Some(_), Some(_)) => {
1671 return Err(format!("{verb} src:{n}: give out, or the timeline length (`to`/`length`), not both: a duration sets the out point from in"))
1672 }
1673 (Some(d), None) => {
1674 let o = in_f.saturating_add(d);
1675 if o > frames {
1676 return Err(format!(
1677 "{verb} src:{n}: {} from in {} runs past the source end at {}; a shorter range or an earlier in",
1678 secs_text(d, fps),
1679 b.pos(b.native(in_f)),
1680 b.pos(b.native(frames))
1681 ));
1682 }
1683 o
1684 }
1685 (None, Some(o)) => o.0,
1686 (None, None) => frames,
1687 };
1688 if out_f <= in_f || out_f > frames {
1689 return Err(format!(
1690 "src:{n} {} plays {} to {}; the range {} to {} is not inside it",
1691 source_name(s, n),
1692 b.pos(0),
1693 b.pos(b.native(frames)),
1694 b.pos(b.native(in_f)),
1695 b.pos(b.native(out_f)),
1696 ));
1697 }
1698 let notes: String = [given_in, given_out].into_iter().flatten().map(|(_, note)| note).collect();
1699 (in_f, out_f, notes)
1700 };
1701 let items: Vec<(Lane, Clip)> = lanes.iter().map(|&l| (l, clip_of(n, in_f, out_f))).collect();
1702 let before: Vec<(Lane, Vec<Clip>)> = lanes.iter().map(|&l| (l, s.lane_clips(l).to_vec())).collect();
1703 s.edit_from_source_at(kind, parse::secs(at, fps), &items).map_err(|e| format!("{verb} src:{n} at {}: {e}", parse::tc(at, fps)))?;
1704
1705 // What landed: the source range and length the take has (a take is cut to its shorter half).
1706 let touched: Vec<(Lane, u32)> = lanes.iter().map(|&l| (l, at)).collect();
1707 let (l_in, l_out) = landed_span(s, &touched, n).unwrap_or((in_f, out_f));
1708 let len = s.lane_clips(touched[0].0).iter().find(|c| c.start == at && c.source == n).map_or(out_f - in_f, |c| c.frames());
1709 let names: Vec<String> = lanes.iter().map(|&l| parse::lane_name(l)).collect();
1710 let shown = match (still, engine::is_still(&path)) {
1711 (true, true) => "(still)".to_string(),
1712 (true, false) => "(sequence)".to_string(),
1713 _ => Base::of(s, &path).span(l_in, l_out),
1714 };
1715 let mut text = format!(
1716 "{verb} src:{n} {shown} at timeline {at}f ({}) on {} for {}{note}",
1717 secs_text(at, fps),
1718 names.join("+"),
1719 secs_text(len, fps)
1720 );
1721 if kind == SourceEdit::Insert {
1722 let cut: Vec<String> = before
1723 .iter()
1724 .flat_map(|(l, cs)| cs.iter().filter(|c| c.start < at && at < c.end()).map(|c| parse::addr(*l, c.start)))
1725 .collect();
1726 let moved: usize = before.iter().map(|(_, cs)| cs.iter().filter(|c| c.start >= at || (c.start < at && at < c.end())).count()).sum();
1727 if !cut.is_empty() {
1728 text.push_str(&format!(" — split {}", cut.join(", ")));
1729 }
1730 if moved > 0 {
1731 text.push_str(&format!("{} rippled the later clips on {} {} later", if cut.is_empty() { " —" } else { ";" }, names.join("+"), secs_text(len, fps)));
1732 }
1733 } else {
1734 let end_f = at + len;
1735 let replaced: Vec<String> = overwrite_notes(&before, at, end_f, fps);
1736 if !replaced.is_empty() {
1737 text.push_str(&format!(" — overwrote {}", replaced.join(", ")));
1738 }
1739 }
1740 text.push_str(&fit_note(s, n, &touched));
1741 Ok(plain(text, touched))
1742}
1743
1744fn op_append(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Done, String> {
1745 let n = source_arg(s, op)?;
1746 let lane = lane_arg(op, "lane")?;
1747 if let Some(until) = opt_time(op, "until", fps, end)? {
1748 if op.get("audio_track").is_some() {
1749 return Err(format!("append src:{n}: audio_track does not loop: place the track once with place, then copy it"));
1750 }
1751 if op.get("length").is_some() {
1752 return Err(format!("append src:{n}: until and length do not combine: give until, or a length for one copy"));
1753 }
1754 return append_loop(s, op, n, lane, until, fps);
1755 }
1756 let at = tail_start(s, lane);
1757 // Append pairs sound as a laneless place does. audio:false lays the picture alone on V1
1758 // (or `lane`) at the end; audio:true is the default, so it is taken out before audio_arg reads it.
1759 match op.get("audio") {
1760 Some(Value::Bool(false)) => place_op(s, "append", n, op, at, Some(lane.unwrap_or(Lane::V1)), fps),
1761 Some(Value::Bool(true)) => {
1762 let mut paired = op.clone();
1763 if let Some(o) = paired.as_object_mut() {
1764 o.remove("audio");
1765 }
1766 place_op(s, "append", n, &paired, at, lane, fps)
1767 }
1768 _ => place_op(s, "append", n, op, at, lane, fps),
1769 }
1770}
1771
1772/// `append {source, lane?, until, in?, out?, audio?}`: the source's range (its in..out, or the
1773/// whole file) laid back to back from the end of `lane` (V1 when none) until timeline time
1774/// `until`; the last copy is trimmed to end there. Every copy goes through `place_range`, so
1775/// a video lane pairs sound and a busy lane refuses, as a plain append does.
1776fn append_loop(
1777 s: &mut PlaybackSession,
1778 op: &Value,
1779 n: usize,
1780 lane: Option<Lane>,
1781 until: u32,
1782 fps: f64,
1783) -> Result<Done, String> {
1784 let path: PathBuf = s.sources()[n].path.clone();
1785 if engine::is_image(&path) {
1786 return Err(format!("append src:{n} until: src:{n} is a still image; a still is placed with place, and loops are for media files"));
1787 }
1788 let b = Base::of(s, &path);
1789 let frames = s.file_frames(&path);
1790 let in_f = opt_source_time(op, "in", b, frames)?.map_or(0, |p| p.0);
1791 let out_f = opt_source_time(op, "out", b, frames)?.map_or(frames, |p| p.0);
1792 if out_f <= in_f {
1793 return Err(format!("append src:{n} until: the range {} is empty", b.span(in_f, out_f)));
1794 }
1795 let first = tail_start(s, lane);
1796 if until <= first {
1797 return Err(format!(
1798 "append src:{n} until {}: {} already runs to {}, past that time",
1799 parse::tc(until, fps),
1800 lane.map_or("V1".to_string(), parse::lane_name),
1801 parse::tc(first, fps)
1802 ));
1803 }
1804 let audio = audio_arg(op, lane)?;
1805 let copy = out_f - in_f;
1806 let mut at = first;
1807 let mut copies = 0usize;
1808 let mut touched = Vec::new();
1809 let mut replaced = Vec::new();
1810 while at < until {
1811 let seg = copy.min(until - at);
1812 let got = place_range(s, n, in_f, in_f + seg, Dest { at, lane, audio, overwrite: false }, Speed::NORMAL, &mut replaced)
1813 .map_err(|e| format!("append src:{n} copy {}: {e}", copies + 1))?;
1814 // The next copy starts where this one landed: a take is cut to its shorter half.
1815 let (pa, pz) = landed_span(s, &got, n).unwrap_or((in_f, in_f + seg));
1816 at += pz - pa;
1817 touched.extend(got);
1818 copies += 1;
1819 }
1820 let trimmed = if (until - first).is_multiple_of(copy) { String::new() } else { " (last copy trimmed)".to_string() };
1821 let mut text = format!(
1822 "loop src:{n} {copies}× on {} from {} to {}{trimmed}",
1823 lane.map_or("V1+A1".to_string(), parse::lane_name),
1824 parse::tc(first, fps),
1825 parse::tc(until, fps)
1826 );
1827 // A range shorter than the gap plays back to back: say how often, so a short file is not a surprise.
1828 if copies > 1 {
1829 text.push_str(&format!(
1830 "; the {:.1}s range looped {copies} times to fill it",
1831 parse::secs(copy, fps)
1832 ));
1833 }
1834 if !replaced.is_empty() {
1835 text.push_str(&format!(" — overwrote {}", replaced.join(", ")));
1836 }
1837 Ok(plain(text, touched))
1838}
1839
1840fn op_keep(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Done, String> {
1841 let n = source_arg(s, op)?;
1842 let lane = lane_arg(op, "lane")?;
1843 let audio = audio_arg(op, lane)?;
1844 let overwrite = overwrite_arg(op)?;
1845 let mut replaced = Vec::new();
1846 let ranges = op
1847 .get("ranges")
1848 .and_then(Value::as_array)
1849 .filter(|r| !r.is_empty())
1850 .ok_or("missing `ranges`: give [[in,out], ...] in source times, e.g. [[\"0s\",\"4.5s\"]]")?;
1851 let path: PathBuf = s.sources()[n].path.clone();
1852 if engine::is_image(&path) {
1853 return Err(format!("src:{n} is a still image; keep takes ranges of a media file"));
1854 }
1855 let b = Base::of(s, &path);
1856 let frames = s.file_frames(&path);
1857 let first = opt_time(op, "at", fps, end)?.unwrap_or_else(|| tail_start(s, lane));
1858 let mut at = first;
1859 let mut touched = Vec::new();
1860 let mut notes = String::new();
1861 let mut shown = Vec::with_capacity(ranges.len());
1862 for (i, r) in ranges.iter().enumerate() {
1863 let pair = r
1864 .as_array()
1865 .filter(|p| p.len() == 2)
1866 .ok_or_else(|| format!("ranges[{i}] must be [in,out], two source times"))?;
1867 let (a, note_a) = source_time(&pair[0], b, frames, "in").map_err(|e| format!("ranges[{i}] {e}"))?;
1868 let (z, note_z) = source_time(&pair[1], b, frames, "out").map_err(|e| format!("ranges[{i}] {e}"))?;
1869 let z = range_end(Some(&pair[0]), &pair[1], b, fps, frames, a, z);
1870 let got = place_range(s, n, a, z, Dest { at, lane, audio, overwrite }, Speed::NORMAL, &mut replaced).map_err(|e| format!("ranges[{i}]: {e}"))?;
1871 // The span named is the one the clip landed with (frame-snapped), as clip_info reads it; the
1872 // next range starts where it ends.
1873 let (pa, pz) = landed_span(s, &got, n).unwrap_or((a, z));
1874 at += pz - pa;
1875 touched.extend(got);
1876 notes.push_str(&note_a);
1877 notes.push_str(&note_z);
1878 shown.push(b.span(pa, pz));
1879 }
1880 let mut text = format!("keep src:{n} {} at timeline {first}f{notes}", shown.join(", "));
1881 if !replaced.is_empty() {
1882 text.push_str(&format!(" — overwrote {}", replaced.join(", ")));
1883 }
1884 Ok(plain(text, touched))
1885}
1886
1887/// `assemble {items:[{source, in?, out?}], lane?, at?, gap?}`: each item is a
1888/// source range, laid back to back from `at`; items may come from different sources.
1889fn op_assemble(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Done, String> {
1890 let items = op
1891 .get("items")
1892 .and_then(Value::as_array)
1893 .filter(|r| !r.is_empty())
1894 .ok_or("missing `items`: give [{source, in?, out?}, ...]; each item is one range, laid end to end")?;
1895 let lane = lane_arg(op, "lane")?;
1896 let audio = audio_arg(op, lane)?;
1897 let gap = length(op, "gap", fps)?.unwrap_or(0);
1898 if gap > 0 && lane.is_none() {
1899 return Err("assemble: a gap needs `lane` (V1.. or A1..); without one the items land at the timeline end and the gap cannot be kept".into());
1900 }
1901 let overwrite = overwrite_arg(op)?;
1902 let mut replaced = Vec::new();
1903 let first = opt_time(op, "at", fps, end)?.unwrap_or_else(|| tail_start(s, lane));
1904 let mut at = first;
1905 let mut touched = Vec::new();
1906 let mut notes: Vec<String> = Vec::new();
1907 for (i, item) in items.iter().enumerate() {
1908 if let Some(key) = item.as_object().and_then(|o| o.keys().find(|k| !matches!(k.as_str(), "source" | "in" | "out"))) {
1909 return Err(format!("items[{i}]: unknown key `{key}`; an item takes source, in, out"));
1910 }
1911 let n = source_arg(s, item).map_err(|e| format!("items[{i}]: {e}"))?;
1912 let path: PathBuf = s.sources()[n].path.clone();
1913 if engine::is_image(&path) {
1914 return Err(format!("items[{i}]: src:{n} is a still image; assemble takes ranges of media files"));
1915 }
1916 let base = Base::of(s, &path);
1917 let frames = s.file_frames(&path);
1918 let given_in = opt_source_time(item, "in", base, frames).map_err(|e| format!("items[{i}] {e}"))?;
1919 let given_out = opt_source_time(item, "out", base, frames).map_err(|e| format!("items[{i}] {e}"))?;
1920 let a = given_in.as_ref().map_or(0, |p| p.0);
1921 let z = given_out.as_ref().map_or(frames, |p| p.0);
1922 let got = place_range(s, n, a, z, Dest { at, lane, audio, overwrite }, Speed::NORMAL, &mut replaced).map_err(|e| format!("items[{i}]: {e}"))?;
1923 // place_range refuses an empty or backwards range, so z > a here. The next item starts where
1924 // this one landed, which a take cut to its shorter half makes shorter than the range asked.
1925 let (pa, pz) = landed_span(s, &got, n).unwrap_or((a, z));
1926 at += (pz - pa) + if i + 1 < items.len() { gap } else { 0 };
1927 touched.extend(got);
1928 notes.extend(given_in.into_iter().chain(given_out).map(|(_, note)| note));
1929 }
1930 let mut names: Vec<String> = Vec::new();
1931 for &(l, _) in &touched {
1932 let name = parse::lane_name(l);
1933 if !names.contains(&name) {
1934 names.push(name);
1935 }
1936 }
1937 let mut text = format!(
1938 "assembled {} clip(s) on {} from {} to {}{}",
1939 items.len(),
1940 names.join("+"),
1941 secs_text(first, fps),
1942 secs_text(at, fps),
1943 notes.concat()
1944 );
1945 if !replaced.is_empty() {
1946 text.push_str(&format!(" — overwrote {}", replaced.join(", ")));
1947 }
1948 Ok(plain(text, touched))
1949}
1950
1951// ---- cuts and moves -------------------------------------------------------
1952
1953fn op_split(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Done, String> {
1954 let asked = need(op, "at", fps, end)?;
1955 let all = s.lanes();
1956 let named = lane_list(op, "lanes")?;
1957 if named.as_ref().is_some_and(|v| v.is_empty()) {
1958 return Err(format!(
1959 "split {}: `lanes` is empty; name the lanes to cut, or leave `lanes` out to cut every lane",
1960 shown_time(op.get("at"), asked)
1961 ));
1962 }
1963 let explicit = named.is_some();
1964 let mut cut_on: Vec<Lane> = match &named {
1965 None => all.clone(),
1966 Some(v) => {
1967 if let Some(&l) = v.iter().find(|l| !all.contains(l)) {
1968 return Err(format!("lane {} is not on this timeline", parse::lane_name(l)));
1969 }
1970 v.clone()
1971 }
1972 };
1973 // A slow clip can be cut only where a source frame begins, so a frame between two showings of one
1974 // is moved to the nearest cut point that every clip the cut runs through can take (the same snap
1975 // insert_time, remove_time and freeze make). The reply says so.
1976 let scope_for_cut = if explicit { cut_on.clone() } else { cut_lanes(s, &cut_on, asked) };
1977 let at = cut_point(s, &scope_for_cut, asked);
1978 // Default: a clip the cut runs through takes its linked partners' lanes with it, so a take
1979 // stays whole. With explicit `lanes` only the named lanes are cut: a partner not named stays
1980 // whole, and the take is unlinked at the cut (reported below).
1981 let mut partners: Vec<String> = Vec::new();
1982 let mut unlink_at: Vec<String> = Vec::new();
1983 for &l in &cut_on.clone() {
1984 if l.kind == LaneKind::Subtitle {
1985 continue;
1986 }
1987 for (i, c) in s.lane_clips(l).iter().enumerate() {
1988 if c.start < at && at < c.end() {
1989 let take = take_of(s, l, i);
1990 if explicit && take.iter().any(|(m, _)| !cut_on.contains(m)) {
1991 // The cut unlinks this take, which changes the link of every clip in it: a locked one refuses.
1992 if let Some(&(m, _)) = take.iter().find(|(m, _)| s.lane_locked(*m)) {
1993 return Err(format!(
1994 "split {}: the cut would detach {} from its take at the cut, and {} is locked; {}, or cut its lanes too (leave `lanes` out)",
1995 shown_time(op.get("at"), asked),
1996 addr_of(s, l, i),
1997 parse::lane_name(m),
1998 lock_msg(m)
1999 ));
2000 }
2001 let names: Vec<String> = take.iter().map(|&(m, j)| addr_of(s, m, j)).collect();
2002 unlink_at.push(names.join(" + "));
2003 }
2004 for (m, _) in take {
2005 if !cut_on.contains(&m) && !explicit {
2006 cut_on.push(m);
2007 partners.push(format!("{} (linked to {})", parse::lane_name(m), addr_of(s, l, i)));
2008 }
2009 }
2010 }
2011 }
2012 }
2013 let media_on: Vec<Lane> = cut_on.iter().copied().filter(|l| l.kind != LaneKind::Subtitle).collect();
2014 check_unlocked(s, &media_on)?;
2015 // The clips the cut runs through, read before it: only these are cut, so only these are named.
2016 let straddled: Vec<(Lane, u32)> = media_on
2017 .iter()
2018 .flat_map(|&l| s.lane_clips(l).iter().filter(|c| c.start < at && at < c.end()).map(move |c| (l, c.start)).collect::<Vec<_>>())
2019 .collect();
2020 if !s.cut_at_lanes(parse::secs(at, fps), &cut_on) {
2021 return Err(format!(
2022 "nothing to split at {}: no clip spans that frame, or a cut is already there",
2023 shown_time(op.get("at"), asked)
2024 ));
2025 }
2026 // An explicit-lanes cut that leaves a partner whole unlinks the take at the cut: the engine does
2027 // that inside the split itself (one undo step), so the reply below only reports it.
2028 // Each clip cut leaves its left piece at its start and a right piece at the cut.
2029 let mut touched = Vec::new();
2030 for (l, start) in straddled {
2031 touched.push((l, start));
2032 touched.push((l, at));
2033 }
2034 let kept: Vec<String> = all.iter().filter(|l| !cut_on.contains(l)).map(|&l| parse::lane_name(l)).collect();
2035 let mut text = format!("split @{at}f");
2036 if at != asked {
2037 text.push_str(&cut_moved_note(asked, at));
2038 }
2039 if !partners.is_empty() {
2040 text.push_str(&format!("; also cut {}", partners.join(", ")));
2041 }
2042 if !kept.is_empty() {
2043 text.push_str(&format!("; kept whole: {}", kept.join(", ")));
2044 }
2045 if !unlink_at.is_empty() {
2046 text.push_str(&format!("; now detached at the cut: {}", unlink_at.join(", ")));
2047 }
2048 Ok(plain(text, touched))
2049}
2050
2051/// A time as the caller wrote it, with its frame: `99s (2970f)`. A frame count
2052/// (`2970f`) is already the frame, so it is shown alone.
2053fn shown_time(v: Option<&Value>, frame: u32) -> String {
2054 match v {
2055 Some(Value::String(t)) if !t.trim().ends_with(['f', 'F']) => format!("{} ({frame}f)", t.trim()),
2056 Some(Value::Number(n)) => format!("{n}s ({frame}f)"),
2057 _ => format!("{frame}f"),
2058 }
2059}
2060
2061/// A trim the engine refused after the room check passed: the edge is not where it asked, and
2062/// it did not move, so the reply names the room the edge has and says the move was refused.
2063fn trim_refusal(s: &PlaybackSession, lane: Lane, idx: usize, edge: Edge, shown: &str, addr: &str) -> String {
2064 let side = if edge == Edge::Start { "in" } else { "out" };
2065 match s.trim_room(lane, idx, edge) {
2066 Some((lo, hi)) => format!(
2067 "trim {addr} {side} to {shown} refused: the edge can travel {lo}f–{hi}f and the engine would not move it"
2068 ),
2069 None => format!("no clip at {addr}"),
2070 }
2071}
2072
2073fn op_trim(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Done, String> {
2074 let (lane, idx) = clip_arg(s, op)?;
2075 let addr = addr_of(s, lane, idx);
2076 let (edge, side) = match op.get("edge").and_then(Value::as_str) {
2077 Some("in") => (Edge::Start, "in"),
2078 Some("out") => (Edge::End, "out"),
2079 _ => return Err("`edge` must be \"in\" or \"out\"".into()),
2080 };
2081 let to = need(op, "to", fps, end)?;
2082 let shown = shown_time(op.get("to"), to);
2083 let group = match op.get("scope").and_then(Value::as_str).unwrap_or("group") {
2084 "group" => true,
2085 "clip" => false,
2086 other => return Err(format!("scope `{other}` is not \"group\" or \"clip\"")),
2087 };
2088 // `ripple:true` closes (or opens) the hole the edge leaves, and what follows moves with it:
2089 // Premiere's ripple trim. The clip's linked partners move with it through the engine.
2090 let ripple = match op.get("ripple") {
2091 None => false,
2092 Some(v) => v.as_bool().ok_or("`ripple` must be true or false")?,
2093 };
2094 let verb = if ripple { "ripple trim" } else { "trim" };
2095 let take = take_of(s, lane, idx);
2096 let lanes: Vec<Lane> = take.iter().map(|&(l, _)| l).collect();
2097 if group {
2098 check_unlocked(s, &lanes)?;
2099 } else {
2100 // The clip alone changes only its own lane. Its partners keep their media, but leaving the take
2101 // changes their link, which a locked lane never takes, so a locked partner refuses with the way out.
2102 check_unlocked(s, &[lane])?;
2103 if let Some(&(pl, _)) = take.iter().skip(1).find(|(l, _)| s.lane_locked(*l)) {
2104 let pn = parse::lane_name(pl);
2105 return Err(format!(
2106 "trim {addr} scope:\"clip\" refused: trimming {addr} alone unlinks it from {pn}, which is locked; unlock {pn} or use scope:\"group\""
2107 ));
2108 }
2109 }
2110 if group && take.len() > 1 && !ripple {
2111 let at_clip = |s: &PlaybackSession| s.lane_clips(lane).get(idx).map(|c| if edge == Edge::Start { c.start } else { c.end() });
2112 let before = at_clip(s);
2113 let mut done = trim_take(s, &take, edge, to, fps, &addr, side, &shown, op.get("to"))?;
2114 if let Some(hint) = in_edge_hole_hint(edge, before, at_clip(s), &lanes.iter().map(|&l| parse::lane_name(l)).collect::<Vec<_>>()) {
2115 done.text.push_str(&format!("; {hint}"));
2116 }
2117 return Ok(done);
2118 }
2119 let edge_at = |s: &PlaybackSession, l: Lane, i: usize| {
2120 s.lane_clips(l).get(i).map(|c| if edge == Edge::Start { c.start } else { c.end() })
2121 };
2122 let before = edge_at(s, lane, idx);
2123 // Clamped to the room the edge has, here, so the reply can name the clamp and its wall. The
2124 // walls are named before anything moves: a clamp is worded from the bound it reached.
2125 let Some((lo, hi)) = s.trim_room(lane, idx, edge) else {
2126 return Err(format!("no clip at {addr}"));
2127 };
2128 let Some(bounds) = s.trim_bounds(lane, idx, edge) else {
2129 return Err(format!("no clip at {addr}"));
2130 };
2131 // The other edge bounds what this one may be: a clip that would end where it starts
2132 // (or start where it ends) has no picture left, so that is refused, not clamped.
2133 if let Some(c) = s.lane_clips(lane).get(idx).cloned() {
2134 let (other, other_name, ok) = match edge {
2135 Edge::End => (c.start, "in", to > c.start),
2136 Edge::Start => (c.end(), "out", to < c.end()),
2137 };
2138 if !ok {
2139 return Err(format!(
2140 "trim {addr} {side} to {shown} would leave no picture: its {side} edge must stay {} its {other_name} edge at {}",
2141 if edge == Edge::End { "after" } else { "before" },
2142 parse::tc(other, fps)
2143 ));
2144 }
2145 }
2146 let target = to.clamp(lo, hi);
2147 let (named_lo, named_hi) = (wall_named(s, lane, idx, edge, lo, bounds.0), wall_named(s, lane, idx, edge, hi, bounds.1));
2148 // The blockers are read before anything moves; the clicked clip is never its own blocker.
2149 let own: Vec<(Lane, u32)> = s.lane_clips(lane).get(idx).map(|c| (lane, c.start)).into_iter().collect();
2150 let words_lo = clamp_words(s, &own, named_lo, lane, edge, lo);
2151 let words_hi = clamp_words(s, &own, named_hi, lane, edge, hi);
2152 let reason = if target == hi { words_hi.clone() } else { words_lo.clone() };
2153 // An edge that is already where the op asks is a note, not a failed batch: nothing moves.
2154 if Some(to) == before {
2155 return Ok(plain(format!("{addr} {side} edge is already at {}: nothing to trim", parse::tc(to, fps)), Vec::new()));
2156 }
2157 if Some(target) == before {
2158 return Ok(plain(
2159 format!("{addr} {side} edge is already at {}: {reason}; it cannot go to {shown}", parse::tc(target, fps)),
2160 Vec::new(),
2161 ));
2162 }
2163 // Trimming one clip of a take alone leaves the take. Only this clip is unlinked: its partners are
2164 // regrouped among themselves, so they stay linked to each other (and their media does not move).
2165 // This comes after the no-op checks above: a trim that changes nothing must not detach anything.
2166 if !group && take.len() > 1 {
2167 if !s.ungroup(lane, idx) {
2168 return Err(format!("trim {addr} refused: its take could not be detached"));
2169 }
2170 let partners = &take[1..];
2171 for &(pl, pi) in &partners[1..] {
2172 s.group(partners[0].0, partners[0].1, pl, pi)
2173 .map_err(|e| format!("trim {addr} refused: its partners could not stay linked: {e}"))?;
2174 }
2175 }
2176 let trimmed = match ripple {
2177 true => s.ripple_trim_clip(lane, idx, edge, target),
2178 false => s.trim_clip(lane, idx, edge, target),
2179 };
2180 if !trimmed {
2181 return Err(trim_refusal(s, lane, idx, edge, &shown, &addr));
2182 }
2183 // A ripple start keeps the clip's start where it is and cuts its head, so the start alone does
2184 // not show the move: the cut point is where the edge landed.
2185 let ripple_head = ripple && edge == Edge::Start;
2186 let actual = if ripple_head { Some(target) } else { edge_at(s, lane, idx) };
2187 if actual == before {
2188 return Ok(plain(format!("{addr} {side} edge did not move: nothing to trim"), Vec::new()));
2189 }
2190 let touched: Vec<(Lane, u32)> = s.lane_clips(lane).get(idx).map(|c| (lane, c.start)).into_iter().collect();
2191 let landed = actual.unwrap_or(to);
2192 let mut text = match asked_arrow(op.get("to"), fps, landed) {
2193 Some(a) => format!("{verb} {addr} {side}: {a}"),
2194 None => format!("{verb} {addr} {side} → {}", parse::tc(landed, fps)),
2195 };
2196 if !group && take.len() > 1 {
2197 let rest = take.len() - 1;
2198 if rest == 1 {
2199 text.push_str("; now detached from its take (1 partner left where it is and unlinked)");
2200 } else {
2201 text.push_str(&format!("; now detached from its take ({rest} partners stay linked to each other)"));
2202 }
2203 }
2204 if let Some(a) = actual.filter(|&a| a != to) {
2205 let words = if a == hi { &words_hi } else { &words_lo };
2206 text.push_str(&format!("; clamped from {shown} to {}: {words}", parse::tc(a, fps)));
2207 }
2208 // An in edge that moved later leaves the clip where it was, so a hole opens before it. Name the
2209 // close for it: no ripple trim exists, and close_gaps pulls the later clips left.
2210 if let Some(hint) = in_edge_hole_hint(edge, before, actual, &[parse::lane_name(lane)]).filter(|_| !ripple) {
2211 text.push_str(&format!("; {hint}"));
2212 }
2213 Ok(plain(text, touched))
2214}
2215
2216/// `split_edit {clip, side, edge, to}`: the split edit on the clip's take. `side` names the half
2217/// whose edge moves ("audio" or "video"), `edge` which edge of that half ("in" or "out"), and the
2218/// other half stays put. The pair is unlinked first, as a group trims together.
2219fn op_split_edit(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Done, String> {
2220 let (lane, idx) = clip_arg(s, op)?;
2221 let addr = addr_of(s, lane, idx);
2222 let (audio, word) = match op.get("side").and_then(Value::as_str) {
2223 Some("audio") => (true, "audio"),
2224 Some("video") => (false, "video"),
2225 _ => return Err("`side` must be \"audio\" or \"video\": the half of the take whose edge moves".into()),
2226 };
2227 let edge = match op.get("edge").and_then(Value::as_str) {
2228 Some("in") => Edge::Start,
2229 Some("out") => Edge::End,
2230 _ => return Err("`edge` must be \"in\" or \"out\"".into()),
2231 };
2232 let to = need(op, "to", fps, end)?;
2233 let shown = shown_time(op.get("to"), to);
2234 let take = take_of(s, lane, idx);
2235 check_unlocked(s, &take.iter().map(|&(l, _)| l).collect::<Vec<_>>())?;
2236 let (l, i, moved, landed) = engine::editkeys::split_edit_at(s, (lane, idx), audio, Some(edge), to)
2237 .map_err(|e| format!("split_edit {addr} {word} {shown} refused: {e}"))?;
2238 let ed = if moved == Edge::Start { "in" } else { "out" };
2239 let now = addr_of(s, l, i);
2240 let mut text = match asked_arrow(op.get("to"), fps, landed) {
2241 Some(a) => format!("split_edit {now} {word} {ed}: {a}"),
2242 None => format!("split_edit {now} {word} {ed} → {}", parse::tc(landed, fps)),
2243 };
2244 if take.len() > 1 {
2245 text.push_str("; the pair is unlinked");
2246 }
2247 let touched: Vec<(Lane, u32)> = s.lane_clips(l).get(i).map(|c| (l, c.start)).into_iter().collect();
2248 Ok(plain(text, touched))
2249}
2250
2251/// The one-line offer after a trim of an in edge that moved later: the hole it leaves is closed by
2252/// close_gaps on the lane (no op trims and pulls later clips left in one step). None when the in
2253/// edge did not move later, so no hole opened.
2254fn in_edge_hole_hint(edge: Edge, before: Option<u32>, actual: Option<u32>, names: &[String]) -> Option<String> {
2255 let (before, actual) = (before?, actual?);
2256 if edge != Edge::Start || actual <= before {
2257 return None;
2258 }
2259 let closes: Vec<String> = names.iter().map(|n| format!("close_gaps {{lane:\"{n}\"}}")).collect();
2260 Some(format!(
2261 "the in edge leaves a hole before the clip; to pull later clips left over it, {} (each closes every gap on its lane)",
2262 closes.join(" and ")
2263 ))
2264}
2265
2266/// The bound an edge's wall is named by, read against the clips on its lane. The engine calls a
2267/// source's end the binding wall when it meets a neighbour exactly (equal walls count as media),
2268/// so a wall that a neighbour sits on is named for the neighbour: that clip is what stops the edge.
2269fn wall_named(s: &PlaybackSession, lane: Lane, idx: usize, edge: Edge, at: u32, bound: WallBound) -> WallBound {
2270 if !matches!(bound, WallBound::Source | WallBound::Cap) {
2271 return bound;
2272 }
2273 let clips = s.lane_clips(lane);
2274 let meets = match edge {
2275 Edge::End => clips.get(idx + 1).is_some_and(|n| n.start == at),
2276 Edge::Start => idx.checked_sub(1).and_then(|p| clips.get(p)).is_some_and(|p| p.end() == at),
2277 };
2278 if meets { WallBound::Neighbour(at) } else { bound }
2279}
2280
2281/// What stopped an edge at `at`, in words, from the bound the engine named for that wall
2282/// ([`engine::project::WallBound`]), asked before the trim.
2283fn wall_words(bound: WallBound, edge: Edge, lane: Lane, at: u32) -> String {
2284 match bound {
2285 WallBound::Source if edge == Edge::Start => format!("clamped at the source's start ({at} frames)"),
2286 WallBound::Source => format!("clamped at the source's end ({at} frames)"),
2287 WallBound::Neighbour(f) => format!("clamped where it meets {}", parse::addr(lane, f)),
2288 WallBound::Timeline => "clamped at the timeline start".to_string(),
2289 WallBound::MinLength => "clamped at the 1-frame minimum".to_string(),
2290 WallBound::Cap => "clamped at the still's length cap".to_string(),
2291 }
2292}
2293
2294/// The clip that stops an edge at frame `at`, named by address: a clip that meets the edge there
2295/// (ends at `at` for an in edge, starts there for an out edge), looked for on the wall's own lane
2296/// first and then the other lanes of its kind. The take's own members (`members`, as (lane, start))
2297/// never count: a clip cannot be its own partner's blocker.
2298fn blocker_addr(s: &PlaybackSession, members: &[(Lane, u32)], lane: Lane, edge: Edge, at: u32) -> Option<String> {
2299 let mut order = vec![lane];
2300 order.extend(s.lanes().iter().copied().filter(|&l| l != lane && l.kind == lane.kind));
2301 for l in order {
2302 for c in s.lane_clips(l) {
2303 let meets = match edge {
2304 Edge::Start => c.end() == at,
2305 Edge::End => c.start == at,
2306 };
2307 if meets && !members.contains(&(l, c.start)) {
2308 return Some(parse::addr(l, c.start));
2309 }
2310 }
2311 }
2312 None
2313}
2314
2315/// The words for the wall that clamps an edge at `at`: a neighbour wall is named by the clip that
2316/// actually meets the edge (see [`blocker_addr`]); the other walls read as [`wall_words`].
2317fn clamp_words(s: &PlaybackSession, members: &[(Lane, u32)], bound: WallBound, lane: Lane, edge: Edge, at: u32) -> String {
2318 match bound {
2319 WallBound::Neighbour(_) => match blocker_addr(s, members, lane, edge, at) {
2320 Some(addr) => format!("clamped where it meets {addr}"),
2321 None => wall_words(bound, edge, lane, at),
2322 },
2323 other => wall_words(other, edge, lane, at),
2324 }
2325}
2326
2327/// The index of the take member on `lane` (the take holds one clip per lane).
2328fn idx_of(take: &[(Lane, usize)], lane: Lane) -> usize {
2329 take.iter().find(|&&(l, _)| l == lane).map_or(0, |&(_, i)| i)
2330}
2331
2332/// Trims the whole take `take` (two or more linked clips) so the `edge` of every member
2333/// lands on one absolute time: `to`, clamped to the room every member has, so the shortest
2334/// source or the nearest neighbour sets the limit and the reply says which. The members are
2335/// unlinked for the move, each trimmed on its own, then grouped again.
2336#[allow(clippy::too_many_arguments)]
2337fn trim_take(
2338 s: &mut PlaybackSession,
2339 take: &[(Lane, usize)],
2340 edge: Edge,
2341 to: u32,
2342 fps: f64,
2343 addr: &str,
2344 side: &str,
2345 shown: &str,
2346 asked: Option<&Value>,
2347) -> Result<Done, String> {
2348 let mut lo = 0u32;
2349 let mut hi = u32::MAX;
2350 // The wall that set each limit, named by its member's bound before anything moves.
2351 let mut lo_wall: Option<(Lane, WallBound)> = None;
2352 let mut hi_wall: Option<(Lane, WallBound)> = None;
2353 for &(l, i) in take {
2354 let (Some((a, b)), Some((wl, wh))) = (s.trim_room(l, i, edge), s.trim_bounds(l, i, edge)) else {
2355 return Err(format!("trim {addr} refused: a member of its take has no {side} edge to trim"));
2356 };
2357 if a >= lo {
2358 lo = a;
2359 lo_wall = Some((l, wl));
2360 }
2361 if b <= hi {
2362 hi = b;
2363 hi_wall = Some((l, wh));
2364 }
2365 }
2366 if lo > hi {
2367 return Err(format!("trim {addr} {side} refused: the take has no room to move that edge"));
2368 }
2369 let target = to.clamp(lo, hi);
2370 let edge_at = |s: &PlaybackSession, l: Lane, i: usize| {
2371 s.lane_clips(l).get(i).map(|c| if edge == Edge::Start { c.start } else { c.end() })
2372 };
2373 // Zero length on the clicked clip (its other edge is what the in/out would cross): refused, not clamped.
2374 if let Some(c) = s.lane_clips(take[0].0).get(take[0].1).cloned() {
2375 let ok = if edge == Edge::End { to > c.start } else { to < c.end() };
2376 if !ok {
2377 return Err(format!("trim {addr} {side} to {shown} would leave no picture: its {side} edge must stay {} its other edge", if edge == Edge::End { "after" } else { "before" }));
2378 }
2379 }
2380 // Read before anything moves: the wall that set the limit the target reached.
2381 let members: Vec<(Lane, u32)> = take.iter().filter_map(|&(l, i)| s.lane_clips(l).get(i).map(|c| (l, c.start))).collect();
2382 let reason = if target == to {
2383 None
2384 } else if target == hi {
2385 hi_wall.map(|(l, w)| clamp_words(s, &members, wall_named(s, l, idx_of(take, l), edge, hi, w), l, edge, hi))
2386 } else {
2387 lo_wall.map(|(l, w)| clamp_words(s, &members, wall_named(s, l, idx_of(take, l), edge, lo, w), l, edge, lo))
2388 };
2389 if take.iter().all(|&(l, i)| edge_at(s, l, i) == Some(target)) {
2390 let why = match &reason {
2391 Some(r) => format!(": {r}; it cannot go to {shown}"),
2392 None => ": nothing to trim".to_string(),
2393 };
2394 return Ok(plain(format!("{addr} {side} edge is already at {}{why}", parse::tc(target, fps)), Vec::new()));
2395 }
2396 for &(l, i) in take {
2397 s.ungroup(l, i);
2398 }
2399 for &(l, i) in take {
2400 if edge_at(s, l, i) == Some(target) {
2401 continue;
2402 }
2403 if !s.trim_clip(l, i, edge, target) {
2404 return Err(format!(
2405 "trim {addr} refused: {} would not take its edge at {}",
2406 parse::lane_name(l),
2407 parse::tc(target, fps)
2408 ));
2409 }
2410 }
2411 let regrouped = s.group_all(take).is_ok();
2412 let touched: Vec<(Lane, u32)> = take.iter().filter_map(|&(l, i)| s.lane_clips(l).get(i).map(|c| (l, c.start))).collect();
2413 let own = touched.first().copied();
2414 let with: Vec<String> = touched.iter().skip(1).filter(|t| Some(**t) != own).map(|&(l, st)| parse::addr(l, st)).collect();
2415 let tail = if with.is_empty() { String::new() } else { format!(" (with {})", with.join(", ")) };
2416 let mut text = match asked_arrow(asked, fps, target) {
2417 Some(a) => format!("trim {addr} {side}: {a}{tail}"),
2418 None => format!("trim {addr} {side} → {}{tail}", parse::tc(target, fps)),
2419 };
2420 if let Some(r) = reason {
2421 text.push_str(&format!("; clamped from {shown} to {}: {r}", parse::tc(target, fps)));
2422 }
2423 if !regrouped {
2424 text.push_str("; take now detached: its members' spans no longer agree");
2425 }
2426 Ok(plain(text, touched))
2427}
2428
2429/// Why a move refused. Checked in order: the lanes' locks, a kind mismatch,
2430/// then the first clip a member's requested span would run into (the group's
2431/// members at their shifted spans), and a fallback for the rest.
2432fn move_refusal(s: &PlaybackSession, lane: Lane, idx: usize, to: Lane, at: u32, at_shown: &str, take: &[(Lane, usize)]) -> String {
2433 let fps = parse::session_fps(s);
2434 let addr = addr_of(s, lane, idx);
2435 let target = parse::lane_name(to);
2436 if to.kind != lane.kind {
2437 return format!("move {addr} to {target}@{at_shown} refused: a clip moves only within its kind (V to V, A to A)");
2438 }
2439 let Some(clip) = s.lane_clips(lane).get(idx).cloned() else {
2440 return format!("no clip at {addr}");
2441 };
2442 let delta = i64::from(at) - i64::from(clip.start);
2443 let moving: Vec<(Lane, u32)> = take
2444 .iter()
2445 .filter_map(|&(l, i)| s.lane_clips(l).get(i).map(|c| (l, c.start)))
2446 .collect();
2447 // Every collision is named: the clicked clip's, and each linked partner's at its own destination.
2448 let mut hits: Vec<String> = Vec::new();
2449 for &(l, i) in take {
2450 let Some(c) = s.lane_clips(l).get(i).cloned() else { continue };
2451 let dest = if (l, i) == (lane, idx) { to } else { l };
2452 let start = i64::from(c.start) + delta;
2453 if start < 0 {
2454 return format!("move {addr} to {target}@{at_shown} refused: the take would start before frame 0");
2455 }
2456 let start = start as u32;
2457 let who = if (l, i) == (lane, idx) { addr.to_string() } else { format!("its partner {}", addr_of(s, l, i)) };
2458 for o in overlapping(s, dest, start, start + c.frames(), &moving, fps) {
2459 hits.push(format!("{who} at {} would overlap {o}", parse::tc(start, fps)));
2460 }
2461 }
2462 if hits.is_empty() {
2463 return format!("move {addr} to {target}@{at_shown} refused: the engine would not place the take there (no clip is in its way)");
2464 }
2465 format!(
2466 "move {addr} to {target}@{at_shown} refused: {}; move or lift the clip(s) in the way first, pick another at, or insert:true to ripple the clip in (the later clips move to make room)",
2467 hits.join("; ")
2468 )
2469}
2470
2471fn op_move(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Done, String> {
2472 let (lane, idx) = clip_arg(s, op)?;
2473 let addr = addr_of(s, lane, idx);
2474 let before = s
2475 .lane_clips(lane)
2476 .get(idx)
2477 .ok_or_else(|| format!("no clip at {addr}"))?.clone();
2478 let to = lane_arg(op, "to_lane")?.unwrap_or(lane);
2479 let at = need(op, "at", fps, end)?;
2480 // Already where it was asked to go: nothing moves, so there is nothing to refuse or undo.
2481 if to == lane && at == before.start {
2482 return Ok(plain(
2483 format!("move {addr}: already at {} — nothing to do", parse::tc(at, fps)),
2484 vec![(lane, before.start)],
2485 ));
2486 }
2487 // A move carries the whole take, so every lane the take is on (and the target) must be unlocked.
2488 let take = take_of(s, lane, idx);
2489 let mut lanes: Vec<Lane> = take.iter().map(|&(l, _)| l).collect();
2490 lanes.push(to);
2491 check_unlocked(s, &lanes)?;
2492 let at_shown = shown_time(op.get("at"), at);
2493 if insert_arg(op)? {
2494 return op_move_insert(s, op, fps, (lane, idx), (to, at), &before, &addr);
2495 }
2496 if !s.move_clip_to(lane, idx, to, at) {
2497 return Err(move_refusal(s, lane, idx, to, at, &at_shown, &take));
2498 }
2499 // Moves clamp `at` to the room the take has, so the new address is read
2500 // back, matching the clip by its source range (the one thing a move does not change).
2501 let touched: Vec<(Lane, u32)> = s
2502 .lane_clips(to)
2503 .iter()
2504 .find(|c| c.source == before.source && c.in_frame == before.in_frame && c.out_frame == before.out_frame)
2505 .map(|c| vec![(to, c.start)])
2506 .unwrap_or_default();
2507 // The batch line adds the new address after the arrow, so the text stops at the old one.
2508 let clamped = match touched.first() {
2509 Some(&(_, st)) if st != at => format!(" (asked for {}; the neighbours leave room only there)", parse::tc(at, fps)),
2510 _ => String::new(),
2511 };
2512 let mut text = format!("move {addr}{clamped}");
2513 // Titles follow the picture they sit over: one wholly over the clip travels with it by default,
2514 // `titles:true` carries the ones it only partly covers too, `titles:false` carries none. A title
2515 // that stays put is said so, with the title_set that moves it.
2516 if let (LaneKind::Video, Some(&(_, new_start))) = (lane.kind, touched.first()) {
2517 let carry_all = titles_arg(op)?;
2518 let delta = i64::from(new_start) - i64::from(before.start);
2519 let (old_start, old_end) = (i64::from(before.start), i64::from(before.end()));
2520 let mut moved = Vec::new();
2521 let mut plan = Vec::new();
2522 for (i, t) in s.titles().iter().enumerate() {
2523 let (ts, te) = (i64::from(t.start), i64::from(t.start) + i64::from(t.frames));
2524 if ts >= old_end || te <= old_start {
2525 continue;
2526 }
2527 let whole = ts >= old_start && te <= old_end;
2528 if carry_all.unwrap_or(whole) {
2529 let to_at = (ts + delta).max(0);
2530 moved.push(format!("T{} {}→{}", i + 1, secs_text(t.start, fps), secs_text(to_at as u32, fps)));
2531 let mut t2 = t.clone();
2532 t2.start = to_at as u32;
2533 plan.push((t.text.clone(), t.start, t2));
2534 } else {
2535 let to_at = (ts + delta).max(0);
2536 text.push_str(&format!(
2537 "; T{} ({}) sat over {addr} and stays put — move it with the clip: title_set {{title:\"T{}\", at:\"{}f\"}}",
2538 i + 1,
2539 secs_text(t.frames, fps),
2540 i + 1,
2541 to_at
2542 ));
2543 }
2544 }
2545 for (text, from, t) in plan {
2546 retitle(s, &text, from, Some(t)).map_err(|e| format!("move {addr}: {e}"))?;
2547 }
2548 if !moved.is_empty() {
2549 text.push_str(&format!("; titles moved with the clip: {}", moved.join(", ")));
2550 }
2551 }
2552 Ok(plain(text, touched))
2553}
2554
2555/// `insert` on a move: true for a ripple move, false (the default) for the slide.
2556fn insert_arg(op: &Value) -> Result<bool, String> {
2557 match op.get("insert") {
2558 None | Some(Value::Null) => Ok(false),
2559 Some(Value::Bool(b)) => Ok(*b),
2560 Some(_) => Err("`insert` must be true or false".into()),
2561 }
2562}
2563
2564/// The clip on `lane` that a move carried from `before`: found by its start and its source range.
2565fn find_moved(s: &PlaybackSession, lane: Lane, start: u32, before: &Clip) -> Option<usize> {
2566 s.lane_clips(lane)
2567 .iter()
2568 .position(|c| c.start == start && c.source == before.source && c.in_frame == before.in_frame && c.out_frame == before.out_frame)
2569}
2570
2571#[allow(clippy::too_many_arguments)]
2572/// `move {clip, at, to_lane?, insert:true}`: a ripple move. The clip (its take with the linked
2573/// partners) leaves its slot, which closes on the ripple scope as `ripple_delete` closes one, and
2574/// lands at `at`, with the later clips on the scope lanes pushed to make room. Done in engine
2575/// steps that keep the clip whole: the room opens first, the clip moves into it, then the slot it
2576/// left closes. Titles over the clip carry with it, as a plain move carries them.
2577fn op_move_insert(
2578 s: &mut PlaybackSession,
2579 op: &Value,
2580 fps: f64,
2581 from: (Lane, usize),
2582 target: (Lane, u32),
2583 before: &Clip,
2584 addr: &str,
2585) -> Result<Done, String> {
2586 let (lane, idx) = from;
2587 let (to, at) = target;
2588 let (old, dur) = (before.start, before.frames());
2589 let target = parse::lane_name(to);
2590 let at_shown = shown_time(op.get("at"), at);
2591 if to == lane && old < at && at < old + dur {
2592 return Err(format!(
2593 "move {addr} insert to {target}@{at_shown} refused: the clip cannot be inserted inside its own span; pick a point outside {addr}"
2594 ));
2595 }
2596 let take = take_of(s, lane, idx);
2597 let mut sc = rip_scope(s, op, &take, old)?;
2598 if !sc.lanes.contains(&to) {
2599 sc.lanes.push(to);
2600 }
2601 check_unlocked(s, &sc.lanes)?;
2602 // The slot the clip leaves is cut out of the scope lanes once it has moved; a clip outside the take there is lost.
2603 let hit = unrelated_in_cut(s, &sc.lanes, &take, old, old + dur);
2604 if !hit.is_empty() {
2605 return Err(unrelated_refusal(
2606 &format!("move {addr} insert to {target}@{at_shown}"),
2607 addr,
2608 &hit,
2609 &format!("move {addr} without insert to leave the gap instead"),
2610 ));
2611 }
2612 let shown = (at_shown.clone(), format!("{:.1}s", parse::secs(dur, fps)));
2613 // Titles over the clip: the ones wholly over it travel, `titles:true` the partial ones too, `titles:false` none.
2614 let carry_all = titles_arg(op)?;
2615 let (old_i, old_e) = (i64::from(old), i64::from(old + dur));
2616 let mut carried: Vec<(usize, u32)> = Vec::new();
2617 let mut carried_text: Vec<String> = Vec::new();
2618 if lane.kind == LaneKind::Video {
2619 for (i, t) in s.titles().iter().enumerate() {
2620 let (ts, te) = (i64::from(t.start), i64::from(t.start) + i64::from(t.frames));
2621 if ts >= old_e || te <= old_i {
2622 continue;
2623 }
2624 let whole = ts >= old_i && te <= old_e;
2625 if carry_all.unwrap_or(whole) {
2626 let ns = (i64::from(at) + (ts - old_i)).max(0) as u32;
2627 carried.push((i, ns));
2628 carried_text.push(format!("T{} {}→{}", i + 1, secs_text(t.start, fps), secs_text(ns, fps)));
2629 }
2630 }
2631 }
2632 // The room opens, the clip moves into it, and the slot it left closes. Before `at` the room
2633 // opens at `at` and the slot is the one the clip shifted into; after it the room opens past
2634 // `at`, which is where the clip lands once the slot ahead of it has closed.
2635 // Captions over the picture travel with it: lifted out of the slot before it closes (the cut
2636 // would take them), and set down at the picture's new place once it has landed. A caption
2637 // A caption placement spanning one of the slot's edges would be split there, so by default
2638 // the move refuses it by name; `split_captions:true` splits it and reports both halves. Either
2639 // way each placement is then wholly over the picture or wholly beside it.
2640 let sub_lanes: Vec<Lane> = sc.lanes.iter().copied().filter(|l| l.kind == LaneKind::Subtitle).collect();
2641 // A caption grouped with some other take, lying over the slot, is refused before any cut: a
2642 // grouped caption moves its whole group when it is dragged, and cutting the slot would take its
2643 // cue. Captions grouped with the moved take itself travel with it.
2644 for &l in &sub_lanes {
2645 for c in s.sub_lane(l) {
2646 let Some(id) = c.link else { continue };
2647 if c.start >= old + dur || c.start + c.frames <= old {
2648 continue;
2649 }
2650 // A grouped caption wholly within the moved take's own span travels with it.
2651 if before.link == Some(id) && c.start >= old && c.start + c.frames <= old + dur {
2652 continue;
2653 }
2654 let p = c.start.max(old);
2655 let why = if before.link == Some(id) {
2656 "spans an edge of the moved take"
2657 } else {
2658 "is grouped with another take and lies over the slot the move closes"
2659 };
2660 return Err(format!(
2661 "move {addr} insert to {target}@{at_shown} refused: caption '{}' ({} {}–{}) is grouped and {why}; ungroup it or trim it first ({})",
2662 caption_words(s, c, p),
2663 parse::lane_name(l),
2664 secs_text(c.start, fps),
2665 secs_text(c.start + c.frames, fps),
2666 parse::addr(l, c.start)
2667 ));
2668 }
2669 }
2670 let split_caps = bool_arg(op, "split_captions")?;
2671 let edges = [old, old + dur];
2672 // Decided per cue: a placement may span an edge while no cue's own text does, and then the
2673 // placement is split between cues, which cuts no words. A cue whose text crosses an edge is
2674 // refused by name, unless `split_captions:true` allows the words to be cut.
2675 if !split_caps {
2676 for &p in &edges {
2677 for &l in &sub_lanes {
2678 for c in s.sub_lane(l) {
2679 if !(c.start < p && p < c.start + c.frames) {
2680 continue;
2681 }
2682 if let Some((words, a, b)) = crossing_cues(s, c, p).into_iter().next() {
2683 return Err(format!(
2684 "move {addr} insert to {target}@{at_shown} refused: cue '{words}' ({} {}–{}) crosses the edge of the moved clip; trim it, or pass split_captions:true to split it",
2685 parse::lane_name(l),
2686 secs_text(a, fps),
2687 secs_text(b, fps)
2688 ));
2689 }
2690 }
2691 }
2692 }
2693 }
2694 let mut split_notes: Vec<String> = Vec::new();
2695 for p in edges {
2696 let spanning = spanning_captions(s, &sub_lanes, p);
2697 if !spanning.is_empty() {
2698 s.cut_at_lanes(parse::secs(p, fps), &sub_lanes);
2699 for c in &spanning {
2700 let lane = parse::lane_name(c.lane);
2701 let cut_cues = c.cues_cut.clone();
2702 if cut_cues.is_empty() {
2703 split_notes.push(format!("{lane} split at {} between cues (no cue cut)", secs_text(p, fps)));
2704 continue;
2705 }
2706 split_notes.push(format!(
2707 "'{}' ({lane} {}–{}) split at {} into {lane} {}–{} and {lane} {}–{}",
2708 c.words,
2709 secs_text(c.start, fps),
2710 secs_text(c.end, fps),
2711 secs_text(p, fps),
2712 secs_text(c.start, fps),
2713 secs_text(p, fps),
2714 secs_text(p, fps),
2715 secs_text(c.end, fps)
2716 ));
2717 }
2718 }
2719 }
2720 let carry = carried_captions(s, &sc.lanes, old, dur);
2721 // The insert splits any clip it lands inside (the moved clip's own slot aside): named, not left to the effects.
2722 let p = if at <= old { at } else { at + dur };
2723 let split_at: Vec<String> = sc
2724 .lanes
2725 .iter()
2726 .filter(|l| l.kind != LaneKind::Subtitle)
2727 .flat_map(|&l| {
2728 s.lane_clips(l)
2729 .iter()
2730 .filter(move |c| c.start < p && p < c.end() && !(l == lane && c.start == old))
2731 .map(move |c| format!("{} at {}", parse::addr(l, c.start), secs_text(p, fps)))
2732 })
2733 .collect();
2734 let cut_start = if at <= old {
2735 check_carry(addr, &carry, at)?;
2736 insert_span(s, at, dur, &sc, fps, shown)?;
2737 let i = find_moved(s, lane, old + dur, before)
2738 .ok_or_else(|| format!("move {addr} insert refused: the clip could not be followed through the ripple"))?;
2739 if !s.move_clip_to(lane, i, to, at) {
2740 return Err(format!("move {addr} to {target}@{at_shown} insert refused: the engine would not place the take there"));
2741 }
2742 carry_to(s, addr, &carry, at, dur, at as i64 - (old + dur) as i64)?;
2743 old + dur
2744 } else {
2745 // Once the old slot closes the timeline is `dur` shorter: a later `at` past that would leave a gap.
2746 let post_end = parse::session_end(s).saturating_sub(dur);
2747 if at > post_end {
2748 return Err(format!(
2749 "move {addr} insert to {target}@{at_shown} refused: past the timeline end once its slot closes ({:.1}s); use at {:.1}s or less, or append it",
2750 parse::secs(post_end, fps),
2751 parse::secs(post_end, fps)
2752 ));
2753 }
2754 check_carry(addr, &carry, at + dur)?;
2755 insert_span(s, at + dur, dur, &sc, fps, shown)?;
2756 let i = find_moved(s, lane, old, before)
2757 .ok_or_else(|| format!("move {addr} insert refused: the clip could not be followed through the ripple"))?;
2758 if !s.move_clip_to(lane, i, to, at + dur) {
2759 return Err(format!("move {addr} to {target}@{at_shown} insert refused: the engine would not place the take there"));
2760 }
2761 carry_to(s, addr, &carry, at + dur, dur, at as i64 + dur as i64 - old as i64)?;
2762 old
2763 };
2764 s.cut_regions(&[(cut_start, dur)], &sc.lanes)
2765 .map_err(|e| format!("move {addr} insert refused: {e}"))?;
2766 let mut moved = if has_picture(&sc.lanes) { move_titles_for_cuts(s, &[(cut_start, dur)], fps)? } else { Vec::new() };
2767 // A carried title is set where the clip put it, so the cut's move of it is not reported: one final position each.
2768 moved.retain(|m| !carried.iter().any(|&(i, _)| m.starts_with(&format!("T{} ", i + 1))));
2769 for &(i, ns) in &carried {
2770 if let Some(mut t) = s.titles().get(i).cloned() {
2771 t.start = ns;
2772 s.set_title(i, t);
2773 }
2774 }
2775 let pushed = if at <= old {
2776 format!("the clips from {at_shown} up to its old slot moved {:.1}s later", parse::secs(dur, fps))
2777 } else {
2778 format!("the clips between its old slot and {at_shown} moved {:.1}s earlier", parse::secs(dur, fps))
2779 };
2780 let mut text = format!("move {addr} insert to {target}@{at_shown}: its old slot closed and {pushed}");
2781 if !carried_text.is_empty() {
2782 text.push_str(&format!("; titles moved with the clip: {}", carried_text.join(", ")));
2783 }
2784 if !carry.is_empty() {
2785 text.push_str(&format!("; {} caption(s) moved with the clip", carry.len()));
2786 }
2787 if !split_at.is_empty() {
2788 text.push_str(&format!("; split {}", split_at.join(", ")));
2789 }
2790 if !split_notes.is_empty() {
2791 text.push_str(&format!("; captions split: {} (positions before the move)", split_notes.join("; ")));
2792 }
2793 text.push_str(&titles_note(&moved));
2794 text.push_str(&skipped_note(&sc.skipped));
2795 let mut touched = ripple_touched(s, &sc.lanes, at.min(old));
2796 if !touched.contains(&(to, at)) {
2797 touched.push((to, at));
2798 }
2799 Ok(Done { text, touched, lanes: sc.lanes })
2800}
2801
2802/// A caption placement a ripple move lifts with the picture: its identity, and where it starts
2803/// before the ripple.
2804#[derive(Clone, Copy)]
2805struct Carry {
2806 lane: Lane,
2807 track: usize,
2808 win_in: i64,
2809 win_out: i64,
2810 frames: u32,
2811 start: u32,
2812}
2813
2814/// The captions on `lanes` that overlap the slot `[old, old+dur)` a ripple move leaves: each
2815/// placement, whole, since a caption over any part of the picture is over the picture. Linked
2816/// captions are left to their take.
2817fn carried_captions(s: &PlaybackSession, lanes: &[Lane], old: u32, dur: u32) -> Vec<Carry> {
2818 let mut out = Vec::new();
2819 for &l in lanes.iter().filter(|l| l.kind == LaneKind::Subtitle) {
2820 for c in s.sub_lane(l) {
2821 if c.link.is_none() && c.start < old + dur && c.start + c.frames > old {
2822 out.push(Carry { lane: l, track: c.track, win_in: c.in_us, win_out: c.out_us, frames: c.frames, start: c.start });
2823 }
2824 }
2825 }
2826 out
2827}
2828
2829/// Refuses before a ripple when a carried caption straddles `point`, where the ripple cuts:
2830/// the cut would split it, and it could not then be found to carry.
2831fn check_carry(addr: &str, carry: &[Carry], point: u32) -> Result<(), String> {
2832 match carry.iter().find(|c| c.start < point && point < c.start + c.frames) {
2833 Some(c) => Err(format!(
2834 "move {addr} insert refused: a caption over the picture spans {}, where the ripple opens; cut it there first",
2835 parse::addr(c.lane, c.start)
2836 )),
2837 None => Ok(()),
2838 }
2839}
2840
2841/// Sets the carried captions down `delta` frames from where the ripple left them: each one at or
2842/// past `rippled_at` has moved `dur` later with the ripple, then all move by `delta` (the picture's
2843/// own shift), the ones moving away first so none lands on one not yet moved.
2844fn carry_to(s: &mut PlaybackSession, addr: &str, carry: &[Carry], rippled_at: u32, dur: u32, delta: i64) -> Result<(), String> {
2845 let mut now: Vec<(Carry, u32)> = carry
2846 .iter()
2847 .map(|c| (*c, if c.start >= rippled_at { c.start + dur } else { c.start }))
2848 .collect();
2849 now.sort_by_key(|&(_, st)| st);
2850 if delta > 0 {
2851 now.reverse();
2852 }
2853 for (c, st) in now {
2854 let idx = s
2855 .sub_lane(c.lane)
2856 .iter()
2857 .position(|x| x.start == st && x.frames == c.frames && x.track == c.track && x.in_us == c.win_in && x.out_us == c.win_out)
2858 .ok_or_else(|| format!("move {addr} insert refused: a caption over the picture could not be followed through the ripple"))?;
2859 let to = i64::from(st) + delta;
2860 let to = u32::try_from(to).map_err(|_| format!("move {addr} insert refused: a caption over the picture would start before the timeline"))?;
2861 s.move_sub(c.lane, idx, c.lane, to)
2862 .map_err(|e| format!("move {addr} insert refused: a caption over the picture would not move: {e}"))?;
2863 }
2864 Ok(())
2865}
2866
2867/// A caption placement that spans a point a move cuts at: its lane, the words of the cue at the
2868/// point, and its span in frames.
2869struct Spanning {
2870 lane: Lane,
2871 words: String,
2872 start: u32,
2873 end: u32,
2874 /// The cues whose own text crosses the edge (their words, cut); empty when the placement
2875 /// spans the edge only between cues.
2876 cues_cut: Vec<String>,
2877}
2878
2879
2880/// The caption placements on `lanes` that span frame `p` strictly inside them, in lane order.
2881fn spanning_captions(s: &PlaybackSession, lanes: &[Lane], p: u32) -> Vec<Spanning> {
2882 let mut out = Vec::new();
2883 for &l in lanes {
2884 for c in s.sub_lane(l) {
2885 if c.start < p && p < c.start + c.frames {
2886 out.push(Spanning { lane: l, words: caption_words(s, c, p), start: c.start, end: c.start + c.frames, cues_cut: crossing_cues(s, c, p).into_iter().map(|x| x.0).collect() });
2887 }
2888 }
2889 }
2890 out
2891}
2892
2893/// The cues a placement shows whose own timeline interval strictly contains frame `p`: their
2894/// words, and the frames their text starts and ends at (the placement's mapping of cue times, as
2895/// `cues_in_span` reads it). A placement that spans `p` between two cues gives none.
2896fn crossing_cues(s: &PlaybackSession, c: &engine::project::SubClip, p: u32) -> Vec<(String, u32, u32)> {
2897 let Some(track) = s.subtitles().get(c.track) else { return Vec::new() };
2898 let window = (c.out_us - c.in_us).max(1) as f64;
2899 let frames = f64::from(c.frames);
2900 let frame_of = |us: i64| c.start as f64 + (us - c.in_us) as f64 * frames / window;
2901 track
2902 .cues
2903 .iter()
2904 .filter(|q| q.start_us < c.out_us && q.end_us > c.in_us)
2905 .filter_map(|q| {
2906 let (a, b) = (frame_of(q.start_us), frame_of(q.end_us));
2907 // Frames, so 1e-3 is a thousandth of a frame: a cue that starts on
2908 // a cut maps to 59.999996 rather than 60 and must not read as crossing.
2909 if a + 1e-3 < f64::from(p) && f64::from(p) + 1e-3 < b {
2910 let text = q.text.replace('\n', " / ");
2911 let words: String = if text.chars().count() > 60 {
2912 format!("{}…", text.chars().take(60).collect::<String>())
2913 } else {
2914 text
2915 };
2916 Some((words, a.round() as u32, b.round() as u32))
2917 } else {
2918 None
2919 }
2920 })
2921 .collect()
2922}
2923
2924/// The words of the cue a placement shows at frame `p` (or, between cues, the first cue it shows),
2925/// newlines as ` / `, cut to 60 characters.
2926fn caption_words(s: &PlaybackSession, c: &engine::project::SubClip, p: u32) -> String {
2927 let Some(track) = s.subtitles().get(c.track) else { return String::new() };
2928 let window = (c.out_us - c.in_us).max(1) as f64;
2929 let at_us = c.in_us + ((p - c.start) as f64 * window / f64::from(c.frames)) as i64;
2930 let cue = track
2931 .cues
2932 .iter()
2933 .find(|q| q.start_us <= at_us && at_us < q.end_us)
2934 .or_else(|| track.cues.iter().find(|q| q.start_us < c.out_us && q.end_us > c.in_us));
2935 match cue {
2936 Some(q) => {
2937 let text = q.text.replace('\n', " / ");
2938 if text.chars().count() > 60 {
2939 format!("{}…", text.chars().take(60).collect::<String>())
2940 } else {
2941 text
2942 }
2943 }
2944 None => String::new(),
2945 }
2946}
2947
2948/// A true-or-false op key: false when omitted.
2949fn bool_arg(op: &Value, key: &str) -> Result<bool, String> {
2950 match op.get(key) {
2951 None | Some(Value::Null) => Ok(false),
2952 Some(Value::Bool(b)) => Ok(*b),
2953 Some(_) => Err(format!("`{key}` must be true or false")),
2954 }
2955}
2956
2957/// `titles` on a move: true carries every title over the clip, false none; omitted, only the
2958/// titles wholly over it travel.
2959fn titles_arg(op: &Value) -> Result<Option<bool>, String> {
2960 match op.get("titles") {
2961 None | Some(Value::Null) => Ok(None),
2962 Some(Value::Bool(b)) => Ok(Some(*b)),
2963 Some(_) => Err("`titles` must be true or false".into()),
2964 }
2965}
2966
2967/// The link of every item on `l` that starts at or after `from`, for the ripple ops.
2968fn links_from(s: &PlaybackSession, l: Lane, from: u32) -> Vec<Option<u32>> {
2969 if l.kind == LaneKind::Subtitle {
2970 s.sub_lane(l).iter().filter(|c| c.start >= from).map(|c| c.link).collect()
2971 } else {
2972 s.lane_clips(l).iter().filter(|c| c.start >= from).map(|c| c.link).collect()
2973 }
2974}
2975
2976/// The lanes a ripple from `from` would move: the scope lanes holding anything at
2977/// or after it, and any other lane holding a link partner of such an item, since a
2978/// take moves whole. The lock check reads this set, so a locked partner refuses too.
2979fn ripple_lanes(s: &PlaybackSession, scope: &[Lane], from: u32) -> Vec<Lane> {
2980 let mut out: Vec<Lane> = Vec::new();
2981 let mut links: Vec<u32> = Vec::new();
2982 for &l in scope {
2983 let ls = links_from(s, l, from);
2984 if !ls.is_empty() && !out.contains(&l) {
2985 out.push(l);
2986 }
2987 links.extend(ls.into_iter().flatten());
2988 }
2989 for l in s.lanes() {
2990 if !out.contains(&l) && links_from(s, l, from).iter().flatten().any(|x| links.contains(x)) {
2991 out.push(l);
2992 }
2993 }
2994 out
2995}
2996
2997/// The lanes a ripple moves for `scope`, closed over what it reaches: each cut point `cuts`
2998/// inside a clip brings that clip's take, and then `ripple_lanes` runs from `from` to a fixed
2999/// point. Refuses when a locked lane is among them, named or reached through a link: a take
3000/// moves whole, so its locked member would move too. Returns the closed lane list.
3001///
3002/// A locked caption lane that a cut point falls inside is not refused: it is left out and named
3003/// in the returned skipped list, as the default scope skips locked caption lanes. A locked picture
3004/// or sound lane is refused when a cut point falls inside one of its clips (the cut would have to
3005/// split it, and the ripple would leave its halves apart), and, with `default` (no `lanes` given),
3006/// when a clip on it ends after `from`: the default scope would otherwise leave it behind while the
3007/// lanes around it move. A locked partner that the take reaches is still refused, since a take
3008/// moves whole.
3009fn ripple_guard(s: &PlaybackSession, scope: &[Lane], from: u32, cuts: &[u32], default: bool) -> Result<(Vec<Lane>, Vec<Lane>), String> {
3010 let mut lanes: Vec<Lane> = scope.to_vec();
3011 let mut skipped: Vec<Lane> = Vec::new();
3012 let mut refused: Vec<Lane> = Vec::new();
3013 for &p in cuts {
3014 for l in s.lanes() {
3015 if l.kind == LaneKind::Subtitle {
3016 if s.sub_lane(l).iter().any(|c| c.start < p && p < c.start + c.frames) && !lanes.contains(&l) {
3017 if s.lane_locked(l) {
3018 if !skipped.contains(&l) {
3019 skipped.push(l);
3020 }
3021 } else {
3022 lanes.push(l);
3023 }
3024 }
3025 continue;
3026 }
3027 for (i, c) in s.lane_clips(l).iter().enumerate() {
3028 if c.start < p && p < c.end() {
3029 if s.lane_locked(l) && !lanes.contains(&l) {
3030 if !refused.contains(&l) {
3031 refused.push(l);
3032 }
3033 continue;
3034 }
3035 for (m, _) in take_of(s, l, i) {
3036 if !lanes.contains(&m) {
3037 lanes.push(m);
3038 }
3039 }
3040 }
3041 }
3042 }
3043 }
3044 if default {
3045 for l in s.lanes() {
3046 if l.kind != LaneKind::Subtitle && s.lane_locked(l) && !lanes.contains(&l) && s.lane_clips(l).iter().any(|c| c.end() > from) && !refused.contains(&l) {
3047 refused.push(l);
3048 }
3049 }
3050 }
3051 if let Some(&l) = refused.first() {
3052 return Err(format!("{}, or pass lanes without it: the ripple would move or cut it", lock_msg(l)));
3053 }
3054 loop {
3055 let before = lanes.len();
3056 for l in ripple_lanes(s, &lanes, from) {
3057 if !lanes.contains(&l) {
3058 lanes.push(l);
3059 }
3060 }
3061 if lanes.len() == before {
3062 break;
3063 }
3064 }
3065 check_unlocked(s, &lanes)?;
3066 Ok((lanes, skipped))
3067}
3068
3069/// The clips and captions on lanes outside `scope` that start at or after `from`. A ripple
3070/// leaves them where they are, so the reply lists them (capped): empty when there are none.
3071pub(crate) fn left_behind(s: &PlaybackSession, scope: &[Lane], from: u32) -> String {
3072 const CAP: usize = 6;
3073 let mut items: Vec<String> = Vec::new();
3074 for l in s.lanes() {
3075 if scope.contains(&l) {
3076 continue;
3077 }
3078 if l.kind == LaneKind::Subtitle {
3079 items.extend(s.sub_lane(l).iter().filter(|c| c.start >= from).map(|c| parse::addr(l, c.start)));
3080 } else {
3081 items.extend(s.lane_clips(l).iter().filter(|c| c.start >= from).map(|c| parse::addr(l, c.start)));
3082 }
3083 }
3084 if items.is_empty() {
3085 return String::new();
3086 }
3087 let more = if items.len() > CAP { format!(" … {} more", items.len() - CAP) } else { String::new() };
3088 let shown: Vec<String> = items.iter().take(CAP).cloned().collect();
3089 format!("; left in place (not linked; pass lanes to move them): {}{more}", shown.join(", "))
3090}
3091
3092/// The warning a ripple owes when it moves captions but leaves the sound under them where it was:
3093/// an audio lane outside `scope` with a clip that overlaps a caption stretch the edit moves keeps
3094/// its place while the words move, so the speech and its words part. The stretch of a caption in
3095/// `scope` that moves is the part from `to` (the end of what the edit removes, read before the cut)
3096/// on; a caption wholly before `to` does not move. Empty unless such a stretch and such a clip
3097/// both exist. `shift` is the move as the reply shows it, such as "−2.000s".
3098fn sound_drift(s: &PlaybackSession, scope: &[Lane], to: u32, shift: &str) -> String {
3099 let mut stretches: Vec<(u32, u32)> = Vec::new();
3100 let mut moved: Vec<String> = Vec::new();
3101 for l in s.subtitle_lanes() {
3102 if !scope.contains(&l) {
3103 continue;
3104 }
3105 let before = stretches.len();
3106 stretches.extend(s.sub_lane(l).iter().filter(|c| c.end() > to).map(|c| (c.start.max(to), c.end())));
3107 if stretches.len() > before {
3108 moved.push(parse::lane_name(l));
3109 }
3110 }
3111 let left: Vec<String> = s
3112 .lanes()
3113 .into_iter()
3114 .filter(|l| l.kind == LaneKind::Audio && !scope.contains(l))
3115 .filter(|l| {
3116 s.lane_clips(*l)
3117 .iter()
3118 .any(|c| stretches.iter().any(|&(a, b)| c.start < b && a < c.end()))
3119 })
3120 .map(parse::lane_name)
3121 .collect();
3122 if moved.is_empty() || left.is_empty() {
3123 return String::new();
3124 }
3125 format!(
3126 "; captions on {} moved {shift} but {} (sound under them) stayed — they may no longer match the speech; add lanes:[…{}] or undo",
3127 moved.join(", "),
3128 left.join(", "),
3129 left.join(", ")
3130 )
3131}
3132
3133/// The lanes a time falls strictly inside a clip or caption of: a cut there is needed first.
3134fn straddlers(s: &PlaybackSession, at: u32) -> Vec<Lane> {
3135 s.lanes()
3136 .into_iter()
3137 .filter(|&l| {
3138 if l.kind == LaneKind::Subtitle {
3139 s.sub_lane(l).iter().any(|c| c.start < at && at < c.start + c.frames)
3140 } else {
3141 s.lane_clips(l).iter().any(|c| c.start < at && at < c.end())
3142 }
3143 })
3144 .collect()
3145}
3146
3147/// The lanes an insert or remove ripples: `lanes` as named (each must exist), else
3148/// every lane not locked.
3149fn ripple_scope(s: &PlaybackSession, op: &Value) -> Result<Vec<Lane>, String> {
3150 match lane_list(op, "lanes")? {
3151 Some(v) => {
3152 let all = s.lanes();
3153 match v.iter().find(|l| !all.contains(l)) {
3154 Some(&l) => Err(format!("lane {} is not on this timeline", parse::lane_name(l))),
3155 None => Ok(v),
3156 }
3157 }
3158 None => Ok(s.lanes().into_iter().filter(|&l| !s.lane_locked(l)).collect()),
3159 }
3160}
3161
3162/// The default scope of insert_time and remove_time: every unlocked lane, with the locked caption
3163/// lanes listed as skipped (a note, never a refusal). `lanes` replaces it, with no skips.
3164fn default_scope(s: &PlaybackSession, op: &Value) -> Result<Scope, String> {
3165 let lanes = ripple_scope(s, op)?;
3166 let skipped = if lane_list(op, "lanes")?.is_some() {
3167 Vec::new()
3168 } else {
3169 s.lanes().into_iter().filter(|&l| l.kind == LaneKind::Subtitle && s.lane_locked(l)).collect()
3170 };
3171 let explicit = lane_list(op, "lanes")?.is_some();
3172 Ok(Scope { lanes, skipped, explicit })
3173}
3174
3175/// What a rippling op moves: the lanes in scope, and the caption lanes it left
3176/// alone because they are locked and only came in by following the picture.
3177struct Scope {
3178 lanes: Vec<Lane>,
3179 skipped: Vec<Lane>,
3180 /// `lanes` was given by the caller, rather than being the default scope.
3181 explicit: bool,
3182}
3183
3184pub(crate) fn has_picture(lanes: &[Lane]) -> bool {
3185 lanes.iter().any(|l| l.kind == LaneKind::Video)
3186}
3187
3188/// The reply's note for the clips an insert cut in two, per lane: which clips were split, and the
3189/// silence (black on a picture lane) the inserted time leaves across the split. Empty when none.
3190fn split_note(splits: &[(Lane, Vec<String>)], at: u32, dur: u32, fps: f64) -> String {
3191 if splits.is_empty() {
3192 return String::new();
3193 }
3194 let parts: Vec<String> = splits
3195 .iter()
3196 .map(|(l, names)| {
3197 let gap = if l.kind == LaneKind::Audio { "silence" } else { "black" };
3198 format!(
3199 "{} split {} at {:.3}s, leaving {:.3}s of {gap} at {:.3}–{:.3}s",
3200 parse::lane_name(*l),
3201 names.join(", "),
3202 parse::secs(at, fps),
3203 parse::secs(dur, fps),
3204 parse::secs(at, fps),
3205 parse::secs(at + dur, fps)
3206 )
3207 })
3208 .collect();
3209 format!("; {}", parts.join("; "))
3210}
3211
3212/// The reply's note for caption lanes skipped as locked, empty when none were.
3213fn skipped_note(skipped: &[Lane]) -> String {
3214 if skipped.is_empty() {
3215 return String::new();
3216 }
3217 let names: Vec<String> = skipped.iter().map(|&l| parse::lane_name(l)).collect();
3218 let stays = if skipped.iter().all(|l| l.kind == LaneKind::Subtitle) { "its cues stay put" } else { "it stays put" };
3219 format!("; skipped locked {}: {stays}", names.join(", "))
3220}
3221
3222/// The one ripple rule (EDIT_DOC, RIPPLE RULE). For an op that ripples from the clips
3223/// `edited` at `from`: the lanes of those clips, the lanes of any clip linked or grouped
3224/// to one of them, closed over what the ripple reaches (a take moves whole). On a picture
3225/// lane the caption lanes come too, so cues follow the picture; a locked one among them
3226/// is skipped with a note. `lanes` replaces all of it and must name the edited lanes.
3227fn rip_scope(s: &PlaybackSession, op: &Value, edited: &[(Lane, usize)], from: u32) -> Result<Scope, String> {
3228 let mut edit_lanes: Vec<Lane> = Vec::new();
3229 for &(l, _) in edited {
3230 if !edit_lanes.contains(&l) {
3231 edit_lanes.push(l);
3232 }
3233 }
3234 if let Some(v) = lane_list(op, "lanes")? {
3235 let all = s.lanes();
3236 if let Some(&l) = v.iter().find(|l| !all.contains(l)) {
3237 return Err(format!("lane {} is not on this timeline", parse::lane_name(l)));
3238 }
3239 if let Some(&l) = edit_lanes.iter().find(|l| !v.contains(l)) {
3240 return Err(format!("`lanes` must include {}, the lane being edited", parse::lane_name(l)));
3241 }
3242 return Ok(Scope { lanes: v, skipped: Vec::new(), explicit: true });
3243 }
3244 let mut lanes = edit_lanes.clone();
3245 for &(l, i) in edited {
3246 for (m, _) in take_of(s, l, i) {
3247 if !lanes.contains(&m) {
3248 lanes.push(m);
3249 }
3250 }
3251 }
3252 loop {
3253 let before = lanes.len();
3254 for l in ripple_lanes(s, &lanes, from) {
3255 if !lanes.contains(&l) {
3256 lanes.push(l);
3257 }
3258 }
3259 if lanes.len() == before {
3260 break;
3261 }
3262 }
3263 let mut skipped = Vec::new();
3264 if has_picture(&edit_lanes) {
3265 for l in s.lanes() {
3266 if l.kind != LaneKind::Subtitle || lanes.contains(&l) {
3267 continue;
3268 }
3269 if s.lane_locked(l) {
3270 skipped.push(l);
3271 } else {
3272 lanes.push(l);
3273 }
3274 }
3275 }
3276 Ok(Scope { lanes, skipped, explicit: false })
3277}
3278
3279/// The clips a ripple cut over `[from, to)` would remove that the edit did not name: a clip on a
3280/// scope lane outside the take of the edited clips that overlaps the span. A ripple reaches such a
3281/// lane only through a later take's link, and the cut takes the unrelated clip with it, so the
3282/// picture under a deleted sound (or the reverse) would be lost. Returned as (lane, start).
3283fn unrelated_in_cut(s: &PlaybackSession, scope: &[Lane], edited: &[(Lane, usize)], from: u32, to: u32) -> Vec<(Lane, u32)> {
3284 let mut own: Vec<Lane> = Vec::new();
3285 for &(l, i) in edited {
3286 for (m, _) in take_of(s, l, i) {
3287 if !own.contains(&m) {
3288 own.push(m);
3289 }
3290 }
3291 }
3292 let mut out = Vec::new();
3293 for &l in scope {
3294 if l.kind == LaneKind::Subtitle || own.contains(&l) {
3295 continue;
3296 }
3297 out.extend(s.lane_clips(l).iter().filter(|c| c.start < to && c.end() > from).map(|c| (l, c.start)));
3298 }
3299 out
3300}
3301
3302/// The refusal for a ripple whose cut would remove `hit` (from `unrelated_in_cut`). `head` is the
3303/// op as the reply names it, `addr` the clip the edit is about, and `first_way` the way out that
3304/// leaves the gap. The second way out lifts the clips in the way and closes the gaps they leave.
3305fn unrelated_refusal(head: &str, addr: &str, hit: &[(Lane, u32)], first_way: &str) -> String {
3306 let names: Vec<String> = hit.iter().map(|&(l, st)| parse::addr(l, st)).collect();
3307 let mut lanes: Vec<String> = Vec::new();
3308 for &(l, _) in hit {
3309 let n = parse::lane_name(l);
3310 if !lanes.contains(&n) {
3311 lanes.push(n);
3312 }
3313 }
3314 let closes: Vec<String> = lanes.iter().map(|n| format!("close_gaps {{lane:\"{n}\"}}")).collect();
3315 format!(
3316 "{head} refused: the ripple would close over {}, which is not part of {addr}'s take, and remove it; {first_way}, or lift {} too and {}",
3317 names.join(", "),
3318 names.join(", "),
3319 closes.join(" and ")
3320 )
3321}
3322
3323/// The refusal for an insert whose cut at `at` would split a take: a clip on `scope` that `at` falls
3324/// inside has a take partner on a lane outside `scope`. The cut would split that partner too, and
3325/// the ripple would leave its half behind, so the op refuses and names the partner and the lanes to
3326/// add to `lanes`, as remove_time and cut_regions refuse it. A locked partner is left to the lock check.
3327fn split_take_refusal(s: &PlaybackSession, scope: &[Lane], at: u32, shown: &str) -> Option<String> {
3328 for &l in scope.iter().filter(|l| l.kind != LaneKind::Subtitle) {
3329 for (i, c) in s.lane_clips(l).iter().enumerate() {
3330 if !(c.start < at && at < c.end()) {
3331 continue;
3332 }
3333 let Some(&(pl, pi)) = take_of(s, l, i).iter().skip(1).find(|(m, _)| !scope.contains(m) && !s.lane_locked(*m)) else {
3334 continue;
3335 };
3336 let mut with: Vec<String> = scope.iter().map(|&x| format!("\"{}\"", parse::lane_name(x))).collect();
3337 with.push(format!("\"{}\"", parse::lane_name(pl)));
3338 return Some(format!(
3339 "insert_time {shown} refused: the {} clip at {} is one take with the {} clip at {}, and {} is not in lanes; cutting at {} would pull the take apart. Add {} to lanes (lanes:[{}]), or drop lanes to move the whole take",
3340 parse::lane_name(l),
3341 parse::addr(l, c.start),
3342 parse::lane_name(pl),
3343 parse::addr(pl, s.lane_clips(pl)[pi].start),
3344 parse::lane_name(pl),
3345 parse::tc(at, parse::session_fps(s)),
3346 parse::lane_name(pl),
3347 with.join(",")
3348 ));
3349 }
3350 }
3351 None
3352}
3353
3354/// `insert_time {at, duration, lanes?}`: ripples empty time in at `at`, on the lanes
3355/// `lanes` names, else every unlocked lane. See `insert_span`.
3356fn op_insert_time(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Done, String> {
3357 let at = need(op, "at", fps, end)?;
3358 let dur = need(op, "duration", fps, u32::MAX)?;
3359 if dur == 0 {
3360 return Err("insert_time: duration must be more than 0".into());
3361 }
3362 // At or past the timeline end nothing lies after the cut, so nothing can move: say so, and say what lengthens it.
3363 if at >= end {
3364 let shown = shown_time(op.get("at"), at);
3365 // An empty timeline has no clip to hold a lead-in: the gap before a first clip exists only once a clip is placed after it.
3366 if end == 0 {
3367 let secs = format!("{:.3}s", f64::from(dur) / fps);
3368 return Ok(plain(
3369 format!(
3370 "insert_time at {shown}: the timeline is empty, so no clip moved and nothing changed; a {secs} lead-in appears once a clip is placed after it, e.g. place {{source, lane:\"V1\", at:\"{secs}\"}}"
3371 ),
3372 Vec::new(),
3373 ));
3374 }
3375 return Ok(plain(
3376 format!(
3377 "insert_time at {shown}: nothing after the end to push; to lengthen the timeline add a clip with append {{source}} or place {{source, at:\"end\"}}, or a title past the end with title_add {{at, duration}}"
3378 ),
3379 Vec::new(),
3380 ));
3381 }
3382 let scope = default_scope(s, op)?;
3383 let shown = (shown_time(op.get("at"), at), shown_time(op.get("duration"), dur));
3384 let drift = caption_drift(s, op, &scope.lanes, at);
3385 let cut = cut_point(s, &cut_lanes(s, &scope.lanes, at), at);
3386 if let Some(msg) = split_take_refusal(s, &scope.lanes, cut, &shown.0) {
3387 return Err(msg);
3388 }
3389 let mut done = insert_span(s, cut, dur, &scope, fps, shown)?;
3390 if cut != at {
3391 done.text.push_str(&cut_moved_note(at, cut));
3392 }
3393 done.text.push_str(&drift);
3394 Ok(done)
3395}
3396
3397/// The lanes a cut at `at` on `scope` makes: the scope, and the take partners of each clip the cut
3398/// runs through (a take is cut whole).
3399fn cut_lanes(s: &PlaybackSession, scope: &[Lane], at: u32) -> Vec<Lane> {
3400 let mut out: Vec<Lane> = scope.to_vec();
3401 for &l in scope.iter().filter(|l| l.kind != LaneKind::Subtitle) {
3402 for (i, c) in s.lane_clips(l).iter().enumerate() {
3403 if c.start < at && at < c.end() {
3404 for (m, _) in take_of(s, l, i) {
3405 if !out.contains(&m) {
3406 out.push(m);
3407 }
3408 }
3409 }
3410 }
3411 }
3412 out
3413}
3414
3415/// Whether a cut at frame `f` can be made on `lanes`: a slow clip plays each source frame over
3416/// several timeline frames, and the engine cuts it only where a source frame begins
3417/// ([`engine::Speed::split_at`]). At 0.5x only every second timeline frame is a cut point.
3418fn cuttable(s: &PlaybackSession, lanes: &[Lane], f: u32) -> bool {
3419 lanes.iter().filter(|l| l.kind != LaneKind::Subtitle).all(|&l| {
3420 s.lane_clips(l)
3421 .iter()
3422 .filter(|c| c.start < f && f < c.end())
3423 .all(|c| c.speed.split_at(c.len(), f - c.start).is_some())
3424 })
3425}
3426
3427/// The frame a cut at `at` lands on across `lanes`: `at` itself when [`cuttable`], else the
3428/// nearest frame within 8 that is (the earlier one first on a tie), else `at`.
3429fn cut_point(s: &PlaybackSession, lanes: &[Lane], at: u32) -> u32 {
3430 if cuttable(s, lanes, at) {
3431 return at;
3432 }
3433 (1..=8u32)
3434 .flat_map(|d| [at.checked_sub(d), at.checked_add(d)])
3435 .flatten()
3436 .find(|&f| f > 0 && cuttable(s, lanes, f))
3437 .unwrap_or(at)
3438}
3439
3440/// The start a span `at`..`at+dur` is cut from on `lanes`: `at` when both of its edges can be cut
3441/// there, else the nearest start within 8 frames whose two edges can (same length, so the amount
3442/// removed is the amount asked). `at` when no start does, and the sliver closing then owns it.
3443fn span_start(s: &PlaybackSession, lanes: &[Lane], at: u32, dur: u32) -> u32 {
3444 let both = |f: u32| cuttable(s, lanes, f) && cuttable(s, lanes, f + dur);
3445 if both(at) {
3446 return at;
3447 }
3448 (1..=8u32)
3449 .flat_map(|d| [at.checked_sub(d), at.checked_add(d)])
3450 .flatten()
3451 .find(|&f| f > 0 && both(f))
3452 .unwrap_or(at)
3453}
3454
3455/// The reply's words for a cut that [`cut_point`] moved off the frame asked for.
3456fn cut_moved_note(asked: u32, cut: u32) -> String {
3457 format!("; the cut moved from {asked}f to {cut}f: a slow clip plays each source frame over several timeline frames, and {asked}f is between two showings of one")
3458}
3459
3460/// The warning a ripple with explicit `lanes` owes when it leaves a caption lane out: the
3461/// captions on that lane at or after `at` stay put while the lanes they belong to move.
3462/// Empty unless `lanes` was given. Read before the edit, so the counts are the cues that
3463/// would have followed.
3464pub(crate) fn caption_drift(s: &PlaybackSession, op: &Value, lanes: &[Lane], at: u32) -> String {
3465 if !matches!(op.get("lanes"), Some(v) if !v.is_null()) {
3466 return String::new();
3467 }
3468 let anchor = lanes
3469 .iter()
3470 .find(|l| l.kind != LaneKind::Subtitle)
3471 .map_or_else(|| "the cut lanes".to_string(), |l| parse::lane_name(*l));
3472 let mut out = String::new();
3473 for l in s.subtitle_lanes() {
3474 if lanes.contains(&l) {
3475 continue;
3476 }
3477 // Cues, not placements: a placed track is one placement over many cues.
3478 let fps = parse::session_fps(s);
3479 let n = s
3480 .sub_lane_cues(l)
3481 .iter()
3482 .filter(|c| (c.start_us as f64 * fps / 1e6).round() as u32 >= at)
3483 .count();
3484 if n > 0 {
3485 let name = parse::lane_name(l);
3486 let word = if n == 1 { "cue" } else { "cues" };
3487 out.push_str(&format!("; {name} not in lanes: {n} {word} now out of sync with {anchor} (add {name} to lanes)"));
3488 }
3489 }
3490 out
3491}
3492
3493/// Ripples `dur` frames of empty time in at `at` on the lanes of `scope`. A clip or
3494/// caption on those lanes that `at` falls inside is cut there first, with the partners
3495/// of what is cut (only those lanes are cut, so the others keep their clips whole);
3496/// then every scope item starting at or after `at` moves `dur` later, as one engine
3497/// move (a take's partners come with it), and titles starting at or after `at` move
3498/// too when the scope holds the picture.
3499fn insert_span(s: &mut PlaybackSession, at: u32, dur: u32, scope: &Scope, fps: f64, shown: (String, String)) -> Result<Done, String> {
3500 let scope_lanes = scope.lanes.clone();
3501 // The lanes that move: the scope closed over link partners. A locked one refuses, before any cut.
3502 let (closure, guard_skipped) = ripple_guard(s, &scope_lanes, at, &[at], !scope.explicit)?;
3503 let mut cut_on: Vec<Lane> = Vec::new();
3504 for &l in &scope_lanes {
3505 if straddlers(s, at).contains(&l) {
3506 if !cut_on.contains(&l) {
3507 cut_on.push(l);
3508 }
3509 let idxs: Vec<usize> = if l.kind == LaneKind::Subtitle {
3510 Vec::new()
3511 } else {
3512 s.lane_clips(l).iter().enumerate().filter(|(_, c)| c.start < at && at < c.end()).map(|(i, _)| i).collect()
3513 };
3514 for i in idxs {
3515 for (m, _) in take_of(s, l, i) {
3516 if !cut_on.contains(&m) {
3517 cut_on.push(m);
3518 }
3519 }
3520 }
3521 }
3522 }
3523 // Every media clip the cut splits, per lane, read before the cut: the reply names them and the gap they leave.
3524 let mut split_lanes: Vec<(Lane, Vec<String>)> = Vec::new();
3525 for &l in cut_on.iter().filter(|l| l.kind != LaneKind::Subtitle) {
3526 let names: Vec<String> = s
3527 .lane_clips(l)
3528 .iter()
3529 .filter(|c| c.start < at && at < c.end())
3530 .map(|c| parse::addr(l, c.start))
3531 .collect();
3532 if !names.is_empty() {
3533 split_lanes.push((l, names));
3534 }
3535 }
3536 if !cut_on.is_empty() {
3537 check_unlocked(s, &cut_on)?;
3538 s.cut_at_lanes(parse::secs(at, fps), &cut_on);
3539 if scope_lanes.iter().any(|l| straddlers(s, at).contains(l)) {
3540 return Err(format!("insert_time: could not cut at {} to make room", parse::tc(at, fps)));
3541 }
3542 }
3543 check_unlocked(s, &scope_lanes)?;
3544
3545 let mut media: Vec<(Lane, usize)> = Vec::new();
3546 let mut subs: Vec<(Lane, usize)> = Vec::new();
3547 for &l in &scope_lanes {
3548 if l.kind == LaneKind::Subtitle {
3549 subs.extend(s.sub_lane(l).iter().enumerate().filter(|(_, c)| c.start >= at).map(|(i, _)| (l, i)));
3550 } else {
3551 media.extend(s.lane_clips(l).iter().enumerate().filter(|(_, c)| c.start >= at).map(|(i, _)| (l, i)));
3552 }
3553 }
3554 let mut touched: Vec<(Lane, u32)> = media.iter().map(|&(l, i)| (l, s.lane_clips(l)[i].start + dur)).collect();
3555 touched.extend(subs.iter().map(|&(l, i)| (l, s.sub_lane(l)[i].start + dur)));
3556
3557 match media.first().copied() {
3558 Some((dl, di)) => {
3559 let picks: Vec<(Lane, usize)> = media.iter().chain(subs.iter()).copied().collect();
3560 let start = s.lane_clips(dl)[di].start + dur;
3561 if !s.move_selection_to(&picks, dl, di, dl, start) {
3562 return Err(format!(
3563 "insert_time {} refused: the items after it cannot all move {} later",
3564 shown.0, shown.1
3565 ));
3566 }
3567 }
3568 None => {
3569 // Captions alone: the last of each lane moves first, so each index stays valid.
3570 for &(l, i) in subs.iter().rev() {
3571 let start = s.sub_lane(l)[i].start + dur;
3572 s.move_sub(l, i, l, start).map_err(|e| format!("insert_time: {e}"))?;
3573 }
3574 }
3575 }
3576
3577 let tail: Vec<usize> = if has_picture(&scope_lanes) {
3578 s.titles().iter().enumerate().filter(|(_, t)| t.start >= at).map(|(i, _)| i).collect()
3579 } else {
3580 Vec::new()
3581 };
3582 for &i in tail.iter().rev() {
3583 let mut t = s.titles()[i].clone();
3584 t.start += dur;
3585 if !s.set_title(i, t) {
3586 return Err(format!("insert_time: title T{} would not move", i + 1));
3587 }
3588 }
3589 // Chapters at or after `at` move with the titles, by the same `dur`: a shift of everything past a
3590 // point keeps them one to a frame.
3591 if has_picture(&scope_lanes) {
3592 s.remap_chapters(|f| if f >= at { f + dur } else { f });
3593 s.remap_markers(|f| if f >= at { f + dur } else { f });
3594 }
3595 Ok(plain(
3596 format!(
3597 "insert_time {} for {}: {} clip(s), {} caption(s), {} title(s) moved{}{}{}",
3598 shown.0,
3599 shown.1,
3600 media.len(),
3601 subs.len(),
3602 tail.len(),
3603 split_note(&split_lanes, at, dur, fps),
3604 skipped_note(&[scope.skipped.clone(), guard_skipped].concat()),
3605 left_behind(s, &closure, at)
3606 ),
3607 touched,
3608 ))
3609}
3610
3611/// `freeze {at, duration, lane?="V1", insert?=true}`: holds the picture at `at`.
3612/// The composed frame at `at` is saved as `<project>/freeze/<stem>-<frame>-<hash8>.png`,
3613/// the hash taken from its pixels (an identical frame reuses the file and its source),
3614/// imported as a still and placed at `duration`
3615/// on `lane`. `insert` ripples first, as `insert_time` does, so audio gets silence
3616/// and everything after moves `duration` later. Without `insert` the still
3617/// overwrites `lane`; with no `lane` it goes on a new top video lane over the picture.
3618/// The still is registered as a source: a failed batch or a no-op batch takes that source back (the
3619/// engine keeps sources out of undo, so an undo alone leaves it), and a dry run imports nothing.
3620/// FNV-1a over the frame's size and BGRA bytes, folded to 32 bits: the `<hash8>`
3621/// in a freeze file's name. Std has no stable hasher and this crate has no hash
3622/// dependency; the names only need to differ when the pixels do.
3623fn frame_hash(frame: &engine::decode::Frame) -> u32 {
3624 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
3625 for b in frame.width.to_le_bytes().into_iter().chain(frame.height.to_le_bytes()).chain(frame.bgra.iter().copied()) {
3626 h ^= u64::from(b);
3627 h = h.wrapping_mul(0x0000_0100_0000_01b3);
3628 }
3629 (h >> 32) as u32 ^ h as u32
3630}
3631
3632fn op_freeze(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32, project: Option<&Path>, dry: bool) -> Result<Done, String> {
3633 let at = need(op, "at", fps, end)?;
3634 let dur = need(op, "duration", fps, u32::MAX)?;
3635 if dur == 0 {
3636 return Err("freeze: duration must be more than 0".into());
3637 }
3638 let insert = match op.get("insert") {
3639 None | Some(Value::Null) => true,
3640 Some(Value::Bool(b)) => *b,
3641 Some(_) => return Err("freeze: `insert` must be true or false".into()),
3642 };
3643 let named = lane_arg(op, "lane")?;
3644 let mut lane = named.unwrap_or(Lane::V1);
3645 if lane.kind != LaneKind::Video {
3646 return Err(format!("freeze holds a picture: `lane` must be a video lane (V1..), not {}", parse::lane_name(lane)));
3647 }
3648 let project = project.ok_or("freeze needs a saved project to keep its still in: call project_save {path:\"/abs/file.edith\"} first")?;
3649 if at >= end {
3650 return Err(format!(
3651 "freeze at {} is past the end of the timeline ({}); pick a time before it",
3652 parse::tc(at, fps),
3653 parse::tc(end, fps)
3654 ));
3655 }
3656 let stem = project.file_stem().map_or_else(|| "untitled".to_string(), |f| f.to_string_lossy().into_owned());
3657 let dir = project.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new(".")).join("freeze");
3658 // Composed on every call (~100ms): the pixels decide the name, so a changed
3659 // timeline or grade can never be served a picture taken before it.
3660 let (proj, meta) = s.export_snapshot();
3661 let frame = engine::export::compose_at(&proj, &meta, at, meta.width, meta.height)
3662 .map_err(|e| format!("freeze: cannot compose frame {at}: {e}"))?;
3663 let file = format!("{stem}-{at}-{:08x}.png", frame_hash(&frame));
3664 let png = dir.join(&file);
3665 // A dry run writes no PNG and imports no source: a source outlives the rollback that a dry run
3666 // ends with, and the engine keeps sources out of undo, so it would stay in the project.
3667 let n = if dry {
3668 None
3669 } else {
3670 if !png.is_file() {
3671 let bytes = engine::decode::to_png_bytes(&frame)
3672 .map_err(|e| format!("freeze: cannot encode frame {at} as PNG: {e}"))?;
3673 // What this batch creates is noted, so a refused batch takes it back; a file that was there is never noted.
3674 if !dir.is_dir() {
3675 note_write(dir.clone());
3676 }
3677 std::fs::create_dir_all(&dir).map_err(|e| format!("freeze: cannot create {}: {e}", dir.display()))?;
3678 std::fs::write(&png, bytes).map_err(|e| format!("freeze: cannot write {}: {e}", png.display()))?;
3679 note_write(png.clone());
3680 }
3681 // The same pixels already imported as a source: place that one, no duplicate.
3682 let n = match s.sources().iter().position(|src| src.path == png) {
3683 Some(i) => i,
3684 None => s.import(&png).map_err(|e| format!("freeze: cannot import {}: {e}", png.display()))?,
3685 };
3686 if dur > s.file_frames(&png) {
3687 return Err(format!("freeze: {} is longer than a still can be held", parse::tc(dur, fps)));
3688 }
3689 Some(n)
3690 };
3691 // Named when a new lane was added for the still, so the reply says why a lane the caller did not name exists.
3692 let mut added_note = String::new();
3693 if named.is_none() && !insert {
3694 // Over the picture on a new top video lane: nothing underneath is touched.
3695 edit_fx::apply(s, &json!({ "op": "lane_add", "kind": "video" }), fps)
3696 .ok_or("freeze: lane_add is not available")?
3697 .map_err(|e| format!("freeze: {e}"))?;
3698 lane = s
3699 .lanes()
3700 .into_iter()
3701 .filter(|l| l.kind == LaneKind::Video)
3702 .max_by_key(|l| l.ord)
3703 .ok_or("freeze: no video lane after lane_add")?;
3704 added_note = format!(
3705 "; added lane {} for the still, since insert:false with no lane leaves the picture under it untouched",
3706 parse::lane_name(lane)
3707 );
3708 }
3709 check_unlocked(s, &[lane])?;
3710 // The still goes where the insert cuts nothing: at `at`, or at the clip's end when `at` is its last frame.
3711 // A slow clip the still's cut runs through can be cut only at some frames: the still follows the cut.
3712 let start = freeze_start(s, at);
3713 let pos = if insert { cut_point(s, &cut_lanes(s, &s.lanes(), start), start) } else { at };
3714 let mut touched = Vec::new();
3715 // An insert cuts any clip `pos` falls strictly inside, then leaves silence where the still
3716 // went. On an audio lane that is a hole in the sound, so name the clip it splits.
3717 let mut warning = String::new();
3718 if insert {
3719 for l in straddlers(s, pos).into_iter().filter(|l| l.kind == LaneKind::Audio) {
3720 if let Some(c) = s.lane_clips(l).iter().find(|c| c.start < pos && pos < c.end()) {
3721 warning = format!(
3722 "\n warning: the insert cut audio clip {} in two at {}, so its sound has a silent hole there; insert:false keeps the sound whole",
3723 parse::addr(l, c.start),
3724 parse::tc(pos, fps)
3725 );
3726 }
3727 }
3728 let pre = op_insert_time(
3729 s,
3730 &json!({ "at": format!("{pos}f"), "duration": format!("{dur}f") }),
3731 fps,
3732 end,
3733 )?;
3734 touched = pre.touched;
3735 }
3736 let held = if pos == at {
3737 String::new()
3738 } else if pos != start {
3739 cut_moved_note(start, pos)
3740 } else {
3741 format!(", holding frame {at}f: the clip ends at {pos}f, so nothing is cut")
3742 };
3743 let Some(n) = n else {
3744 // A dry run: the still is not placed, and the reply says so; the insert above is still reported.
3745 touched.push((lane, pos));
3746 return Ok(plain(
3747 format!(
3748 "freeze {:.3}s for {:.3}s on {} (dry run: the still is neither written nor placed){held}{added_note}{warning}",
3749 parse::secs(pos, fps),
3750 parse::secs(dur, fps),
3751 parse::lane_name(lane)
3752 ),
3753 touched,
3754 ));
3755 };
3756 if !s.place_at(lane, parse::secs(pos, fps), clip_of(n, 0, dur)) {
3757 return Err(format!(
3758 "freeze: {} at {} refused: the engine would not place the still there",
3759 parse::lane_name(lane),
3760 parse::tc(pos, fps)
3761 ));
3762 }
3763 touched.push((lane, pos));
3764 let text = format!(
3765 "freeze {:.3}s for {:.3}s on {} (src:{n} freeze/{file}){held}{added_note}{warning}",
3766 parse::secs(pos, fps),
3767 parse::secs(dur, fps),
3768 parse::lane_name(lane)
3769 );
3770 Ok(plain(text, touched))
3771}
3772
3773/// Where an insert-freeze at `at` goes. An insert cuts each clip `at` falls inside; when `at`
3774/// is the last frame of every such clip, the cut would leave that frame alone after the still,
3775/// so the still goes at the clip's end instead and nothing is cut.
3776fn freeze_start(s: &PlaybackSession, at: u32) -> u32 {
3777 let ends: Vec<u32> = media_lanes(s)
3778 .into_iter()
3779 .flat_map(|l| s.lane_clips(l).iter().filter(|c| c.start < at && at < c.end()).map(|c| c.end()).collect::<Vec<_>>())
3780 .collect();
3781 if !ends.is_empty() && ends.iter().all(|&e| e == at + 1) {
3782 at + 1
3783 } else {
3784 at
3785 }
3786}
3787
3788/// `remove_time {at, duration, lanes?}`: the `cut_regions` cut for one span, on the
3789/// scope lanes. Titles after the span move back by `duration`; a title that starts
3790/// inside it refuses the cut, since the cut would take it away.
3791fn op_remove_time(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Done, String> {
3792 let at = need(op, "at", fps, end)?;
3793 let dur = need(op, "duration", fps, u32::MAX)?;
3794 if dur == 0 {
3795 return Err("remove_time: duration must be more than 0".into());
3796 }
3797 if at >= parse::session_end(s) {
3798 return Ok(plain(
3799 format!("remove_time {} is past the timeline end: nothing to cut", shown_time(op.get("at"), at)),
3800 Vec::new(),
3801 ));
3802 }
3803 // The span starts where its edges can both be cut (a slow clip cannot be cut between two showings
3804 // of one source frame); the length does not change.
3805 let asked = at;
3806 let snap_lanes = ripple_scope(s, op)?;
3807 let at = span_start(s, &cut_lanes(s, &snap_lanes, asked), asked, dur);
3808 let to = at.saturating_add(dur);
3809 let (scope, guard_skipped) = if lane_list(op, "lanes")?.is_some() {
3810 let v = ripple_scope(s, op)?;
3811 check_unlocked(s, &v)?;
3812 (v, Vec::new())
3813 } else {
3814 ripple_guard(s, &ripple_scope(s, op)?, at, &[at, to], true)?
3815 };
3816 let drift = caption_drift(s, op, &scope, at);
3817 let picture = has_picture(&scope);
3818 // Titles follow the picture: one wholly inside the span goes with it, one that straddles an
3819 // edge is trimmed to what lies outside the span, and titles after it move back by `dur`.
3820 // (text, start as read, what it becomes: None removes it)
3821 let mut plan: Vec<(String, u32, Option<engine::project::Title>)> = Vec::new();
3822 let mut removed: Vec<String> = Vec::new();
3823 let mut trimmed: Vec<String> = Vec::new();
3824 let mut moved_back = 0;
3825 for (i, t) in s.titles().iter().enumerate().filter(|_| picture) {
3826 let (ts, te) = (t.start, t.start.saturating_add(t.frames));
3827 if te <= at {
3828 continue;
3829 }
3830 if ts >= to {
3831 let mut t2 = t.clone();
3832 t2.start -= dur;
3833 plan.push((t.text.clone(), ts, Some(t2)));
3834 moved_back += 1;
3835 continue;
3836 }
3837 // Overlaps the span: what is left is the part outside it, which closes up at `at`.
3838 let overlap = te.min(to) - ts.max(at);
3839 let kept = t.frames - overlap;
3840 if kept == 0 {
3841 removed.push(format!("T{} ({})", i + 1, secs_text(t.frames, fps)));
3842 plan.push((t.text.clone(), ts, None));
3843 } else {
3844 let mut t2 = t.clone();
3845 t2.start = ts.min(at);
3846 t2.frames = kept;
3847 trimmed.push(format!("T{} now {}–{}", i + 1, secs_text(t2.start, fps), secs_text(t2.start + kept, fps)));
3848 plan.push((t.text.clone(), ts, Some(t2)));
3849 }
3850 }
3851 // Clips on the scope lanes: one wholly inside the span is removed, one the span crosses is trimmed
3852 // to the part outside. Both are named before the cut, by the address the caller read.
3853 let mut clips_gone: Vec<String> = Vec::new();
3854 let mut clips_cut: Vec<String> = Vec::new();
3855 let mut clips_split: Vec<String> = Vec::new();
3856 for &l in scope.iter().filter(|l| l.kind != LaneKind::Subtitle) {
3857 for c in s.lane_clips(l) {
3858 let (cs, ce) = (c.start, c.end());
3859 if ce <= at || cs >= to {
3860 continue;
3861 }
3862 let who = format!("{} ({})", parse::addr(l, cs), source_name(s, c.source));
3863 if cs >= at && ce <= to {
3864 clips_gone.push(who);
3865 } else if cs < at && ce > to {
3866 // The span lies inside the clip: two pieces are left, the second one starting where the span was.
3867 let second = at + (ce - to);
3868 clips_split.push(format!(
3869 "split {}: {} {}–{}, {} {}–{}",
3870 parse::addr(l, cs),
3871 parse::addr(l, cs),
3872 secs_text(cs, fps),
3873 secs_text(at, fps),
3874 parse::addr(l, at),
3875 secs_text(at, fps),
3876 secs_text(second, fps)
3877 ));
3878 } else {
3879 let kept = c.frames() - (ce.min(to) - cs.max(at));
3880 let new_start = cs.min(at);
3881 clips_cut.push(format!("{who} now {}–{}", secs_text(new_start, fps), secs_text(new_start + kept, fps)));
3882 }
3883 }
3884 }
3885 let (cues_gone, cues_cut) = cues_in_span(s, &scope, at, to, fps);
3886 let sound = sound_drift(s, &scope, to, &format!("−{:.3}s", parse::secs(dur, fps)));
3887 s.cut_regions(&[(at, dur)], &scope).map_err(|e| e.to_string())?;
3888 let cues_cut = trimmed_cue_lines(s, &cues_cut);
3889 for (text, from, to_title) in plan {
3890 retitle(s, &text, from, to_title).map_err(|e| format!("remove_time: {e}"))?;
3891 }
3892 // Chapters follow the span as the titles do: one inside it lands at its start.
3893 if picture {
3894 s.remap_chapters(|f| title_shift(&[(at, dur)], f));
3895 s.remap_markers(|f| title_shift(&[(at, dur)], f));
3896 }
3897 // A split of a speed-changed clip rounds its piece to whole timeline frames, so the cut can leave
3898 // a frame or two between the piece and the clip after it: close those as the cut_regions op does.
3899 let mut sliver_moved: Vec<String> = Vec::new();
3900 let sliver = sliver_note(close_sliver_holes(s, &scope, fps, &mut sliver_moved));
3901 let mut titles_text = String::new();
3902 if !clips_gone.is_empty() {
3903 titles_text.push_str(&format!("; removed {}", clips_gone.join(", ")));
3904 }
3905 for split in &clips_split {
3906 titles_text.push_str(&format!("; {split}"));
3907 }
3908 if !clips_cut.is_empty() {
3909 titles_text.push_str(&format!("; trimmed {}", clips_cut.join(", ")));
3910 }
3911 if moved_back > 0 {
3912 titles_text.push_str(&format!("; {moved_back} title(s) moved back"));
3913 }
3914 if !trimmed.is_empty() {
3915 titles_text.push_str(&format!("; trimmed to the span's edge: {}", trimmed.join(", ")));
3916 }
3917 if !removed.is_empty() {
3918 titles_text.push_str(&format!("; removed with the span: {}", removed.join(", ")));
3919 }
3920 titles_text.push_str(&cue_cut_text(&cues_gone, &cues_cut));
3921 titles_text.push_str(&titles_note(&sliver_moved));
3922 let moved = if at != asked { cut_moved_note(asked, at) } else { String::new() };
3923 Ok(plain(
3924 format!(
3925 "remove_time {} for {}{titles_text}{drift}{}{}{sound}{sliver}{moved}",
3926 if at != asked { shown_time(Some(&json!(format!("{at}f"))), at) } else { shown_time(op.get("at"), at) },
3927 shown_time(op.get("duration"), dur),
3928 left_behind(s, &scope, at),
3929 skipped_note(&guard_skipped)
3930 ),
3931 ripple_touched(s, &scope, at),
3932 ))
3933}
3934
3935/// A caption cue a cut trims, read before the cut: where its track time and its timeline span
3936/// sit, so `trimmed_cue_lines` can find the pieces the cut leaves.
3937struct CueCut {
3938 lane: Lane,
3939 track: usize,
3940 index: usize,
3941 words: String,
3942 track_start: i64,
3943 track_end: i64,
3944 old_start: i64,
3945 old_end: i64,
3946 new_start: i64,
3947 new_end: i64,
3948}
3949
3950/// The caption cues a cut of `at..at+dur` on `lanes` would take: `(removed, trimmed)`. A cue is
3951/// removed only when every part of it on those lanes lies inside the span; a cue with any part
3952/// left outside (a placement cut in two counts as one cue) is trimmed. Removed cues name their
3953/// whole text and old times; trimmed cues are named after the cut, by `trimmed_cue_lines`. Read
3954/// before the cut. A cue's timeline place follows the placement that shows it, the way the engine
3955/// lays cues out (see `op_cue_add`).
3956fn cues_in_span(s: &PlaybackSession, lanes: &[Lane], at: u32, dur_end: u32, fps: f64) -> (Vec<String>, Vec<CueCut>) {
3957 let us = |f: u32| (f64::from(f) * 1e6 / fps).round() as i64;
3958 let (a, b) = (us(at), us(dur_end));
3959 // Where a timeline point lands once the span is cut out: before it stays, after it moves back, inside it is at its edge.
3960 let after_cut = |p: i64| -> i64 {
3961 if p <= a {
3962 p
3963 } else if p >= b {
3964 p - (b - a)
3965 } else {
3966 a
3967 }
3968 };
3969 // Per cue: its visible extent over every placement on these lanes, and whether any of it
3970 // lies outside the span or overlaps it. Keyed by (track, cue) so the reply lists them in order.
3971 struct Extent {
3972 lane: Lane,
3973 start: i64,
3974 end: i64,
3975 inside: bool,
3976 overlaps: bool,
3977 }
3978 let mut extents: std::collections::BTreeMap<(usize, usize), Extent> = std::collections::BTreeMap::new();
3979 for &l in lanes.iter().filter(|l| l.kind == LaneKind::Subtitle) {
3980 for c in s.sub_lane(l) {
3981 let Some(track) = s.subtitles().get(c.track) else { continue };
3982 let p0 = us(c.start);
3983 let window = (c.out_us - c.in_us).max(1) as f64;
3984 let rate = f64::from(c.frames) / fps * 1e6 / window;
3985 for (ci, cue) in track.cues.iter().enumerate() {
3986 // The part of the cue the placement shows: a cue reaching past its window's edge
3987 // is clamped to it, so the reply never names a time before the placement starts.
3988 let (a0, b0) = (cue.start_us.max(c.in_us), cue.end_us.min(c.out_us));
3989 if b0 <= a0 {
3990 continue;
3991 }
3992 let ts = p0 + ((a0 - c.in_us) as f64 * rate).round() as i64;
3993 let te = p0 + ((b0 - c.in_us) as f64 * rate).round() as i64;
3994 let inside = ts >= a && te <= b;
3995 let overlaps = te > a && ts < b;
3996 let e = extents.entry((c.track, ci)).or_insert(Extent { lane: l, start: ts, end: te, inside: true, overlaps: false });
3997 e.start = e.start.min(ts);
3998 e.end = e.end.max(te);
3999 e.inside &= inside;
4000 e.overlaps |= overlaps;
4001 }
4002 }
4003 }
4004 let (mut gone, mut cut) = (Vec::new(), Vec::new());
4005 for ((track, ci), e) in extents.iter().filter(|(_, e)| e.overlaps) {
4006 let Some(cue) = s.subtitles().get(*track).and_then(|t| t.cues.get(*ci)) else { continue };
4007 let words = cue.text.replace('\n', " / ");
4008 let secs = |us: i64| format!("{:.3}s", us as f64 / 1e6);
4009 if e.inside {
4010 gone.push(format!("\"{words}\" ({}–{})", secs(e.start), secs(e.end)));
4011 } else {
4012 cut.push(CueCut {
4013 lane: e.lane,
4014 track: *track,
4015 index: *ci,
4016 words,
4017 track_start: cue.start_us,
4018 track_end: cue.end_us,
4019 old_start: e.start,
4020 old_end: e.end,
4021 new_start: after_cut(e.start),
4022 new_end: after_cut(e.end),
4023 });
4024 }
4025 }
4026 (gone, cut)
4027}
4028
4029/// The caption lines a cut owes: the cues it removed and the cues it trimmed, each as its own `; ...` clause.
4030fn cue_cut_text(gone: &[String], cut: &[String]) -> String {
4031 let mut text = String::new();
4032 if !gone.is_empty() {
4033 text.push_str(&format!("; caption cue(s) removed: {}", gone.join(", ")));
4034 }
4035 if !cut.is_empty() {
4036 text.push_str(&format!("; caption cue(s) trimmed: {}", cut.join("; ")));
4037 }
4038 text
4039}
4040
4041/// The trimmed cues of a cut, read after it: each as `S1 cue 89 'old words' → 'kept words' (was
4042/// old times, now new times)`. The kept words are the pieces the cut left of that cue: the track's cues inside its
4043/// track time that still sit under a placement's window (a piece the cut took out is none).
4044fn trimmed_cue_lines(s: &PlaybackSession, cut: &[CueCut]) -> Vec<String> {
4045 let secs = |us: i64| format!("{:.3}s", us as f64 / 1e6);
4046 cut.iter()
4047 .map(|c| {
4048 let windows: Vec<(i64, i64)> = s
4049 .lanes()
4050 .into_iter()
4051 .filter(|l| l.kind == LaneKind::Subtitle)
4052 .flat_map(|l| s.sub_lane(l).iter().filter(|p| p.track == c.track).map(|p| (p.in_us, p.out_us)).collect::<Vec<_>>())
4053 .collect();
4054 let mut pieces: Vec<(i64, String)> = s
4055 .subtitles()
4056 .get(c.track)
4057 .map(|t| {
4058 t.cues
4059 .iter()
4060 .filter(|q| q.image.is_none() && q.start_us >= c.track_start && q.end_us <= c.track_end)
4061 .filter(|q| windows.iter().any(|&(a, b)| q.start_us < b && q.end_us > a))
4062 .map(|q| (q.start_us, q.text.replace('\n', " / ")))
4063 .collect()
4064 })
4065 .unwrap_or_default();
4066 pieces.sort_by_key(|p| p.0);
4067 let kept: Vec<String> = pieces.into_iter().map(|p| p.1).collect();
4068 format!(
4069 "{} cue {} '{}' → '{}' (was {}–{}, now {}–{})",
4070 parse::lane_name(c.lane),
4071 c.index + 1,
4072 c.words,
4073 kept.join(" "),
4074 secs(c.old_start),
4075 secs(c.old_end),
4076 secs(c.new_start),
4077 secs(c.new_end)
4078 )
4079 })
4080 .collect()
4081}
4082
4083/// Every clip or caption at or after `from`, on the given lanes, after an edit
4084/// that ripples. These are the addresses a ripple changed.
4085fn ripple_touched(s: &PlaybackSession, lanes: &[Lane], from: u32) -> Vec<(Lane, u32)> {
4086 let mut out = Vec::new();
4087 for &l in lanes {
4088 if l.kind == LaneKind::Subtitle {
4089 out.extend(s.sub_lane(l).iter().filter(|c| c.start >= from).map(|c| (l, c.start)));
4090 } else {
4091 out.extend(s.lane_clips(l).iter().filter(|c| c.start >= from).map(|c| (l, c.start)));
4092 }
4093 }
4094 out
4095}
4096
4097fn clips_of_source_at(s: &PlaybackSession, n: usize, at: u32) -> Vec<(Lane, u32)> {
4098 let mut out = Vec::new();
4099 for l in s.lanes() {
4100 if l.kind == LaneKind::Subtitle {
4101 continue;
4102 }
4103 if s.lane_clips(l).iter().any(|c| c.source == n && c.start == at) {
4104 out.push((l, at));
4105 }
4106 }
4107 out
4108}
4109
4110/// The lanes of the take `(lane, idx)` belongs to: every lane a group-wide op touches.
4111fn take_lanes(s: &PlaybackSession, lane: Lane, idx: usize) -> Vec<Lane> {
4112 take_of(s, lane, idx).into_iter().map(|(l, _)| l).collect()
4113}
4114
4115/// Where a title starting at `x` lands after `spans` (sorted, non-overlapping `(start, len)`
4116/// timeline spans) are cut out: `x` less the frames cut before it. A title inside a span lands
4117/// at the span's start, the cut point.
4118fn title_shift(spans: &[(u32, u32)], x: u32) -> u32 {
4119 let removed: u32 = spans.iter().map(|&(a, len)| x.min(a.saturating_add(len)).saturating_sub(a)).sum();
4120 x - removed
4121}
4122
4123/// Moves every title for a cut of `spans` (see `title_shift`) and returns the moves as
4124/// `T2 6.500s→5.000s`. Titles follow the picture across a ripple, as the lanes do.
4125pub(crate) fn move_titles_for_cuts(s: &mut PlaybackSession, spans: &[(u32, u32)], fps: f64) -> Result<Vec<String>, String> {
4126 let mut moved = Vec::new();
4127 let mut sorted = spans.to_vec();
4128 sorted.sort_unstable();
4129 // Merged, so an overlap is not counted twice.
4130 let mut spans: Vec<(u32, u32)> = Vec::new();
4131 for (a, len) in sorted {
4132 match spans.last_mut() {
4133 Some(last) if a <= last.0.saturating_add(last.1) => {
4134 last.1 = last.1.max(a.saturating_add(len) - last.0);
4135 }
4136 _ => spans.push((a, len)),
4137 }
4138 }
4139 // Read before any write. Each title is written by what it was (its text and start, as read): a write
4140 // can re-sort the list, so an index read before it may name another title after it.
4141 let titles: Vec<engine::project::Title> = s.titles().to_vec();
4142 for (i, t) in titles.iter().enumerate() {
4143 let (ts, te) = (t.start, t.start.saturating_add(t.frames));
4144 // A title inside a span is removed, named; one the span crosses is trimmed to the part outside it;
4145 // one after the span moves back. Titles keep their order (the shift is monotone).
4146 let inside: u32 = spans.iter().map(|&(a, len)| te.min(a.saturating_add(len)).saturating_sub(ts.max(a))).sum();
4147 let new = title_shift(&spans, ts);
4148 if inside == 0 {
4149 if new == ts {
4150 continue;
4151 }
4152 let mut t2 = t.clone();
4153 t2.start = new;
4154 retitle(s, &t.text, ts, Some(t2)).map_err(|e| format!("T{}: {e}", i + 1))?;
4155 moved.push(format!("T{} {:.3}s→{:.3}s", i + 1, parse::secs(ts, fps), parse::secs(new, fps)));
4156 } else if inside >= t.frames {
4157 retitle(s, &t.text, ts, None).map_err(|e| format!("T{}: {e}", i + 1))?;
4158 moved.push(format!("T{} {:.3}s removed with the cut", i + 1, parse::secs(ts, fps)));
4159 } else {
4160 let mut t2 = t.clone();
4161 t2.start = new;
4162 t2.frames = t.frames - inside;
4163 retitle(s, &t.text, ts, Some(t2)).map_err(|e| format!("T{}: {e}", i + 1))?;
4164 moved.push(format!("T{} trimmed to {:.3}–{:.3}s", i + 1, parse::secs(new, fps), parse::secs(new + t.frames - inside, fps)));
4165 }
4166 }
4167 // Chapters follow the cut as titles do: one after a span moves back, one inside it lands at the cut point.
4168 s.remap_markers(|f| title_shift(&spans, f));
4169 let dropped = s.remap_chapters(|f| title_shift(&spans, f));
4170 if dropped > 0 {
4171 moved.push(format!("{dropped} chapter(s) lost their frame: a chapter moved onto another's frame in the cut"));
4172 }
4173 Ok(moved)
4174}
4175
4176/// Writes title `text` that starts at `from` (as the plan read it): `Some` sets it, `None` removes it.
4177/// Titles are kept in start order, so a title moved past another changes its index; each write
4178/// finds its title again by what it was, so the next one still lands on the right title.
4179pub(crate) fn retitle(s: &mut PlaybackSession, text: &str, from: u32, to: Option<engine::project::Title>) -> Result<(), String> {
4180 let idx = s
4181 .titles()
4182 .iter()
4183 .position(|t| t.text == text && t.start == from)
4184 .ok_or_else(|| format!("title {text:?} at {from}f is not there to change"))?;
4185 match to {
4186 Some(t) => match s.set_title(idx, t) {
4187 true => Ok(()),
4188 false => Err(format!("title {text:?} would not move")),
4189 },
4190 None => match s.remove_title(idx) {
4191 true => Ok(()),
4192 false => Err(format!("title {text:?} would not be removed")),
4193 },
4194 }
4195}
4196
4197/// The reply's line for titles that a cut moved, empty when none did.
4198pub(crate) fn titles_note(moved: &[String]) -> String {
4199 if moved.is_empty() {
4200 String::new()
4201 } else {
4202 format!("; titles moved with the cut: {}", moved.join(", "))
4203 }
4204}
4205
4206fn op_delete(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Done, String> {
4207 let (lane, idx) = clip_arg(s, op)?;
4208 let addr = addr_of(s, lane, idx);
4209 let clip = s.lane_clips(lane)[idx].clone();
4210 check_unlocked(s, &take_lanes(s, lane, idx))?;
4211 let span = [(clip.start, clip.frames())];
4212 // A take cut to one span on every member moves by the rule; a hand-built group whose
4213 // members differ keeps the engine's own law, each member's span out of its own lane.
4214 let take = take_of(s, lane, idx);
4215 let even = take.iter().all(|&(l, i)| {
4216 let c = &s.lane_clips(l)[i];
4217 c.start == clip.start && c.frames() == clip.frames()
4218 });
4219 if !even {
4220 let gone = vec![(lane, clip.start, clip.link)];
4221 if !s.delete_clip(lane, idx) {
4222 return Err(format!("delete {addr} refused: no such clip, or its lane is locked"));
4223 }
4224 let moved = move_titles_for_cuts(s, &span, fps)?;
4225 // The clips the ripple moved are named by the shifted list: no arrow list, since the address the
4226 // removed clip had is now another clip's.
4227 return Ok(plain(format!("delete {addr}{}{}", removed_words(&gone), titles_note(&moved)), Vec::new()));
4228 }
4229 let sc = rip_scope(s, op, &[(lane, idx)], clip.start)?;
4230 check_unlocked(s, &sc.lanes)?;
4231 let hit = unrelated_in_cut(s, &sc.lanes, &[(lane, idx)], clip.start, clip.end());
4232 if !hit.is_empty() {
4233 return Err(unrelated_refusal(&format!("delete {addr}"), &addr, &hit, &format!("lift {addr} to leave the gap instead")));
4234 }
4235 let gone = clips_within(s, &sc.lanes, clip.start, clip.end());
4236 let drift = caption_drift(s, op, &sc.lanes, clip.start);
4237 // Delete closes the gap the way ripple_delete does, so the caption cues it removes or trims are named the same way.
4238 let (cues_gone, cues_cut) = cues_in_span(s, &sc.lanes, clip.start, clip.end(), fps);
4239 s.cut_regions(&span, &sc.lanes).map_err(|e| format!("delete {addr} refused: {e}"))?;
4240 let cues_cut = trimmed_cue_lines(s, &cues_cut);
4241 let moved = if has_picture(&sc.lanes) { move_titles_for_cuts(s, &span, fps)? } else { Vec::new() };
4242 Ok(plain(
4243 format!("delete {addr}{}{}{}{drift}{}", removed_words(&gone), titles_note(&moved), skipped_note(&sc.skipped), cue_cut_text(&cues_gone, &cues_cut)),
4244 Vec::new(),
4245 ))
4246}
4247
4248/// `+15f` / `-0.5s` / `00:00:01:00`: the signed distance an op's `by` asks, in frames.
4249fn need_by(op: &Value, fps: f64) -> Result<i64, String> {
4250 match op.get("by") {
4251 None | Some(Value::Null) => Err("missing `by`: give a signed distance such as 15f, -0.5s or +00:00:01:00".into()),
4252 Some(v) => parse::delta(v, fps).map_err(|e| format!("`by`: {e}")),
4253 }
4254}
4255
4256/// A frame count with its sign, for `by` words: `+15f`, `-3f`.
4257fn signed(n: i64) -> String {
4258 format!("{n:+}f")
4259}
4260
4261/// The addresses of the clips a roll/slide left at new starts, for the reply's `now at` list.
4262fn starts_of(s: &PlaybackSession, picks: &[(Lane, usize)]) -> Vec<(Lane, u32)> {
4263 picks.iter().filter_map(|&(l, i)| s.lane_clips(l).get(i).map(|c| (l, c.start))).collect()
4264}
4265
4266/// `roll {clip, by|to, edge?}`: the cut at the clip's out edge (`edge:"in"`: its in edge) moves, and
4267/// the two clips either side of it give and take the frames. Nothing else moves.
4268fn op_roll(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Done, String> {
4269 let (lane, idx) = clip_arg(s, op)?;
4270 let addr = addr_of(s, lane, idx);
4271 let at_in = match op.get("edge").and_then(Value::as_str) {
4272 None | Some("out") => false,
4273 Some("in") => true,
4274 Some(_) => return Err("`edge` must be \"in\" or \"out\": the cut at the clip's in edge or at its out edge".into()),
4275 };
4276 // The clip before the cut is the one the engine rolls by.
4277 let a_idx = if at_in {
4278 idx.checked_sub(1).ok_or_else(|| format!("roll {addr} edge:\"in\" refused: {addr} is the first clip on {}, so no cut lies at its in edge", parse::lane_name(lane)))?
4279 } else {
4280 idx
4281 };
4282 let clips = s.lane_clips(lane);
4283 let cut = match (clips.get(a_idx), clips.get(a_idx + 1)) {
4284 (Some(a), Some(b)) if a.end() == b.start => a.end(),
4285 (Some(a), Some(b)) => {
4286 return Err(format!(
4287 "roll {addr} refused: {} ends at {} and {} starts at {}; a gap, not a cut, lies between them (roll needs two clips butting at a cut; close_gaps first, or trim)",
4288 parse::addr(lane, a.start), parse::tc(a.end(), fps), parse::addr(lane, b.start), parse::tc(b.start, fps)
4289 ));
4290 }
4291 _ => {
4292 return Err(format!(
4293 "roll {addr} refused: there is no clip {} {addr} on {}, so there is no cut to move (roll needs two clips butting at a cut; trim moves a lone edge)",
4294 if at_in { "before" } else { "after" }, parse::lane_name(lane)
4295 ));
4296 }
4297 };
4298 let (want, shown, asked) = match (op.get("by").filter(|v| !v.is_null()), op.get("to").filter(|v| !v.is_null())) {
4299 (Some(_), Some(_)) => return Err("roll takes `by` or `to`, not both".into()),
4300 (None, None) => return Err("missing `by` or `to`: give the new cut place (to: 450f) or a signed move (by: -15f)".into()),
4301 (Some(_), None) => {
4302 let by = need_by(op, fps)?;
4303 ((i64::from(cut) + by).max(0), signed(by), None)
4304 }
4305 (None, Some(_)) => {
4306 let to = need(op, "to", fps, end)?;
4307 (i64::from(to), shown_time(op.get("to"), to), op.get("to"))
4308 }
4309 };
4310 let take = take_of(s, lane, a_idx);
4311 check_unlocked(s, &take.iter().map(|&(l, _)| l).collect::<Vec<_>>())?;
4312 let Some((lo, hi)) = s.roll_room(lane, a_idx) else {
4313 return Err(format!("roll {addr} refused: no cut there"));
4314 };
4315 let want = u32::try_from(want).unwrap_or(u32::MAX);
4316 if want == cut {
4317 return Ok(plain(format!("roll {addr}: the cut is already at {}: nothing to roll", parse::tc(cut, fps)), Vec::new()));
4318 }
4319 let target = want.clamp(lo, hi);
4320 let room = format!("the cut can travel {}–{} (the source media of the two clips, and a frame of each)", parse::tc(lo, fps), parse::tc(hi, fps));
4321 if target == cut {
4322 return Ok(plain(
4323 format!("roll {addr}: the cut is already at {}: clamped, it cannot go to {shown}: {room}", parse::tc(cut, fps)),
4324 Vec::new(),
4325 ));
4326 }
4327 let Some(landed) = s.roll_clip(lane, a_idx, target) else {
4328 return Err(format!("roll {addr} refused: the engine would not roll that cut"));
4329 };
4330 if landed == cut {
4331 return Ok(plain(
4332 format!("roll {addr}: the cut stayed at {}: no frame between it and {} is reachable by every clip of the take at its speed", parse::tc(cut, fps), parse::tc(target, fps)),
4333 Vec::new(),
4334 ));
4335 }
4336 let mut text = match asked.and_then(|a| asked_arrow(Some(a), fps, landed)) {
4337 Some(a) => format!("roll {addr} cut: {a}"),
4338 None => format!("roll {addr} cut {} → {}", parse::tc(cut, fps), parse::tc(landed, fps)),
4339 };
4340 if landed != target {
4341 text.push_str(&format!("; landed on {} (the nearest frame every clip of the take reaches at its speed)", parse::tc(landed, fps)));
4342 }
4343 if target != want {
4344 text.push_str(&format!("; clamped from {shown} to {}: {room}", parse::tc(target, fps)));
4345 }
4346 let mut picks = Vec::new();
4347 for &(l, i) in &take {
4348 let clips = s.lane_clips(l);
4349 if clips.get(i + 1).is_some_and(|b| clips[i].end() == b.start) {
4350 picks.extend([(l, i), (l, i + 1)]);
4351 }
4352 }
4353 let touched = starts_of(s, &picks);
4354 let with: Vec<String> = touched.iter().skip(2).map(|&(l, st)| parse::addr(l, st)).collect();
4355 if !with.is_empty() {
4356 text.push_str(&format!(" (with {})", with.join(", ")));
4357 }
4358 Ok(plain(text, touched))
4359}
4360
4361/// `slip {clip, by}`: the clip keeps its place and length and plays footage `by` timeline frames
4362/// later (earlier for a negative `by`) in its source. A speed other than 1 makes that more or less
4363/// source: the reply says how much.
4364fn op_slip(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Done, String> {
4365 let (lane, idx) = clip_arg(s, op)?;
4366 let addr = addr_of(s, lane, idx);
4367 let by = need_by(op, fps)?;
4368 let take = take_of(s, lane, idx);
4369 check_unlocked(s, &take.iter().map(|&(l, _)| l).collect::<Vec<_>>())?;
4370 let Some((back, fwd)) = s.slip_room(lane, idx) else {
4371 return Err(format!("slip {addr} refused: a still image has no source frames to slip through"));
4372 };
4373 let before = s.lane_clips(lane)[idx].clone();
4374 if by == 0 {
4375 return Ok(plain(format!("slip {addr}: by 0f, nothing to slip"), Vec::new()));
4376 }
4377 let src = s.slip_source_delta(lane, idx, by).unwrap_or(by);
4378 // A ramp's mean rate: the source it reads over the timeline it fills.
4379 let speed = if before.speed_keys.is_empty() {
4380 before.speed.as_f64()
4381 } else {
4382 f64::from(before.len()) / f64::from(before.frames())
4383 };
4384 let conv = if src != by {
4385 format!(" ({} on the timeline is {} source frames at {}x)", signed(by), src, compact(speed))
4386 } else {
4387 String::new()
4388 };
4389 if src == 0 {
4390 return Ok(plain(format!("slip {addr}: {} is less than one source frame at {}x, nothing to slip", signed(by), compact(speed)), Vec::new()));
4391 }
4392 let Some(moved) = s.slip_clip(lane, idx, src) else {
4393 return Err(format!("slip {addr} refused: the engine would not slip that clip"));
4394 };
4395 let room = format!("the source allows {back}f back and +{fwd}f forward from here");
4396 if moved == 0 {
4397 return Ok(plain(format!("slip {addr}: the source window stayed at {}f–{}f: clamped, it cannot go {} source frames: {room}", before.in_frame, before.out_frame, src), Vec::new()));
4398 }
4399 let now = s.lane_clips(lane)[idx].clone();
4400 let mut text = format!(
4401 "slip {addr} by {}{conv}: source {}f–{}f → {}f–{}f, still {}–{} on the timeline",
4402 signed(by), before.in_frame, before.out_frame, now.in_frame, now.out_frame, parse::tc(now.start, fps), parse::tc(now.end(), fps)
4403 );
4404 if moved != src {
4405 text.push_str(&format!("; clamped from {src:+} to {moved:+} source frames: {room}"));
4406 }
4407 let touched = starts_of(s, &take);
4408 let with: Vec<String> = touched.iter().skip(1).map(|&(l, st)| parse::addr(l, st)).collect();
4409 if !with.is_empty() {
4410 text.push_str(&format!(" (with {})", with.join(", ")));
4411 }
4412 Ok(plain(text, touched))
4413}
4414
4415/// `slide {clip, by}`: the clip moves `by` along its lane with its content and length unchanged; the
4416/// clip before it ends later or earlier and the clip after it starts later or earlier, so the
4417/// timeline's length stays. Needs a clip on each side.
4418fn op_slide(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Done, String> {
4419 let (lane, idx) = clip_arg(s, op)?;
4420 let addr = addr_of(s, lane, idx);
4421 let by = need_by(op, fps)?;
4422 let take = take_of(s, lane, idx);
4423 check_unlocked(s, &take.iter().map(|&(l, _)| l).collect::<Vec<_>>())?;
4424 let lane_name = parse::lane_name(lane);
4425 let n = s.lane_clips(lane).len();
4426 if idx == 0 || idx + 1 >= n {
4427 let side = if idx == 0 { "before" } else { "after" };
4428 return Err(format!(
4429 "slide {addr} refused: there is no clip {side} it on {lane_name}, so no neighbour can take up the move and the timeline would change length (slide needs a clip on each side; move places a clip freely)"
4430 ));
4431 }
4432 if let Some(&(l, i)) = take.iter().find(|&&(l, i)| i == 0 || i + 1 >= s.lane_clips(l).len()) {
4433 return Err(format!(
4434 "slide {addr} refused: its take member {} has no neighbour on each side of {}",
4435 addr_of(s, l, i), parse::lane_name(l)
4436 ));
4437 }
4438 let Some((lo, hi)) = s.slide_room(lane, idx) else {
4439 return Err(format!("slide {addr} refused: no clip there to slide"));
4440 };
4441 let start = s.lane_clips(lane)[idx].start;
4442 if by == 0 {
4443 return Ok(plain(format!("slide {addr}: by 0f, nothing to slide"), Vec::new()));
4444 }
4445 let want = u32::try_from((i64::from(start) + by).max(0)).unwrap_or(u32::MAX);
4446 let target = want.clamp(lo, hi);
4447 let room = format!("{addr} can start between {} and {} (the neighbours' source media, a frame of each, and any gap it must not enter)", parse::tc(lo, fps), parse::tc(hi, fps));
4448 if target == start {
4449 return Ok(plain(format!("slide {addr}: clamped, it cannot move {}: {room}", signed(by)), Vec::new()));
4450 }
4451 // Neighbours are named before the move; their indices do not change.
4452 let mut picks: Vec<(Lane, usize)> = Vec::new();
4453 for &(l, i) in &take {
4454 picks.extend([(l, i), (l, i - 1), (l, i + 1)]);
4455 }
4456 let Some(landed) = s.slide_clip(lane, idx, target) else {
4457 return Err(format!("slide {addr} refused: the engine would not slide that clip"));
4458 };
4459 if landed == start {
4460 return Ok(plain(
4461 format!("slide {addr}: stayed at {}: no start between it and {} is reachable by every neighbour at its speed", parse::tc(start, fps), parse::tc(target, fps)),
4462 Vec::new(),
4463 ));
4464 }
4465 let new_addr = parse::addr(lane, landed);
4466 let clips = s.lane_clips(lane);
4467 let mut text = format!(
4468 "slide {addr} by {}: now {new_addr}; {} now ends at {}, {} now starts at {}",
4469 signed(i64::from(landed) - i64::from(start)),
4470 parse::addr(lane, clips[idx - 1].start),
4471 parse::tc(clips[idx - 1].end(), fps),
4472 parse::addr(lane, clips[idx + 1].start),
4473 parse::tc(clips[idx + 1].start, fps)
4474 );
4475 if landed != target {
4476 text.push_str(&format!("; landed on {} (the nearest start every neighbour reaches at its speed)", parse::tc(landed, fps)));
4477 }
4478 if target != want {
4479 text.push_str(&format!("; clamped from {} to {}: {room}", signed(by), signed(i64::from(landed) - i64::from(start))));
4480 }
4481 let touched = starts_of(s, &picks);
4482 Ok(plain(text, touched))
4483}
4484
4485/// `swap {a, b}`: two placements of one lane trade places. `b` takes `a`'s start, what lies
4486/// between them ripples by the difference in their lengths, and `a` lands where `b` was. The
4487/// span they cover keeps its length, so nothing after `b` moves. The reply lists every clip
4488/// that moved. One undo step.
4489fn op_swap(s: &mut PlaybackSession, op: &Value) -> Result<Done, String> {
4490 let a_raw = op.get("a").and_then(Value::as_str).ok_or("missing `a`: the first clip's address, such as V1@0")?;
4491 let b_raw = op.get("b").and_then(Value::as_str).ok_or("missing `b`: the second clip's address, such as V1@300f")?;
4492 let (la, ia) = clip_addr(s, a_raw)?;
4493 let (lb, ib) = clip_addr(s, b_raw)?;
4494 let who = format!("swap {a_raw} ↔ {b_raw}");
4495 if la != lb {
4496 return Err(format!(
4497 "{who}: the two clips are on {} and {}; swap trades two clips on one lane. Use move to carry one onto the other lane",
4498 parse::lane_name(la),
4499 parse::lane_name(lb)
4500 ));
4501 }
4502 if ia == ib {
4503 return Err(format!("{who}: the same clip twice; name two different clips"));
4504 }
4505 check_unlocked(s, &[la])?;
4506 let ripple = match op.get("ripple") {
4507 None | Some(Value::Null) => true,
4508 Some(Value::Bool(b)) => *b,
4509 Some(_) => return Err(format!("{who}: `ripple` must be true or false")),
4510 };
4511 if !ripple {
4512 return swap_in_slots(s, la, ia, ib, &who);
4513 }
4514 // A clip is in a take only when another clip shares its link; a lone link (what ungroup leaves) is not.
4515 if take_of(s, la, ia).len() > 1 || take_of(s, la, ib).len() > 1 {
4516 return Err(format!(
4517 "{who} refused: a clip in a take (grouped with another lane) is moved as a take, not swapped apart. Ungroup the take first"
4518 ));
4519 }
4520 let before = layout(s);
4521 let (la_len, lb_len) = (s.lane_clips(la)[ia].frames(), s.lane_clips(la)[ib].frames());
4522 if !s.swap_clips(la, ia, ib) {
4523 return Err(format!(
4524 "{who} refused: a clip in a take (grouped with another lane) is moved as a take, not swapped apart. Ungroup the take first"
4525 ));
4526 }
4527 // The earlier of the two now holds the later clip, and the later one holds the earlier.
4528 let (lo, hi) = (ia.min(ib), ia.max(ib));
4529 let now = s.lane_clips(la);
4530 let (at_lo, at_hi) = (parse::addr(la, now[lo].start), parse::addr(la, now[hi].start));
4531 let (later, earlier) = if ia > ib { (a_raw, b_raw) } else { (b_raw, a_raw) };
4532 let mut text = format!("{who}: {later} now at {at_lo}, {earlier} now at {at_hi}");
4533 // The clips that moved are listed once, on the batch's `shifted:` line.
4534 let moved_any = !shifted_pairs(&before, &layout(s)).is_empty();
4535 if !moved_any {
4536 text.push_str(" (nothing else moved)");
4537 }
4538 // A swap ripples what lies between the two by the difference in their lengths: say so, so a
4539 // shifted clip is explained. ripple:false keeps both slots where they were.
4540 // Said only when a clip moved: an unequal swap with nothing after it moves nothing.
4541 if la_len != lb_len && moved_any {
4542 text.push_str(&format!(
4543 " (the swapped clips differ by {}f, so later clips moved by {}f; use ripple:false to keep everyone else in place)",
4544 la_len.abs_diff(lb_len),
4545 la_len.abs_diff(lb_len)
4546 ));
4547 }
4548 Ok(plain(text, Vec::new()))
4549}
4550
4551/// `swap {a, b, ripple:false}`: the two clips trade slots and nothing between them moves. The
4552/// earlier clip takes the later one's start and the later one the earlier's, so a shorter clip
4553/// leaves a gap in its slot and a longer one is refused where it would overlap what follows. The
4554/// engine checks the two clips at their final positions, so a clip may land on the slot the other
4555/// one leaves. Atomic: a refusal changes nothing, and the swap is one undo step.
4556fn swap_in_slots(s: &mut PlaybackSession, la: Lane, ia: usize, ib: usize, who: &str) -> Result<Done, String> {
4557 if take_of(s, la, ia).len() > 1 || take_of(s, la, ib).len() > 1 {
4558 return Err(format!(
4559 "{who} refused: a clip in a take (grouped with another lane) is moved as a take, not swapped apart. Ungroup the take first"
4560 ));
4561 }
4562 let (lo, hi) = if ia < ib { (ia, ib) } else { (ib, ia) };
4563 let (lo_start, hi_start) = (s.lane_clips(la)[lo].start, s.lane_clips(la)[hi].start);
4564 let (lo_len, hi_len) = (s.lane_clips(la)[lo].frames(), s.lane_clips(la)[hi].frames());
4565 s.swap_clips_in_place(la, ia, ib).map_err(|e| format!("{who} refused: {e}"))?;
4566 // The engine gives the earlier clip the later one's start and the later clip the earlier's.
4567 // Read from that rule rather than from a clip key: two clips with the same source range
4568 // would make a key lookup name the wrong one.
4569 // `a` and `b` are named as the caller gave them: the earlier one takes the later start.
4570 let (a_at, b_at) = if ia < ib { (hi_start, lo_start) } else { (lo_start, hi_start) };
4571 // A shorter clip leaves the rest of its slot empty: name each hole an unequal swap leaves.
4572 let mut holes = String::new();
4573 if lo_len > hi_len {
4574 let at = lo_start + hi_len;
4575 holes.push_str(&format!("; a gap of {}f is left after {} at {}", lo_len - hi_len, parse::addr(la, lo_start), parse::tc(at, parse::session_fps(s))));
4576 }
4577 if hi_len > lo_len {
4578 let at = hi_start + lo_len;
4579 holes.push_str(&format!("; a gap of {}f is left after {} at {}", hi_len - lo_len, parse::addr(la, hi_start), parse::tc(at, parse::session_fps(s))));
4580 }
4581 Ok(plain(
4582 format!(
4583 "{who}: first now at {}, second now at {}{holes}",
4584 secs_text(a_at, parse::session_fps(s)),
4585 secs_text(b_at, parse::session_fps(s))
4586 ),
4587 vec![(la, a_at), (la, b_at)],
4588 ))
4589}
4590
4591fn op_lift(s: &mut PlaybackSession, op: &Value) -> Result<Done, String> {
4592 let (lane, idx) = clip_arg(s, op)?;
4593 let addr = addr_of(s, lane, idx);
4594 // Lifting a clip takes it out of its take: a locked partner would lose its link, so it refuses.
4595 check_unlocked(s, &take_lanes(s, lane, idx))?;
4596 check_unlocked(s, &[lane])?;
4597 if !s.lift_clip(lane, idx) {
4598 return Err(format!("lift {addr} refused: no such clip, or its lane is locked"));
4599 }
4600 Ok(Done { text: format!("lift {addr} (gap left)"), touched: Vec::new(), lanes: vec![lane] })
4601}
4602
4603fn op_ripple_delete(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Done, String> {
4604 let (lane, idx) = clip_arg(s, op)?;
4605 let addr = addr_of(s, lane, idx);
4606 let clip = s.lane_clips(lane)[idx].clone();
4607 let sc = rip_scope(s, op, &[(lane, idx)], clip.start)?;
4608 check_unlocked(s, &sc.lanes)?;
4609 let hit = unrelated_in_cut(s, &sc.lanes, &[(lane, idx)], clip.start, clip.end());
4610 if !hit.is_empty() {
4611 return Err(unrelated_refusal(&format!("ripple_delete {addr}"), &addr, &hit, &format!("lift {addr} to leave the gap instead")));
4612 }
4613 let span = [(clip.start, clip.frames())];
4614 let gone = clips_within(s, &sc.lanes, clip.start, clip.end());
4615 let drift = caption_drift(s, op, &sc.lanes, clip.start);
4616 let sound =sound_drift(s, &sc.lanes, clip.end(), &format!("−{:.3}s", parse::secs(clip.frames(), fps)));
4617 // The caption cues inside the cut leave with it, so the reply names them (read before the cut, as remove_time does).
4618 let (cues_gone, cues_cut) = cues_in_span(s, &sc.lanes, clip.start, clip.end(), fps);
4619 s.cut_regions(&span, &sc.lanes).map_err(|e| format!("ripple_delete {addr} refused: {e}"))?;
4620 let cues_cut = trimmed_cue_lines(s, &cues_cut);
4621 let moved = if has_picture(&sc.lanes) { move_titles_for_cuts(s, &span, fps)? } else { Vec::new() };
4622 // The span it closed is named, so the reply says how much time went (the removed clips are side effects).
4623 let closed = format!(" closed {}–{}", secs_text(clip.start, fps), secs_text(clip.end(), fps));
4624 Ok(plain(
4625 format!("ripple_delete {addr}{closed}{}{}{}{}{sound}{drift}{}", removed_words(&gone), titles_note(&moved), skipped_note(&sc.skipped), left_behind(s, &sc.lanes, clip.start), cue_cut_text(&cues_gone, &cues_cut)),
4626 Vec::new(),
4627 ))
4628}
4629
4630/// The gaps on a lane as (the clip after the gap, its identity, gap start, gap end). A gap is
4631/// closed when the clip after it no longer has one before it, which the identity tells.
4632fn gaps_of(s: &PlaybackSession, lane: Lane) -> Vec<(String, u32, u32)> {
4633 let mut out = Vec::new();
4634 let mut prev_end = 0u32;
4635 if lane.kind == LaneKind::Subtitle {
4636 for c in s.sub_lane(lane) {
4637 if c.start > prev_end {
4638 out.push((format!("caption {}:{}", c.track, c.in_us), prev_end, c.start));
4639 }
4640 prev_end = prev_end.max(c.start + c.frames);
4641 }
4642 } else {
4643 for c in s.lane_clips(lane) {
4644 if c.start > prev_end {
4645 out.push((format!("clip {}:{}", c.source, c.in_frame), prev_end, c.start));
4646 }
4647 prev_end = prev_end.max(c.end());
4648 }
4649 }
4650 out
4651}
4652
4653/// Why close_gaps would leave the gap `start..start+frames` on `lane` open, in the words a fix needs.
4654/// None when it closes. The engine's own refusal (`gap_take_scope`) names the other take's gap
4655/// "there too" even when that lane has no gap there, so a partner with no gap of this span is named here.
4656fn take_gap_refusal(s: &PlaybackSession, lane: Lane, start: u32, frames: u32) -> Option<String> {
4657 let engine = match s.gap_take_scope(lane, start, frames) {
4658 Ok(_) => return None,
4659 Err(e) => e.to_string(),
4660 };
4661 let end = start + frames;
4662 let name = parse::lane_name(lane);
4663 for c in s.lane_clips(lane).iter().filter(|c| c.end() == start || c.start == end) {
4664 let Some(id) = c.link else { continue };
4665 for j in s.lanes() {
4666 if j == lane || j.kind == LaneKind::Subtitle {
4667 continue;
4668 }
4669 let Some(half) = s.lane_clips(j).iter().find(|o| o.link == Some(id)) else { continue };
4670 let other = parse::lane_name(j);
4671 if gaps_of(s, j).iter().any(|&(_, a, b)| a == start && b == end) {
4672 continue;
4673 }
4674 return Some(format!(
4675 "the {name} clip at {} is one take with the {other} clip at {}, and {other} has no gap of that length there: closing this one alone would pull the take out of sync, so the gap stays open (ungrouping would break the take)",
4676 parse::addr(lane, c.start),
4677 parse::addr(j, half.start)
4678 ));
4679 }
4680 }
4681 Some(engine)
4682}
4683
4684fn op_close_gaps(s: &mut PlaybackSession, op: &Value) -> Result<Done, String> {
4685 let lane = lane_arg(op, "lane")?.ok_or("missing `lane`: give a lane such as A1")?;
4686 check_unlocked(s, &[lane])?;
4687 let fps = parse::session_fps(s);
4688 // An empty lane has no gap to close, and no end to measure against the timeline.
4689 let empty = if lane.kind == LaneKind::Subtitle { s.sub_lane(lane).is_empty() } else { s.lane_clips(lane).is_empty() };
4690 if empty {
4691 let name = parse::lane_name(lane);
4692 return Ok(Done { text: format!("close_gaps {name}: {name} is empty: nothing to close"), touched: Vec::new(), lanes: vec![lane] });
4693 }
4694 let before_gaps = gaps_of(s, lane);
4695 let before_layout = layout(s);
4696 // Read before the close, while each gap still has its place: the reason a take refuses it.
4697 let own_reasons: Vec<(u32, String)> = before_gaps
4698 .iter()
4699 .filter_map(|&(_, a, b)| take_gap_refusal(s, lane, a, b - a).map(|r| (a, r)))
4700 .collect();
4701 let report = s.close_all_gaps_on_lane(lane).map_err(|e| e.to_string())?;
4702 let after_gaps = gaps_of(s, lane);
4703 let span = |a: u32, b: u32| format!("{}–{}", secs_text(a, fps), secs_text(b, fps));
4704 let closed: Vec<String> = before_gaps
4705 .iter()
4706 .filter(|(who, _, _)| !after_gaps.iter().any(|(w, _, _)| w == who))
4707 .map(|&(_, a, b)| span(a, b))
4708 .collect();
4709 let open: Vec<String> = after_gaps.iter().map(|&(_, a, b)| span(a, b)).collect();
4710 let name = parse::lane_name(lane);
4711 // A lane with no gap at all says so, and its reply names no clip (nothing was closed or moved).
4712 let no_gaps = report.closed == 0 && report.skipped.is_empty() && open.is_empty();
4713 let mut text = if no_gaps {
4714 format!("close_gaps {name}: {name} has no gaps")
4715 } else {
4716 format!("close_gaps {name}: closed {}", report.closed)
4717 };
4718 if !closed.is_empty() {
4719 text.push_str(&format!(" ({})", closed.join(", ")));
4720 }
4721 if !report.skipped.is_empty() || !open.is_empty() {
4722 // Each gap says why the engine kept it open (its own refusal, a take that would split). The
4723 // skipped list runs left to right like the open spans, so each reason sits beside its span.
4724 let reasons: Vec<String> = report
4725 .skipped
4726 .iter()
4727 .map(|k| own_reasons.iter().find(|(a, _)| *a == k.start).map_or_else(|| k.reason.clone(), |(_, r)| r.clone()))
4728 .collect();
4729 let detail = if reasons.is_empty() {
4730 open.join(", ")
4731 } else if open.len() == reasons.len() {
4732 open.iter().zip(&reasons).map(|(span, why)| format!("{span}: {why}")).collect::<Vec<_>>().join("; ")
4733 } else {
4734 reasons.join("; ")
4735 };
4736 let detail = if detail.is_empty() { "times not read".to_string() } else { detail };
4737 text.push_str(&format!("; left open {} ({detail})", open.len().max(reasons.len())));
4738 }
4739 // Clips on other lanes that moved (a linked partner comes with the clip that closes the gap).
4740 let moved: Vec<String> = shifted_pairs(&before_layout, &layout(s))
4741 .into_iter()
4742 // Only the clips on other lanes: neither end of a pair may be on the lane that was closed.
4743 .filter(|(a, b)| !a.starts_with(&format!("{name}@")) && !b.starts_with(&format!("{name}@")))
4744 .map(|(a, b)| format!("{a}→{b}"))
4745 .collect();
4746 if !moved.is_empty() {
4747 text.push_str(&format!("; moved on other lanes: {}", moved.join(", ")));
4748 }
4749 // A gap the close leaves on another media lane (a music bed with no gap where this lane had one) is
4750 // named with its way out: its own close_gaps, or the take that keeps it open.
4751 let mut left: Vec<String> = Vec::new();
4752 for other in s.lanes().into_iter().filter(|&l| l != lane && l.kind != LaneKind::Subtitle).collect::<Vec<_>>() {
4753 let gaps = gaps_of(s, other);
4754 if gaps.is_empty() {
4755 continue;
4756 }
4757 let oname = parse::lane_name(other);
4758 let spans: Vec<String> = gaps.iter().map(|&(_, a, b)| span(a, b)).collect();
4759 let why = gaps
4760 .iter()
4761 .find_map(|&(_, a, b)| take_gap_refusal(s, other, a, b - a))
4762 .map(|r| format!(" (kept open: {r})"))
4763 .unwrap_or_else(|| format!(" (close with close_gaps {{lane:\"{oname}\"}})"));
4764 left.push(format!("{oname} {}{why}", spans.join(", ")));
4765 }
4766 if !left.is_empty() {
4767 text.push_str(&format!("; gaps left on other lanes: {}", left.join("; ")));
4768 }
4769 // A lane that ends before the timeline does not have a gap to close: its tail is empty time.
4770 let end = parse::session_end(s);
4771 let ends = lane_end(s, lane);
4772 if ends < end {
4773 // The item that sets the timeline end: a lane, or else a title (titles count toward the end).
4774 let longest = s
4775 .lanes()
4776 .into_iter()
4777 .find(|&l| lane_end(s, l) == end)
4778 .map(parse::lane_name)
4779 .or_else(|| s.titles().iter().position(|t| t.start + t.frames == end).map(|i| format!("T{}", i + 1)))
4780 .unwrap_or_else(|| "the timeline".to_string());
4781 text.push_str(&format!(
4782 "; {name} ends at {:.1}s, {:.1}s before the timeline end ({longest}); trim {longest} or extend {name} to reach it",
4783 parse::secs(ends, fps),
4784 parse::secs(end - ends, fps)
4785 ));
4786 }
4787 let touched = if no_gaps { Vec::new() } else { s.lane_clips(lane).iter().map(|c| (lane, c.start)).collect() };
4788 Ok(Done { text, touched, lanes: vec![lane] })
4789}
4790
4791/// `close_gap {lane, at}`: closes the one gap on `lane` that `at` stands in, the way the GUI's Close
4792/// gap does: the gap's take scope ([`PlaybackSession::gap_take_scope`]) is cut out together, so a
4793/// linked partner closes with it. Nothing else moves.
4794fn op_close_gap(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Done, String> {
4795 let lane = lane_arg(op, "lane")?.ok_or("missing `lane`: give a lane such as V1")?;
4796 let at = need(op, "at", fps, end)?;
4797 let name = parse::lane_name(lane);
4798 if lane.kind == LaneKind::Subtitle {
4799 return Err(format!("close_gap {name}: captions have no gap closed this way; use close_gaps {{lane:\"{name}\"}}"));
4800 }
4801 let Some((start, frames)) = s.closable_gap_at(lane, at) else {
4802 return Err(format!(
4803 "close_gap {name}: no gap on {name} at {}; a clip is there, the time is past the last clip, or it is the empty lead-in before the first clip",
4804 shown_time(op.get("at"), at)
4805 ));
4806 };
4807 let scope = s.gap_take_scope(lane, start, frames).map_err(|e| e.to_string())?;
4808 check_unlocked(s, &scope)?;
4809 let scope = s.close_gap_at(lane, start, frames).map_err(|e| e.to_string())?;
4810 let names: Vec<String> = scope.iter().map(|&l| parse::lane_name(l)).collect();
4811 let take = if scope.len() > 1 { format!(" with its take on {}", names.join(", ")) } else { String::new() };
4812 let text = format!(
4813 "close_gap {name}: closed {}–{} ({frames}f){take}",
4814 secs_text(start, fps),
4815 secs_text(start + frames, fps)
4816 );
4817 Ok(Done { text, touched: ripple_touched(s, &scope, start), lanes: scope })
4818}
4819
4820/// `regroup {at}`: rejoins the clips that meet at `at` in every lane and puts them back in one group,
4821/// the inverse of `split`. The GUI's Regroup does the same at the playhead, through the same engine door.
4822fn op_regroup(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Done, String> {
4823 let at = need(op, "at", fps, end)?;
4824 let shown = shown_time(op.get("at"), at);
4825 // A rejoin takes one placement out of each lane it joins, and the joined one no longer starts at
4826 // `at`, so the lanes are the ones that lost a placement, counted before and after.
4827 let before: Vec<(Lane, usize)> = s.lanes().into_iter().map(|l| (l, placements(s, l))).collect();
4828 if !s.regroup_at(parse::secs(at, fps)) {
4829 return Err(format!(
4830 "regroup {shown}: nothing to rejoin there; no cut sits at that frame, or the clips on it were never split apart"
4831 ));
4832 }
4833 let mut lanes: Vec<Lane> = Vec::new();
4834 let mut touched: Vec<(Lane, u32)> = Vec::new();
4835 for (l, n) in before {
4836 if placements(s, l) >= n {
4837 continue;
4838 }
4839 // The rejoined placement is the one that now covers the cut, and its new address is what a reply names.
4840 let start = if l.kind == LaneKind::Subtitle {
4841 s.sub_lane(l).iter().find(|c| c.start < at && at < c.start + c.frames).map(|c| c.start)
4842 } else {
4843 s.lane_clips(l).iter().find(|c| c.start < at && at < c.end()).map(|c| c.start)
4844 };
4845 lanes.push(l);
4846 touched.extend(start.map(|st| (l, st)));
4847 }
4848 let names: Vec<String> = lanes.iter().map(|&l| parse::lane_name(l)).collect();
4849 Ok(Done { text: format!("regroup {shown}: the cut is rejoined on {}", names.join(", ")), touched, lanes })
4850}
4851
4852/// How many placements a lane holds: its clips, or its captions for a subtitle lane.
4853fn placements(s: &PlaybackSession, lane: Lane) -> usize {
4854 if lane.kind == LaneKind::Subtitle { s.sub_lane(lane).len() } else { s.lane_clips(lane).len() }
4855}
4856
4857/// `solo {lane, on}`: solos an audio lane for listening, so only the soloed lanes are heard while this
4858/// session plays. Solo is monitoring only: it is not project state, it is not saved, and an export never
4859/// reads it, so it leaves no undo step and marks nothing changed.
4860fn op_solo(s: &mut PlaybackSession, op: &Value) -> Result<Done, String> {
4861 let lane = lane_arg(op, "lane")?.ok_or("missing `lane`: give an audio lane such as A1")?;
4862 let name = parse::lane_name(lane);
4863 if lane.kind != LaneKind::Audio {
4864 return Err(format!("solo {name}: only audio lanes solo, and {name} is not one"));
4865 }
4866 let on = match op.get("on") {
4867 Some(Value::Bool(b)) => *b,
4868 None | Some(Value::Null) => return Err("missing `on`: true solos the lane, false un-solos it".into()),
4869 Some(_) => return Err("`on` must be true or false".into()),
4870 };
4871 let mut solo: Vec<Lane> = s.soloed().to_vec();
4872 if on {
4873 if !solo.contains(&lane) {
4874 solo.push(lane);
4875 }
4876 } else {
4877 solo.retain(|&l| l != lane);
4878 }
4879 let changed = s.set_solo(&solo);
4880 let text = if s.soloed().is_empty() {
4881 format!("solo {name}: {}", if changed { "solo cleared, every audio lane plays" } else { "no solo to clear" })
4882 } else {
4883 let names: Vec<String> = s.soloed().iter().map(|&l| parse::lane_name(l)).collect();
4884 let state = if changed { "soloed" } else { "already soloed" };
4885 format!("solo {name}: {state}; only {} play while listening (monitoring only: not saved, not exported)", names.join(", "))
4886 };
4887 Ok(Done { text, touched: Vec::new(), lanes: Vec::new() })
4888}
4889
4890/// The ramp shape `preset` names, or None when it is absent. The names are the speed card's chips.
4891fn preset_arg(op: &Value) -> Result<Option<engine::project::SpeedRampShape>, String> {
4892 let Some(v) = op.get("preset").filter(|v| !v.is_null()) else { return Ok(None) };
4893 let t = v.as_str().ok_or("`preset` must be one of speed_up, slow_down, fast_middle, slow_middle")?;
4894 engine::project::SpeedRampShape::ALL
4895 .into_iter()
4896 .find(|shape| shape.name() == t)
4897 .map(Some)
4898 .ok_or_else(|| format!("`preset` {t} is not one of speed_up, slow_down, fast_middle, slow_middle"))
4899}
4900
4901/// `copy_paste {clips:[addr...], at, lane?}`: the GUI's copy and paste, through the same engine doors.
4902/// One clip goes in as the GUI's single paste does (`paste_at`: it splits the clip under `at` and ripples
4903/// the room open). Several, or any clip with `lane`, go in as one set (`paste_set_at`): each keeps its
4904/// own lane and its spacing from the others, and the set is refused whole rather than opening room.
4905/// `lane` puts every copy on that lane, which must be the kind (V or A) of each copied clip.
4906fn op_copy_paste(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Done, String> {
4907 let at = need(op, "at", fps, end)?;
4908 let shown = shown_time(op.get("at"), at);
4909 let raw = op
4910 .get("clips")
4911 .and_then(Value::as_array)
4912 .filter(|a| !a.is_empty())
4913 .ok_or("missing `clips`: give the clip addresses to copy, e.g. [\"V1@0\", \"A1@0\"]")?;
4914 let mut picks: Vec<(Lane, usize)> = Vec::with_capacity(raw.len());
4915 for v in raw {
4916 let addr = v.as_str().ok_or("`clips` lists clip addresses such as \"V1@0\"")?;
4917 let (lane, idx) = clip_addr(s, addr).map_err(|e| format!("copy_paste clips: {e}"))?;
4918 if lane.kind == LaneKind::Subtitle {
4919 return Err(format!("{addr} is a caption lane; copy_paste takes media clips"));
4920 }
4921 if !picks.contains(&(lane, idx)) {
4922 picks.push((lane, idx));
4923 }
4924 }
4925 let target = lane_arg(op, "lane")?;
4926 let mut items: Vec<(Lane, Clip)> = picks.iter().map(|&(l, i)| (l, s.lane_clips(l)[i].clone())).collect();
4927 if let Some(to) = target {
4928 if let Some(&(l, _)) = items.iter().find(|(l, _)| l.kind != to.kind) {
4929 return Err(format!(
4930 "copy_paste: {} is on {} and `lane` {} is not, so the copy would not go there; name a lane of the same kind",
4931 parse::lane_name(l),
4932 if l.kind == LaneKind::Audio { "a sound lane" } else { "a picture lane" },
4933 parse::lane_name(to)
4934 ));
4935 }
4936 for item in &mut items {
4937 item.0 = to;
4938 }
4939 }
4940 let mut locks: Vec<Lane> = picks.iter().map(|&(l, _)| l).collect();
4941 locks.extend(target);
4942 check_unlocked(s, &locks)?;
4943 // The clips already there, as (lane, source, in, out): what the paste adds is read by difference.
4944 let key = |l: Lane, c: &Clip| (l, c.source, c.in_frame, c.out_frame);
4945 let before: Vec<(Lane, usize, u32, u32)> = s.lanes().into_iter().flat_map(|l| s.lane_clips(l).iter().map(move |c| key(l, c)).collect::<Vec<_>>()).collect();
4946 let shape_before = shape(s);
4947 let pasted = match items.as_slice() {
4948 [(_, clip)] if target.is_none() => s.paste_at(parse::secs(at, fps), clip.clone()),
4949 _ => s.paste_set_at(parse::secs(at, fps), &items),
4950 };
4951 if !pasted {
4952 let why = if items.len() > 1 || target.is_some() {
4953 format!("the set would land on a clip on its lane at {shown} (a set-paste opens no room)")
4954 } else {
4955 format!("the clip would not go in at {shown}")
4956 };
4957 return Err(format!("copy_paste refused: {why}; nothing changed"));
4958 }
4959 // The copies are the clips the paste added: the before list minus what is still there, by key.
4960 let mut pending = before;
4961 let mut landed: Vec<(Lane, u32)> = Vec::new();
4962 for l in s.lanes() {
4963 for c in s.lane_clips(l) {
4964 match pending.iter().position(|k| *k == key(l, c)) {
4965 Some(p) => {
4966 pending.swap_remove(p);
4967 }
4968 None => landed.push((l, c.start)),
4969 }
4970 }
4971 }
4972 let addrs: Vec<String> = landed.iter().map(|&(l, start)| parse::addr(l, start)).collect();
4973 let effects = side_effects(&shape_before, &shape(s), "copy_paste");
4974 // A paste past the end is clamped to the end, so the copies append there; say so rather than
4975 // print an asked frame the copies did not land on.
4976 let mut text = if at > end {
4977 format!(
4978 "copy_paste {} clip(s) at {shown} is past the end, so the copies append at {:.3}s ({end}f): pasted {}",
4979 items.len(),
4980 parse::secs(end, fps),
4981 addrs.join(", ")
4982 )
4983 } else {
4984 format!("copy_paste {} clip(s) at {shown}: pasted {}", items.len(), addrs.join(", "))
4985 };
4986 if !effects.is_empty() {
4987 text.push_str(&format!("; effects: {}", effects.join("; ")));
4988 }
4989 let lanes: Vec<Lane> = landed.iter().map(|&(l, _)| l).collect();
4990 Ok(Done { text, touched: landed, lanes })
4991}
4992
4993/// Where the last clip or caption on `lane` ends, in timeline frames (0 for an empty lane).
4994fn lane_end(s: &PlaybackSession, lane: Lane) -> u32 {
4995 if lane.kind == LaneKind::Subtitle {
4996 s.sub_lane(lane).iter().map(|c| c.start + c.frames).max().unwrap_or(0)
4997 } else {
4998 s.lane_clips(lane).iter().map(|c| c.end()).max().unwrap_or(0)
4999 }
5000}
5001
5002/// The engine's CUT_SLIVER_FRAMES (crates/engine/src/project.rs): a kept piece shorter than this
5003/// between two cuts is a sliver no one can read, so the cuts either side of it are joined.
5004pub(crate) const CUT_SLIVER_FRAMES: u32 = 4;
5005
5006/// Joins cut spans `(start, len)` that leave under [`CUT_SLIVER_FRAMES`] of kept picture between
5007/// them (or overlap). Returns the spans, sorted, and how many kept pieces were joined away.
5008pub(crate) fn join_slivers(spans: &[(u32, u32)]) -> (Vec<(u32, u32)>, usize) {
5009 let mut v: Vec<(u64, u64)> = spans.iter().map(|&(a, len)| (u64::from(a), u64::from(a) + u64::from(len))).collect();
5010 v.sort_unstable();
5011 let sliver = u64::from(CUT_SLIVER_FRAMES);
5012 let mut out: Vec<(u64, u64)> = Vec::with_capacity(v.len());
5013 let mut joined = 0;
5014 for (a, b) in v {
5015 match out.last_mut() {
5016 Some(last) if a < last.1 + sliver => {
5017 if a > last.1 {
5018 joined += 1;
5019 }
5020 last.1 = last.1.max(b);
5021 }
5022 _ => out.push((a, b)),
5023 }
5024 }
5025 (out.into_iter().map(|(a, b)| (a as u32, (b - a) as u32)).collect(), joined)
5026}
5027
5028/// Closes the holes a cut left under [`CUT_SLIVER_FRAMES`] on the unlocked media lanes of `scope`.
5029/// A hole is closed by trimming a clip beside it (the clip after it starts earlier, or the clip
5030/// before it runs on), never by moving the clips after it: the cut then removes exactly the frames
5031/// it was asked for. A hole at the very start is no hole. `Ok(None)` when there is nothing to
5032/// close; otherwise the reply's note, or the error that kept the holes open (the holes it did
5033/// close stay closed).
5034pub(crate) fn close_sliver_holes(
5035 s: &mut PlaybackSession,
5036 scope: &[Lane],
5037 fps: f64,
5038 _moved: &mut Vec<String>,
5039) -> Result<Option<String>, String> {
5040 let mut lanes: Vec<String> = Vec::new();
5041 let mut closed = 0;
5042 let mut open: Vec<String> = Vec::new();
5043 for &l in scope {
5044 if l.kind == LaneKind::Subtitle || s.lane_locked(l) {
5045 continue;
5046 }
5047 let mut named = false;
5048 // Each pass closes the first hole left on the lane, then reads the lane again: one trim can
5049 // close a hole or move the next one, and a take partner's trim may have closed this one already.
5050 // A hole no trim can close is named and left, and the pass moves on to the next lane.
5051 let mut stuck: Vec<(u32, u32)> = Vec::new();
5052 while let Some((a, b)) = gaps_of(s, l)
5053 .into_iter()
5054 .filter(|&(_, a, b)| a > 0 && b - a < CUT_SLIVER_FRAMES)
5055 .map(|(_, a, b)| (a, b))
5056 .find(|h| !stuck.contains(h))
5057 {
5058 if !named {
5059 named = true;
5060 lanes.push(parse::lane_name(l));
5061 }
5062 let next = s.lane_clips(l).iter().position(|c| c.start == b);
5063 let prev = s.lane_clips(l).iter().position(|c| c.end() == a);
5064 if next.is_some_and(|i| s.trim_clip(l, i, Edge::Start, a)) || prev.is_some_and(|i| s.trim_clip(l, i, Edge::End, b)) {
5065 closed += 1;
5066 } else {
5067 stuck.push((a, b));
5068 open.push(format!("{} {}–{}", parse::addr(l, a), secs_text(a, fps), secs_text(b, fps)));
5069 }
5070 }
5071 }
5072 if lanes.is_empty() {
5073 return Ok(None);
5074 }
5075 if !open.is_empty() {
5076 return Err(format!("no clip beside {} can be trimmed into the hole", open.join(", ")));
5077 }
5078 Ok(Some(format!("; closed {closed} hole(s) under {CUT_SLIVER_FRAMES}f on {} by trimming the clip beside each", lanes.join(", "))))
5079}
5080
5081/// The note for a [`close_sliver_holes`] that could not close: the holes stay, and the reason.
5082pub(crate) fn sliver_note(r: Result<Option<String>, String>) -> String {
5083 match r {
5084 Ok(note) => note.unwrap_or_default(),
5085 Err(e) => format!("; sliver holes left open: {e}"),
5086 }
5087}
5088
5089/// Whether a clip or caption on one of `scope`'s lanes lies in any of the `spans` ((start, length) pairs).
5090fn scope_content_in(s: &PlaybackSession, scope: &[Lane], spans: &[(u32, u32)]) -> bool {
5091 spans.iter().any(|&(a, len)| {
5092 let b = a + len;
5093 scope.iter().any(|&l| {
5094 if l.kind == LaneKind::Subtitle {
5095 s.sub_lane(l).iter().any(|c| c.start < b && a < c.end())
5096 } else {
5097 s.lane_clips(l).iter().any(|c| c.start < b && a < c.end())
5098 }
5099 })
5100 })
5101}
5102
5103fn op_cut_regions(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result<Done, String> {
5104 let list = op
5105 .get("regions")
5106 .and_then(Value::as_array)
5107 .filter(|r| !r.is_empty())
5108 .ok_or("missing `regions`: give [[from,to], ...] times")?;
5109 let mut spans: Vec<(u32, u32)> = Vec::with_capacity(list.len());
5110 for (i, r) in list.iter().enumerate() {
5111 let pair = r
5112 .as_array()
5113 .filter(|p| p.len() == 2)
5114 .ok_or_else(|| format!("regions[{i}] must be [from,to]"))?;
5115 let a = parse::frame(&pair[0], fps, end).map_err(|e| format!("regions[{i}] from: {e}"))?;
5116 let b = parse::frame(&pair[1], fps, end).map_err(|e| format!("regions[{i}] to: {e}"))?;
5117 if b <= a {
5118 return Err(format!("regions[{i}]: to ({b}f) must be after from ({a}f)"));
5119 }
5120 spans.push((a, b - a));
5121 }
5122 let (spans, joined) = join_slivers(&spans);
5123 let from = spans.iter().map(|p| p.0).min().unwrap_or(0);
5124 let (scope, guard_skipped) = match lane_list(op, "lanes")? {
5125 Some(v) => {
5126 check_unlocked(s, &v)?;
5127 (v, Vec::new())
5128 }
5129 None => {
5130 let unlocked: Vec<Lane> = s.lanes().into_iter().filter(|&l| !s.lane_locked(l)).collect();
5131 let cuts: Vec<u32> = spans.iter().flat_map(|&(a, len)| [a, a + len]).collect();
5132 ripple_guard(s, &unlocked, from, &cuts, true)?
5133 }
5134 };
5135 let end_before = end;
5136 s.cut_regions(&spans, &scope).map_err(|e| e.to_string())?;
5137 let mut moved = if has_picture(&scope) { move_titles_for_cuts(s, &spans, fps)? } else { Vec::new() };
5138 let closed = sliver_note(close_sliver_holes(s, &scope, fps, &mut moved));
5139 // Nothing on the scope lanes lies in a span and nothing else moved: the reply says so, since the
5140 // batch then reads as no change (its reason is taken from this text).
5141 let mut text = if !scope_content_in(s, &scope, &spans) && moved.is_empty() && closed.is_empty() {
5142 let names: Vec<String> = scope.iter().map(|&l| parse::lane_name(l)).collect();
5143 format!("cut_regions {} span(s): nothing to cut, nothing on {} lies in the span(s)", spans.len(), names.join(", "))
5144 } else {
5145 format!("cut_regions {} span(s){}{closed}", spans.len(), titles_note(&moved))
5146 };
5147 text.push_str(&left_behind(s, &scope, from));
5148 text.push_str(&skipped_note(&guard_skipped));
5149 if joined > 0 {
5150 text.push_str(&format!(
5151 "; joined {joined} cut(s) across kept pieces under {CUT_SLIVER_FRAMES}f (a sliver that short cannot be read)"
5152 ));
5153 }
5154 // A title that runs past the cut keeps the timeline where it was: say which one.
5155 let new_end = parse::session_end(s);
5156 if new_end > 0 && spans.iter().any(|&(a, len)| a.saturating_add(len) >= end_before)
5157 && let Some((i, t)) = s.titles().iter().enumerate().find(|(_, t)| t.start.saturating_add(t.frames) >= new_end)
5158 {
5159 text.push_str(&format!(
5160 "; timeline still {}: T{} runs to {}",
5161 secs_text(new_end, fps),
5162 i + 1,
5163 secs_text(t.start.saturating_add(t.frames), fps)
5164 ));
5165 }
5166 Ok(Done { text, touched: ripple_touched(s, &scope, from), lanes: scope })
5167}
5168
5169// ---- time and look (speed, fades, transitions) -----------------------------
5170
5171/// `reverse {clip, on?}`: the clip and its take play backward, or forward again. `on` is explicit,
5172/// or absent to toggle. The length and place do not change, so nothing ripples.
5173fn op_reverse(s: &mut PlaybackSession, op: &Value) -> Result<Done, String> {
5174 let (lane, idx) = clip_arg(s, op)?;
5175 let addr = addr_of(s, lane, idx);
5176 let on = match op.get("on") {
5177 None | Some(Value::Null) => None,
5178 Some(Value::Bool(b)) => Some(*b),
5179 Some(_) => return Err("`on` must be true or false".into()),
5180 };
5181 let now = s.reversed_of(lane, idx);
5182 let want = on.unwrap_or(!now);
5183 check_unlocked(s, &take_lanes(s, lane, idx))?;
5184 if want == now {
5185 let state = if now { "reversed" } else { "forward" };
5186 return Ok(plain(format!("reverse {addr}: already {state}"), Vec::new()));
5187 }
5188 s.set_reverse(lane, idx, want).map_err(|e| format!("reverse {addr} refused: {e}"))?;
5189 let touched: Vec<(Lane, u32)> = take_of(s, lane, idx)
5190 .into_iter()
5191 .filter_map(|(l, i)| s.lane_clips(l).get(i).map(|c| (l, c.start)))
5192 .collect();
5193 let state = if want { "plays backward" } else { "plays forward again" };
5194 Ok(plain(format!("reverse {addr}: the clip {state}"), touched))
5195}
5196
5197/// `beats {clip, every?}`: listens to a clip's sound for its beat, and marks every `every`th beat
5198/// (1 by default; 2 or 4 for bars) as a yellow comment marker noted "Beat". The clip's earlier beat
5199/// markers are taken off first, so a second run replaces the first rather than doubling it.
5200fn op_beats(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Done, String> {
5201 let (lane, idx) = clip_arg(s, op)?;
5202 let addr = addr_of(s, lane, idx);
5203 let every = match op.get("every") {
5204 None | Some(Value::Null) => 1,
5205 Some(v) => v
5206 .as_u64()
5207 .filter(|n| (1..=64).contains(n))
5208 .ok_or("beats: `every` is a whole number of beats, 1 for every beat, 2 or 4 for bars")? as usize,
5209 };
5210 let clip = s.lane_clips(lane).get(idx).cloned().ok_or_else(|| format!("beats {addr}: no such clip"))?;
5211 let src = s
5212 .sources()
5213 .get(clip.source)
5214 .ok_or_else(|| format!("beats {addr}: a clip uses src:{}, which is not on the timeline", clip.source))?;
5215 let range = (f64::from(clip.in_frame) / fps, f64::from(clip.out_frame) / fps);
5216 let found = beats::detect(&src.path, src.audio_stream, range)
5217 .map_err(|e| format!("beats {addr}: reading the sound of src:{}: {e}", clip.source))?;
5218 let (bpm, times) = match found {
5219 Found::Beats { bpm, times } => (bpm, times),
5220 Found::NoAudio => return Err(format!("beats {addr}: src:{} has no sound; pick a clip with sound", clip.source)),
5221 Found::Silent => return Err(format!("beats {addr}: the sound is silent, so there is no beat to mark")),
5222 Found::NoPulse => return Err(format!("beats {addr}: no steady beat in the sound to keep time to")),
5223 };
5224 let frames = beats::timeline_beats(&clip, fps, &beats::every_nth(&times, every));
5225 let old = beats::beat_marker_indices(s.markers(), clip.start, clip.end());
5226 for &i in old.iter().rev() {
5227 s.remove_marker(i);
5228 }
5229 for &f in &frames {
5230 s.add_marker(beats::beat_marker(f)).map_err(|e| format!("beats {addr}: {e}"))?;
5231 }
5232 let names: Vec<String> = frames.iter().map(|f| format!("M@{f}")).collect();
5233 let listed = match names.len() {
5234 0 => "none".to_string(),
5235 n if n <= 24 => names.join(", "),
5236 n => format!("{} … {} (and {} more)", names[..12].join(", "), names[n - 1], n - 12 - 1),
5237 };
5238 let text = format!(
5239 "beats {addr}: {bpm:.1} BPM; {} beat markers (every {every}) at {listed}, replacing {} earlier; markers: {}",
5240 frames.len(),
5241 old.len(),
5242 marker_names(s)
5243 );
5244 Ok(plain(text, vec![(lane, clip.start)]))
5245}
5246
5247/// `speed {clip, x, ripple?}`. Without `ripple` a clip that would grow into its neighbour
5248/// refuses. With it the later items on the unlocked lanes move by the length change, as
5249/// `insert_time` (slower) or `cut_regions` (faster) would move them, and titles move with them.
5250fn op_speed(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Done, String> {
5251 let (lane, idx) = clip_arg(s, op)?;
5252 let addr = addr_of(s, lane, idx);
5253 let x = match op.get("x") {
5254 None | Some(Value::Null) => return Err("missing `x`: give a speed between 0.25 and 4".into()),
5255 Some(v) => v.as_f64().ok_or_else(|| format!("`x` must be a number between 0.25 and 4, not {v}"))?,
5256 };
5257 if !(0.25..=4.0).contains(&x) {
5258 return Err(format!("speed {} is outside 0.25–4", compact(x)));
5259 }
5260 let speed = Speed::from_permille((x * 1000.0).round() as u16);
5261 check_unlocked(s, &take_lanes(s, lane, idx))?;
5262 let new_frames = speed.frames(s.lane_clips(lane)[idx].len());
5263 let label = format!("speed {addr} ×{}", compact(x));
5264 let why = format!("at {x:.2}x");
5265 retime_clip(s, op, fps, lane, idx, &label, &why, new_frames, &|s: &mut PlaybackSession| {
5266 s.set_speed(lane, idx, speed).map_err(|e| e.to_string())
5267 })
5268}
5269
5270/// `speed_ramp {clip, keys:[{at, speed}...], ripple?, lanes?}`: a speed that changes over the clip.
5271/// Each key is a speed (0.25–4) at a clip-relative time `at` ("0s", "2s", "end" for the clip's own
5272/// length, or frames); the speed is linear between keys and holds before the first and after the
5273/// last. Empty `keys` clears the ramp, and the clip takes its constant speed again. Its length
5274/// follows from the ramp, and `ripple` moves the later clips as `speed` does.
5275fn op_speed_ramp(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Done, String> {
5276 let (lane, idx) = clip_arg(s, op)?;
5277 let addr = addr_of(s, lane, idx);
5278 check_unlocked(s, &take_lanes(s, lane, idx))?;
5279 let clip = s.lane_clips(lane)[idx].clone();
5280 let clip_frames = clip.frames();
5281 let mut keys: Vec<engine::project::SpeedKey> = Vec::new();
5282 match preset_arg(op)? {
5283 // A preset lays the speed card's shape across the clip's length, as the card's chip does.
5284 Some(shape) => {
5285 if op.get("keys").is_some_and(|v| !v.is_null()) {
5286 return Err("speed_ramp takes `keys` or `preset`, not both".into());
5287 }
5288 keys = shape.keys(clip_frames).ok_or_else(|| {
5289 format!("speed_ramp {addr}: the clip is too short for {} (it needs at least 2 frames)", shape.name())
5290 })?;
5291 }
5292 None => {
5293 let raw = match op.get("keys") {
5294 None | Some(Value::Null) => return Err("missing `keys`: give a list of {at, speed}, a `preset` (speed_up, slow_down, fast_middle, slow_middle), or [] to clear the ramp".into()),
5295 Some(Value::Array(a)) => a,
5296 Some(_) => return Err("`keys` must be a list of {at, speed} objects".into()),
5297 };
5298 if raw.len() > engine::project::MAX_SPEED_KEYS {
5299 return Err(format!("a speed ramp takes at most {} keys", engine::project::MAX_SPEED_KEYS));
5300 }
5301 for k in raw {
5302 let at = k.get("at").ok_or_else(|| "each key needs `at`: a time such as 0s, 2s or end".to_string())?;
5303 let at = parse::frame(at, fps, clip_frames)?;
5304 let speed = match k.get("speed") {
5305 None | Some(Value::Null) => return Err("each key needs `speed`: a number between 0.25 and 4".into()),
5306 Some(v) => v.as_f64().ok_or_else(|| format!("`speed` must be a number between 0.25 and 4, not {v}"))?,
5307 };
5308 if !(0.25..=4.0).contains(&speed) {
5309 return Err(format!("speed {} is outside 0.25–4", compact(speed)));
5310 }
5311 keys.push(engine::project::SpeedKey { at, speed: Speed::from_permille((speed * 1000.0).round() as u16) });
5312 }
5313 }
5314 }
5315 if !keys.is_empty() && !engine::project::valid_speed_keys(&keys) {
5316 return Err("speed ramp keys must be in strictly increasing order of `at`, one per time".into());
5317 }
5318 let new_frames = if keys.is_empty() {
5319 clip.speed.frames(clip.len())
5320 } else {
5321 engine::project::ramp_frames(&keys, clip.len())
5322 };
5323 let label = format!("speed ramp {addr}");
5324 let why = "with that ramp".to_string();
5325 let shown = keys.clone();
5326 retime_clip(s, op, fps, lane, idx, &label, &why, new_frames, &|s: &mut PlaybackSession| {
5327 s.set_speed_ramp(lane, idx, &shown).map_err(|e| e.to_string())
5328 })
5329}
5330
5331/// The shared body of a clip's re-timing ops (`speed`, `speed_ramp`): the length change
5332/// `new_frames` names, refused or rippled as the op asks, then `apply` makes the change.
5333/// `label` opens every reply and refusal, and `why` says what the clip would run at.
5334#[allow(clippy::too_many_arguments)]
5335fn retime_clip(
5336 s: &mut PlaybackSession,
5337 op: &Value,
5338 fps: f64,
5339 lane: Lane,
5340 idx: usize,
5341 label: &str,
5342 why: &str,
5343 new_frames: u32,
5344 apply: &dyn Fn(&mut PlaybackSession) -> Result<(), String>,
5345) -> Result<Done, String> {
5346 let ripple = match op.get("ripple") {
5347 None | Some(Value::Null) => false,
5348 Some(Value::Bool(b)) => *b,
5349 Some(_) => return Err("`ripple` must be true or false".into()),
5350 };
5351 let clip = s.lane_clips(lane)[idx].clone();
5352 let old_end = clip.end();
5353 let new_end = clip.start + new_frames;
5354 // The length change, named in the reply: "4.0s → 5.2s".
5355 let len_text = format!(
5356 " ({:.3}s → {:.3}s)",
5357 parse::secs(old_end - clip.start, fps),
5358 parse::secs(new_end - clip.start, fps)
5359 );
5360 if !ripple {
5361 if let Some(next) = s.lane_clips(lane).get(idx + 1).map(|c| c.start).filter(|&n| new_end > n) {
5362 return Err(format!(
5363 "{label} refused: {why} that clip would run to frame {new_end} and the next {} clip starts at {next}: add ripple:true to move the later clips along by the length change, or trim this one first",
5364 parse::lane_name(lane)
5365 ));
5366 }
5367 apply(s)?;
5368 let touched = s.lane_clips(lane).get(idx).map(|c| vec![(lane, c.start)]).unwrap_or_default();
5369 return Ok(plain(format!("{label}{len_text}"), touched));
5370 }
5371 // The change runs over [from, to): the frames the clip gives up when it is shortened, or the
5372 // point a slower clip opens room at. The edited clip and its take are retimed together, so only
5373 // other clips are checked.
5374 let (from, to) = if new_end > old_end { (old_end, old_end) } else { (new_end, old_end) };
5375 let take = take_of(s, lane, idx);
5376 let sc = rip_scope(s, op, &[(lane, idx)], old_end.min(new_end))?;
5377 let spanners = region_spanners(s, &take, &sc.lanes, from, to);
5378 if let Some(&(l, st, _)) = spanners.iter().find(|x| x.2) {
5379 return Err(format!(
5380 "{label} ripple refused: {} spans the change ({:.3}s–{:.3}s) and would be cut; trim or split it first, or take its lane out of lanes",
5381 parse::addr(l, st),
5382 parse::secs(old_end.min(new_end), fps),
5383 parse::secs(old_end.max(new_end), fps)
5384 ));
5385 }
5386 // A clip on a lane outside the scope spans the change: it is left in place, and the reply says so.
5387 let mut left: Vec<String> = spanners
5388 .iter()
5389 .filter(|x| !x.2)
5390 .map(|&(l, st, _)| format!("{} spans the change and was left in place", parse::addr(l, st)))
5391 .collect();
5392 // Whether any scope item starts at or after the change, so a move is said only when something moved.
5393 // The sped clip and its take (the clips starting where it starts, on its take's lanes) are retimed
5394 // in place, so they are never a later item.
5395 let take_lanes: Vec<Lane> = take.iter().map(|&(l, _)| l).collect();
5396 let own = |l: Lane, st: u32| st == clip.start && take_lanes.contains(&l);
5397 let later = sc.lanes.iter().any(|&l| {
5398 if l.kind == LaneKind::Subtitle {
5399 s.sub_lane(l).iter().any(|c| c.start >= from)
5400 } else {
5401 s.lane_clips(l).iter().any(|c| c.start >= from && !own(l, c.start))
5402 }
5403 });
5404 if new_end > old_end {
5405 // Slower: open the room at the old end on the scope lanes first (as insert_time does, titles
5406 // included), then retime, which now fits.
5407 let room = new_end - old_end;
5408 let shown = (format!("{old_end}f"), format!("{room}f"));
5409 let made = insert_span(s, old_end, room, &sc, fps, shown).map_err(|e| format!("{label} ripple: {e}"))?;
5410 apply(s)?;
5411 let mut touched = made.touched;
5412 touched.extend(s.lane_clips(lane).get(idx).map(|c| (lane, c.start)));
5413 let moved = if later { format!("; later items moved {room}f ({:.3}s) later", room as f64 / fps) } else { String::new() };
5414 let mut text = format!("{label}{len_text}{moved}{}", skipped_note(&sc.skipped));
5415 push_left(&mut text, &mut left);
5416 return Ok(Done { text, touched, lanes: made.lanes });
5417 }
5418 // Faster, or the same: retime, then close the gap it leaves in the ripple scope.
5419 apply(s)?;
5420 let gap = old_end - new_end;
5421 let mut text = format!("{label}{len_text}");
5422 let mut touched = Vec::new();
5423 if gap > 0 {
5424 check_unlocked(s, &sc.lanes)?;
5425 let span = [(new_end, gap)];
5426 let (cues_gone, cues_cut) = cues_in_span(s, &sc.lanes, new_end, old_end, fps);
5427 s.cut_regions(&span, &sc.lanes).map_err(|e| e.to_string())?;
5428 let cues_cut = trimmed_cue_lines(s, &cues_cut);
5429 let moved = if has_picture(&sc.lanes) { move_titles_for_cuts(s, &span, fps)? } else { Vec::new() };
5430 if later {
5431 text.push_str(&format!("; later items moved {gap}f ({:.3}s) earlier", gap as f64 / fps));
5432 }
5433 text.push_str(&titles_note(&moved));
5434 text.push_str(&cue_cut_text(&cues_gone, &cues_cut));
5435 text.push_str(&skipped_note(&sc.skipped));
5436 touched = ripple_touched(s, &sc.lanes, new_end);
5437 }
5438 push_left(&mut text, &mut left);
5439 touched.extend(s.lane_clips(lane).get(idx).map(|c| (lane, c.start)));
5440 Ok(plain(text, touched))
5441}
5442
5443/// Appends the clips a ripple left in place, each as its own `; ...` clause.
5444fn push_left(text: &mut String, left: &mut Vec<String>) {
5445 for l in left.drain(..) {
5446 text.push_str(&format!("; {l}"));
5447 }
5448}
5449
5450/// The clips a change over `[from, to)` runs across: each media clip starting before `to` and
5451/// ending after `from`, other than `skip` (the edited clip and its take). `(lane, start, in scope)`.
5452/// A clip wholly inside the span counts too, since the span would cut it away.
5453fn region_spanners(s: &PlaybackSession, skip: &[(Lane, usize)], scope: &[Lane], from: u32, to: u32) -> Vec<(Lane, u32, bool)> {
5454 let mut out = Vec::new();
5455 for l in s.lanes() {
5456 if l.kind == LaneKind::Subtitle {
5457 continue;
5458 }
5459 for (i, c) in s.lane_clips(l).iter().enumerate() {
5460 if !skip.contains(&(l, i)) && c.start < to && c.end() > from {
5461 out.push((l, c.start, scope.contains(&l)));
5462 }
5463 }
5464 }
5465 out
5466}
5467
5468/// A timeline frame as seconds for a reply: `12.0s`, or `12.52s` when a tenth is not exact.
5469fn secs_text(frame: u32, fps: f64) -> String {
5470 let v = parse::secs(frame, fps);
5471 if (v * 10.0 - (v * 10.0).round()).abs() < 1e-6 {
5472 format!("{v:.1}s")
5473 } else {
5474 format!("{v:.2}s")
5475 }
5476}
5477
5478/// A seconds time as the caller wrote it, for a reply: the string as given, or a number with `s`.
5479fn shown_secs(v: &Value) -> String {
5480 match v {
5481 Value::String(t) => t.trim().to_string(),
5482 _ => format!("{v}s"),
5483 }
5484}
5485
5486/// Adds to an overlap refusal the seconds that rounded to whole frames. A seconds `at`, `in`, `out`
5487/// or `length` lands on a frame, so the clip can sit a frame off what the seconds say. Each value
5488/// that rounded is named with the math and the frame it became; the frame form is the exact way to
5489/// give it. A refusal where nothing rounded, and any other refusal, are returned as they are.
5490fn overlap_rounding_note(e: String, op: &Value, at: u32, len: Option<u32>, src_fps: f64, fps: f64) -> String {
5491 if !(e.contains("would overlap") || e.contains("would overwrite")) {
5492 return e;
5493 }
5494 let mut why: Vec<String> = Vec::new();
5495 let mut frames: Vec<String> = Vec::new();
5496 let mut fix: Vec<String> = Vec::new();
5497 // `at` in seconds: the timeline frame it lands on, read in timeline frames.
5498 if let Some(v) = op.get("at")
5499 && let Some(secs) = seconds_arg(v)
5500 {
5501 let exact = secs * fps;
5502 if (exact - exact.round()).abs() > 1e-6 {
5503 why.push(format!(
5504 "at {} is {exact:.3}f, which rounds to {at}f ({:.3}s)",
5505 shown_secs(v),
5506 parse::secs(at, fps)
5507 ));
5508 frames.push(format!("at \"{at}f\""));
5509 }
5510 }
5511 // `in` and `out` in seconds: the source frame they read, in the source's own rate.
5512 for key in ["in", "out"] {
5513 let Some(v) = op.get(key) else { continue };
5514 let Some(secs) = seconds_arg(v) else { continue };
5515 let exact = secs * src_fps;
5516 if (exact - exact.round()).abs() <= 1e-6 {
5517 continue;
5518 }
5519 // The same rounding source_time uses, so the frame named here is the one the op stored.
5520 let n = (exact + 0.5 + 1e-6).floor() as u32;
5521 why.push(format!("{key} {} is {exact:.3}f at {src_fps} fps, which rounds to {n}f", shown_secs(v)));
5522 frames.push(format!("{key} \"{n}f\""));
5523 }
5524 // `length` in seconds: rounded up or down to whole frames, so the clip ends a frame off.
5525 if let (Some(len), Some(given)) = (len, op.get("length").filter(|v| !v.is_u64()))
5526 && let Some(secs) = seconds_arg(given)
5527 {
5528 let gap = f64::from(len) - secs * fps;
5529 if gap.abs() > 1e-6 {
5530 let verb = if gap > 0.0 { "rounds up to" } else { "rounds down to" };
5531 why.push(format!(
5532 "length {} {verb} {len}f ({:.3}s) and ends at {}f",
5533 shown_secs(given),
5534 parse::secs(len, fps),
5535 at + len
5536 ));
5537 fix.push(if len > 1 {
5538 format!("give length in frames (e.g. \"{}f\") or start 1 frame later", len - 1)
5539 } else {
5540 "give length in frames or start 1 frame later".to_string()
5541 });
5542 }
5543 }
5544 if why.is_empty() {
5545 return e;
5546 }
5547 if !frames.is_empty() {
5548 fix.insert(0, format!("write {} in frames, or move it clear of the clip it would overlap", frames.join(" and ")));
5549 }
5550 format!("{e}. {}; {}", why.join("; "), fix.join("; "))
5551}
5552
5553/// A speed factor for a reply, to three decimals with the zeros trimmed: `0.309`, `2`.
5554fn speed_text(x: f64) -> String {
5555 let s = format!("{x:.3}");
5556 s.trim_end_matches('0').trim_end_matches('.').to_string()
5557}
5558
5559/// What a speed factor means in words: slow motion below 1, sped up above; empty at 1.
5560fn speed_note(x: f64) -> &'static str {
5561 let rounded: f64 = speed_text(x).parse().unwrap_or(x);
5562 if rounded < 1.0 {
5563 " (slow motion)"
5564 } else if rounded > 1.0 {
5565 " (sped up)"
5566 } else {
5567 ""
5568 }
5569}
5570
5571/// A number for a reply: plain, or in exponent form when it is huge or tiny, so 1e300 stays short.
5572fn compact(x: f64) -> String {
5573 if x != 0.0 && (x.abs() >= 1e6 || x.abs() < 1e-3) {
5574 format!("{x:e}")
5575 } else {
5576 x.to_string()
5577 }
5578}
5579
5580/// Whether a fade or dissolve also reaches the clip's linked partners: true unless `linked` is false.
5581fn linked_arg(op: &Value) -> Result<bool, String> {
5582 match op.get("linked") {
5583 None | Some(Value::Null) => Ok(true),
5584 Some(Value::Bool(b)) => Ok(*b),
5585 Some(_) => Err("`linked` must be true or false".into()),
5586 }
5587}
5588
5589/// The clips a fade or dissolve on `lane`/`idx` reaches: its whole take, or the clip alone with `linked:false`.
5590fn reach(s: &PlaybackSession, op: &Value, lane: Lane, idx: usize) -> Result<Vec<(Lane, usize)>, String> {
5591 Ok(if linked_arg(op)? { take_of(s, lane, idx) } else { vec![(lane, idx)] })
5592}
5593
5594/// Where each clip in `reached` starts, for the reply's touched list.
5595fn touched_of(s: &PlaybackSession, reached: &[(Lane, usize)]) -> Vec<(Lane, u32)> {
5596 reached.iter().filter_map(|&(l, i)| s.lane_clips(l).get(i).map(|c| (l, c.start))).collect()
5597}
5598
5599/// Why the clip at `idx` of `lane` cannot join the clip after it, in the words a fix needs.
5600/// None when the next clip starts exactly where this one ends.
5601fn join_problem(s: &PlaybackSession, lane: Lane, idx: usize) -> Option<String> {
5602 let clips = s.lane_clips(lane);
5603 let addr = addr_of(s, lane, idx);
5604 let name = parse::lane_name(lane);
5605 let Some(cur) = clips.get(idx) else {
5606 return Some(format!("there is no clip at {addr}"));
5607 };
5608 let Some(next) = clips.get(idx + 1) else {
5609 return Some(format!("{addr} is the last clip on {name}, so there is no clip after it"));
5610 };
5611 let gap = next.start.saturating_sub(cur.end());
5612 if gap == 0 {
5613 return None;
5614 }
5615 let between = format!("a gap of {gap}f lies between {addr} and {} at {}", addr_of(s, lane, idx + 1), parse::tc(next.start, parse::session_fps(s)));
5616 // close_gaps is named only when it would close the gap; otherwise the take's reason is.
5617 Some(match take_gap_refusal(s, lane, cur.end(), gap) {
5618 None => format!("{between}: close it with close_gaps {{lane:\"{name}\"}}, or move the clip so they meet"),
5619 Some(why) => format!("{between}: close_gaps cannot close it, {why}; or move the clip so they meet"),
5620 })
5621}
5622
5623fn op_fade(s: &mut PlaybackSession, op: &Value, fps: f64, _end: u32) -> Result<Done, String> {
5624 let (lane, idx) = clip_arg(s, op)?;
5625 let addr = addr_of(s, lane, idx);
5626 let fin = length(op, "in", fps)?;
5627 let fout = length(op, "out", fps)?;
5628 if fin.is_none() && fout.is_none() {
5629 return Err(format!("fade {addr} needs `in` and/or `out`: frames (12) or a time (\"0.5s\")"));
5630 }
5631 let reached = reach(s, op, lane, idx)?;
5632 let lanes: Vec<Lane> = reached.iter().map(|&(l, _)| l).collect();
5633 check_unlocked(s, &lanes)?;
5634 // In and out together longer than the clip would overlap: both are clamped to half of it, reported.
5635 let (mut fin, mut fout) = (fin, fout);
5636 let mut clamp_note = String::new();
5637 let len = s.lane_clips(lane).get(idx).map_or(0, |c| c.frames());
5638 if let (Some(a), Some(b)) = (fin, fout)
5639 && len > 0 && a.saturating_add(b) > len
5640 {
5641 let half = len / 2;
5642 clamp_note = format!(
5643 "; in {} + out {} are longer than the {} clip: both clamped to {}",
5644 secs_text(a, fps),
5645 secs_text(b, fps),
5646 secs_text(len, fps),
5647 secs_text(half, fps)
5648 );
5649 fin = Some(half);
5650 fout = Some(half);
5651 }
5652 let mut named = Vec::new();
5653 // What the engine kept, read back per edge: it clamps a ramp to its clip's length.
5654 let mut applied: Vec<(Option<u32>, Option<u32>)> = Vec::new();
5655 for &(l, i) in &reached {
5656 let a = addr_of(s, l, i);
5657 if let Some(f) = fin
5658 && !s.set_fade_in(l, i, f)
5659 {
5660 return Err(format!("fade in on {a} refused: no such clip"));
5661 }
5662 if let Some(f) = fout
5663 && !s.set_fade_out(l, i, f)
5664 {
5665 return Err(format!("fade out on {a} refused: no such clip"));
5666 }
5667 applied.push((fin.map(|_| s.fade_in_of(l, i)), fout.map(|_| s.fade_out_of(l, i))));
5668 named.push(a);
5669 }
5670 // The header names the frames the engine kept (the first clip speaks for the take), so a ramp
5671 // clamped to its clip's length reads as the length it got, with the asked time in the note.
5672 let (kept_in, kept_out) = applied.first().copied().unwrap_or((None, None));
5673 let mut parts = Vec::new();
5674 if let Some(f) = kept_in {
5675 parts.push(format!("in {f}f"));
5676 }
5677 if let Some(f) = kept_out {
5678 parts.push(format!("out {f}f"));
5679 }
5680 let mut text = format!("fade {} {}", named.join(" + "), parts.join(" "));
5681 // The first clip speaks for the note: a linked partner is the same length.
5682 if let Some(&(got_in, got_out)) = applied.first() {
5683 let clamp = |asked: Option<u32>, got: Option<u32>, edge: &str| match (asked, got) {
5684 (Some(asked), Some(got)) if got < asked => Some(format!(
5685 "{edge} clamped from {} to the clip's {}",
5686 secs_text(asked, fps),
5687 secs_text(got, fps)
5688 )),
5689 _ => None,
5690 };
5691 let notes: Vec<String> = [clamp(fin, got_in, "in"), clamp(fout, got_out, "out")]
5692 .into_iter()
5693 .flatten()
5694 .collect();
5695 if !notes.is_empty() {
5696 text.push_str(&format!(" ({})", notes.join("; ")));
5697 }
5698 }
5699 text.push_str(&clamp_note);
5700 let touched = touched_of(s, &reached);
5701 Ok(plain(text, touched))
5702}
5703
5704/// The `kind`/`direction` of a transition op; a dissolve when `kind` is not given.
5705fn transition_kind_arg(op: &Value) -> Result<TransitionKind, String> {
5706 let text = |key: &str| match op.get(key) {
5707 None | Some(Value::Null) => Ok(None),
5708 Some(Value::String(t)) => Ok(Some(t.to_lowercase().replace('_', "-"))),
5709 Some(v) => Err(format!("`{key}` must be text, got {}", parse::kind_of(v))),
5710 };
5711 let shape = text("kind")?.unwrap_or_else(|| "dissolve".into());
5712 let dir = match text("direction")? {
5713 None => None,
5714 Some(d) => Some(Dir::parse(&d).ok_or_else(|| format!("`direction` {d:?} is not one of left, right, up, down"))?),
5715 };
5716 // A full name such as "wipe-left" is also accepted as the kind.
5717 if dir.is_none()
5718 && let Some(k) = TransitionKind::parse(&shape)
5719 {
5720 return Ok(k);
5721 }
5722 let kind = TransitionKind::from_parts(&shape, dir).ok_or_else(|| {
5723 format!("`kind` {shape:?} is not one of dissolve, dip-black, dip-white, wipe, slide, push, zoom")
5724 })?;
5725 if dir.is_some() && kind.dir().is_none() {
5726 return Err(format!("`direction` does not apply to {}: only wipe, slide and push move", kind.shape_name()));
5727 }
5728 Ok(kind)
5729}
5730
5731fn op_dissolve(s: &mut PlaybackSession, op: &Value, fps: f64, keep_length: bool) -> Result<Done, String> {
5732 let (lane, idx) = clip_arg(s, op)?;
5733 let addr = addr_of(s, lane, idx);
5734 let kind = transition_kind_arg(op)?;
5735 let given = match (length(op, "frames", fps)?, length(op, "length", fps)?) {
5736 (Some(_), Some(_)) => return Err("give `frames` or `length`, not both".into()),
5737 (a, b) => a.or(b),
5738 };
5739 // `transition` without a length restyles the transition the clip has.
5740 let kept = if keep_length { Some(s.transition_out_of(lane, idx)).filter(|&n| n > 0) } else { None };
5741 let frames = given.or(kept).ok_or("missing `frames`: give the transition length in frames")?;
5742 if lane.kind != LaneKind::Video {
5743 return Err(format!(
5744 "dissolve on {addr} refused: {} is an audio lane; a dissolve is picture, so use crossfade for sound",
5745 parse::lane_name(lane)
5746 ));
5747 }
5748 // The lock comes before the join: a locked lane is refused as locked, whatever clip it is on.
5749 let reached = reach(s, op, lane, idx)?;
5750 let lanes: Vec<Lane> = reached.iter().map(|&(l, _)| l).collect();
5751 check_unlocked(s, &lanes)?;
5752 if let Some(why) = join_problem(s, lane, idx) {
5753 return Err(format!("dissolve on {addr} refused: {why}"));
5754 }
5755 if !s.set_transition(lane, idx, kind, frames) {
5756 return Err(format!("dissolve on {addr} refused: the engine would not set it"));
5757 }
5758 // The overlap is the frames the engine kept, which is less than asked when the shorter clip is.
5759 let applied = s.transition_out_of(lane, idx);
5760 let next = s.lane_clips(lane).get(idx + 1).map(|c| c.start).unwrap_or(0);
5761 let from = next.saturating_sub(applied);
5762 let mut text = format!(
5763 "{} {addr}→{} over {applied}f ({}–{}): {} blends in over the tail of {addr}",
5764 kind.name(),
5765 addr_of(s, lane, idx + 1),
5766 secs_text(from, fps),
5767 secs_text(next, fps),
5768 addr_of(s, lane, idx + 1)
5769 );
5770 if applied < frames {
5771 text.push_str(&format!(" (clamped from {frames}f by the shorter of the two clips)"));
5772 }
5773 text.push_str("; timeline length unchanged");
5774 // A linked sound partner crossfades into its own next clip, when that clip meets it.
5775 for &(l, i) in reached.iter().filter(|&&(l, i)| (l, i) != (lane, idx) && l.kind == LaneKind::Audio) {
5776 let a = addr_of(s, l, i);
5777 if s.crossfade(l, i, frames) {
5778 text.push_str(&format!("; sound crossfaded {a} {frames}f into {}", addr_of(s, l, i + 1)));
5779 } else if let Some(t) = fade_to_silence(s, l, i, frames) {
5780 text.push_str(&format!("; {t}"));
5781 } else {
5782 text.push_str(&format!("; the sound on {a} was not crossfaded: {}", sound_skip_reason(s, l, i)));
5783 }
5784 }
5785 let touched = touched_of(s, &reached);
5786 Ok(plain(text, touched))
5787}
5788
5789/// Why a linked sound clip could not crossfade into its next clip, and what to do: one clause
5790/// for `dissolve`'s reply.
5791fn sound_skip_reason(s: &PlaybackSession, lane: Lane, idx: usize) -> String {
5792 let addr = addr_of(s, lane, idx);
5793 let name = parse::lane_name(lane);
5794 let clips = s.lane_clips(lane);
5795 match (clips.get(idx), clips.get(idx + 1)) {
5796 (Some(_), None) => format!(
5797 "{addr} is the last clip on {name}, so there is no clip after it to crossfade into; place the next sound clip after it, then crossfade {addr}"
5798 ),
5799 (Some(cur), Some(next)) if next.start > cur.end() => match take_gap_refusal(s, lane, cur.end(), next.start - cur.end()) {
5800 None => format!(
5801 "a gap of {}f lies before {} on {name}; close it with close_gaps {{lane:\"{name}\"}} and crossfade {addr} again",
5802 next.start - cur.end(),
5803 addr_of(s, lane, idx + 1)
5804 ),
5805 Some(why) => format!(
5806 "a gap of {}f lies before {} on {name}, and close_gaps cannot close it: {why}; crossfade {addr} once the gap is closed",
5807 next.start - cur.end(),
5808 addr_of(s, lane, idx + 1)
5809 ),
5810 },
5811 _ => format!("the engine would not crossfade {addr}; crossfade it on its own to see why"),
5812 }
5813}
5814
5815/// `visualizer {clip, on?, style?, fast?}`: the clip's waveform look, as the flags byte the
5816/// engine stores: bit 0 on, bits 1-2 the style (fill, ribbon, ring, wave), bit 3 fast.
5817fn op_visualizer(s: &mut PlaybackSession, op: &Value) -> Result<Done, String> {
5818 const STYLES: [&str; 4] = ["fill", "ribbon", "ring", "wave"];
5819 let (lane, idx) = clip_arg(s, op)?;
5820 let addr = addr_of(s, lane, idx);
5821 let flag = |key: &str| -> Result<Option<bool>, String> {
5822 match op.get(key) {
5823 None | Some(Value::Null) => Ok(None),
5824 Some(Value::Bool(b)) => Ok(Some(*b)),
5825 Some(_) => Err(format!("`{key}` must be true or false")),
5826 }
5827 };
5828 let on = flag("on")?;
5829 let fast = flag("fast")?;
5830 let style = match op.get("style") {
5831 None | Some(Value::Null) => None,
5832 Some(Value::String(t)) => Some(
5833 STYLES
5834 .iter()
5835 .position(|&n| n == t)
5836 .ok_or_else(|| format!("`style` {t} is not one of {}", STYLES.join(", ")))?,
5837 ),
5838 Some(_) => return Err(format!("`style` must be one of {}", STYLES.join(", "))),
5839 };
5840 if on.is_none() && fast.is_none() && style.is_none() {
5841 return Err(format!("visualizer {addr} needs `on`, `style` or `fast`"));
5842 }
5843 // On a sound clip, on:true places a waveform picture for it on a video lane. `style` and `fast`
5844 // set that picture's look (fill is the default), and the picture is grouped with the sound
5845 // clip, so moves, trims and deletes carry it.
5846 if lane.kind == LaneKind::Audio {
5847 // on:false turns off the waveform picture of the take, as it does when given on the picture's own clip.
5848 if on == Some(false) {
5849 if style.is_some() || fast.is_some() {
5850 return Err(format!("visualizer {addr}: on:false turns it off, so style and fast do not apply"));
5851 }
5852 let picture = take_of(s, lane, idx).into_iter().find(|&(l, i)| l.kind == LaneKind::Video && s.lane_clips(l)[i].visualizer != 0);
5853 let Some((pic_lane, pic_idx)) = picture else {
5854 return Ok(plain(format!("visualizer {addr} off already: its take has no waveform picture"), Vec::new()));
5855 };
5856 check_unlocked(s, &[pic_lane])?;
5857 if !s.set_visualizer(pic_lane, pic_idx, 0) {
5858 return Err(format!("visualizer {addr} refused: its waveform picture could not be turned off"));
5859 }
5860 let start = s.lane_clips(pic_lane)[pic_idx].start;
5861 let picture = parse::addr(pic_lane, start);
5862 return Ok(plain(format!("visualizer {addr} off: its waveform picture on {picture} is off"), vec![(pic_lane, start)]));
5863 }
5864 if on != Some(true) {
5865 return Err(format!(
5866 "visualizer {addr} refused: {} is an audio lane; the picture is drawn only from video clips, so set the visualizer on the video clip split from the same take, or give on:true for a waveform picture",
5867 parse::lane_name(lane)
5868 ));
5869 }
5870 check_unlocked(s, &[lane])?;
5871 // A take whose waveform picture is already there is restyled, not given a second one.
5872 let existing = take_of(s, lane, idx)
5873 .into_iter()
5874 .find(|&(l, i)| l.kind == LaneKind::Video && s.lane_clips(l)[i].visualizer != 0);
5875 let placed = existing.is_none();
5876 let (pic_lane, start) = match existing {
5877 Some((pl, pi)) => (pl, s.lane_clips(pl)[pi].start),
5878 None => super::edit_fx::place_waveform_for_audio(s, lane, idx)
5879 .map_err(|e| format!("visualizer {addr}: {e}"))?,
5880 };
5881 let pic_idx = s
5882 .lane_clips(pic_lane)
5883 .iter()
5884 .position(|c| c.start == start)
5885 .ok_or_else(|| format!("visualizer {addr}: the waveform picture was placed but not found"))?;
5886 let mut look = String::new();
5887 if style.is_some() || fast.is_some() {
5888 let cur = s.lane_clips(pic_lane)[pic_idx].visualizer;
5889 let mut f = (if cur == 0 { 1 } else { cur }) | 1;
5890 if let Some(st) = style {
5891 f = engine::decode::with_viz_style(f, st as u8);
5892 }
5893 match fast {
5894 Some(true) => f |= engine::decode::VIZ_FAST,
5895 Some(false) => f &= !engine::decode::VIZ_FAST,
5896 None => {}
5897 }
5898 if !s.set_visualizer(pic_lane, pic_idx, f) {
5899 return Err(format!("visualizer {addr}: the waveform picture could not take its look"));
5900 }
5901 let st = STYLES[usize::from(engine::decode::viz_style(f)) & 3];
5902 let fast_note = if f & engine::decode::VIZ_FAST != 0 { ", fast" } else { "" };
5903 look = format!(" (style {st}{fast_note})");
5904 }
5905 let picture = parse::addr(pic_lane, start);
5906 let text = if placed {
5907 s.group(lane, idx, pic_lane, pic_idx)
5908 .map_err(|e| format!("visualizer {addr}: the waveform picture could not be grouped with it: {e}"))?;
5909 // Read after the group: grouping re-keys the take's clips to one new link, so that link is the take's.
5910 let take_link = s.lane_clips(lane)[idx].link;
5911 let cover = covered_picture_note(s, pic_lane, start, s.lane_clips(pic_lane)[pic_idx].end(), take_link);
5912 format!("visualizer {addr}: placed a waveform picture{look} for {addr} on {picture}, grouped with it{cover}")
5913 } else if look.is_empty() {
5914 format!("visualizer {addr}: already on (its waveform picture is on {picture})")
5915 } else {
5916 format!("visualizer {addr}: restyled its waveform picture on {picture}{look}")
5917 };
5918 return Ok(plain(text, vec![(pic_lane, start), (lane, s.lane_clips(lane)[idx].start)]));
5919 }
5920 let cur = s.lane_clips(lane)[idx].visualizer;
5921 let flags = if on == Some(false) {
5922 if style.is_some() || fast.is_some() {
5923 return Err(format!("visualizer {addr}: on:false turns it off, so style and fast do not apply"));
5924 }
5925 0
5926 } else {
5927 if cur == 0 && on != Some(true) && (style.is_some() || fast.is_some()) {
5928 return Err(format!("visualizer {addr} is off: give on:true with style or fast"));
5929 }
5930 let base = if cur == 0 { 1 } else { cur };
5931 let mut f = base | 1;
5932 if let Some(st) = style {
5933 f = engine::decode::with_viz_style(f, st as u8);
5934 }
5935 match fast {
5936 Some(true) => f |= engine::decode::VIZ_FAST,
5937 Some(false) => f &= !engine::decode::VIZ_FAST,
5938 None => {}
5939 }
5940 f
5941 };
5942 check_unlocked(s, &[lane])?;
5943 if !s.set_visualizer(lane, idx, flags) {
5944 return Err(format!("visualizer {addr} refused: no such clip"));
5945 }
5946 let text = if flags == 0 {
5947 format!("visualizer {addr} off")
5948 } else {
5949 let st = STYLES[usize::from(engine::decode::viz_style(flags)) & 3];
5950 let fast_note = if flags & engine::decode::VIZ_FAST != 0 { ", fast" } else { "" };
5951 format!("visualizer {addr} on (style {st}{fast_note})")
5952 };
5953 Ok(plain(text, vec![(lane, s.lane_clips(lane)[idx].start)]))
5954}
5955
5956/// The note for a picture placed on `pic` over `start..end` when picture lanes below it hold clips
5957/// there: the picture is opaque (its background is drawn, not keyed out), so it hides them. Clips of
5958/// the visualized sound's own take (`take_link`) are left out: that take's picture is the one the
5959/// visualizer is for, not a cover. Empty when nothing below is covered.
5960fn covered_picture_note(s: &PlaybackSession, pic: Lane, start: u32, end: u32, take_link: Option<u32>) -> String {
5961 let fps = parse::session_fps(s);
5962 let mut parts: Vec<String> = Vec::new();
5963 for l in s.lanes().into_iter().filter(|l| l.kind == LaneKind::Video && l.ord < pic.ord) {
5964 for c in s.lane_clips(l) {
5965 let own_take = take_link.is_some() && c.link == take_link;
5966 let (a, b) = (c.start.max(start), c.end().min(end));
5967 if a < b && !own_take {
5968 parts.push(format!("{} ({}) during {}–{}", parse::lane_name(l), source_name(s, c.source), secs_text(a, fps), secs_text(b, fps)));
5969 }
5970 }
5971 }
5972 if parts.is_empty() {
5973 return String::new();
5974 }
5975 format!(
5976 "; the visualizer on {} draws over {}; lane_move it below them: its picture is opaque, and no background option makes it transparent",
5977 parse::lane_name(pic),
5978 parts.join(", ")
5979 )
5980}
5981
5982fn op_crossfade(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Done, String> {
5983 let (lane, idx) = clip_arg(s, op)?;
5984 let addr = addr_of(s, lane, idx);
5985 let frames = length(op, "frames", fps)?.ok_or("missing `frames`: give the crossfade length in frames")?;
5986 if lane.kind != LaneKind::Audio {
5987 return Err(format!(
5988 "crossfade on {addr} refused: {} is a picture lane; a crossfade joins sound, so use dissolve for picture",
5989 parse::lane_name(lane)
5990 ));
5991 }
5992 if let Some(why) = join_problem(s, lane, idx) {
5993 // No sound clip meets this one: fade it to and from silence instead of refusing.
5994 check_unlocked(s, &[lane])?;
5995 return match fade_to_silence(s, lane, idx, frames) {
5996 Some(t) => {
5997 let touched = s.lane_clips(lane).get(idx).map(|c| vec![(lane, c.start)]).unwrap_or_default();
5998 Ok(plain(format!("crossfade {addr} {frames}f: {t}"), touched))
5999 }
6000 None => Err(format!("crossfade on {addr} refused: {why}")),
6001 };
6002 }
6003 // A pair already crossfaded to this length (a dissolve does it for the sound of its take) is no change:
6004 // the reason is named, so the batch's no-change reply can say why.
6005 let (a, b) = (&s.lane_clips(lane)[idx], &s.lane_clips(lane)[idx + 1]);
6006 if s.fade_out_of(lane, idx) == frames.min(a.frames()) && s.fade_in_of(lane, idx + 1) == frames.min(b.frames()) {
6007 let from_dissolve = take_of(s, lane, idx).iter().any(|&(l, i)| {
6008 l.kind == LaneKind::Video && s.transition_out_of(l, i) > 0 && s.lane_clips(l).get(i).is_some_and(|c| c.end() == a.end())
6009 });
6010 let note = if from_dissolve { " (from the dissolve)" } else { "" };
6011 return Ok(plain(
6012 format!("{addr} and {} already crossfade over {frames}f{note}", addr_of(s, lane, idx + 1)),
6013 Vec::new(),
6014 ));
6015 }
6016 check_unlocked(s, &[lane])?;
6017 if !s.crossfade(lane, idx, frames) {
6018 return Err(format!("crossfade on {addr} refused: the engine would not set it"));
6019 }
6020 let touched = s.lane_clips(lane).get(idx).map(|c| vec![(lane, c.start)]).unwrap_or_default();
6021 // The reply names the clip the crossfade joins to, so the arrow is not a self-reference.
6022 Ok(plain(format!("crossfade {addr} {frames}f → {} (the next clip)", addr_of(s, lane, idx + 1)), touched))
6023}
6024
6025// ---- transform warning ----------------------------------------------------
6026
6027/// The share of a transformed clip's box that lands on the canvas, 0 to 1. The
6028/// box is `scale` canvas widths square, centred at (0.5 + x, 0.5 + y) -- taking
6029/// the fit size as the canvas's own shape, which is the common case.
6030fn on_canvas_share(t: &engine::transform::TransformParams) -> f32 {
6031 let (cx, cy) = (0.5 + t.pos_x, 0.5 + t.pos_y);
6032 let half = t.scale / 2.0;
6033 let across = ((cx + half).min(1.0) - (cx - half).max(0.0)).max(0.0);
6034 let down = ((cy + half).min(1.0) - (cy - half).max(0.0)).max(0.0);
6035 (across * down / (t.scale * t.scale)).clamp(0.0, 1.0)
6036}
6037
6038/// The transform op's reply, with a warning when the clip it placed is entirely
6039/// or mostly off the canvas: that is seldom what was meant, and little or none
6040/// of the picture shows.
6041fn off_canvas_note(s: &PlaybackSession, mut applied: Applied) -> Applied {
6042 for &(lane, start) in &applied.touched {
6043 let Some(idx) = s.lane_clips(lane).iter().position(|c| c.start == start) else {
6044 continue;
6045 };
6046 let Some(t) = s.transform_of(lane, idx) else {
6047 continue;
6048 };
6049 let share = on_canvas_share(t);
6050 if share <= 0.0 {
6051 applied
6052 .text
6053 .push_str(" — WARNING: this clip is entirely off the canvas, so none of it shows");
6054 } else if share < 0.5 {
6055 applied.text.push_str(&format!(
6056 " — WARNING: only {:.0}% of this clip is on the canvas",
6057 share * 100.0
6058 ));
6059 }
6060 }
6061 applied
6062}
6063
6064// ---- dispatch -------------------------------------------------------------
6065
6066/// The note for a `rotate` that is not a quarter turn: the picture turns only in 90-degree steps,
6067/// so the angle is drawn at the nearest one (the engine's rule). Empty for a quarter turn.
6068fn rotate_note(op: &Value) -> String {
6069 let Some(deg) = op.get("rotate").and_then(Value::as_f64) else { return String::new() };
6070 if deg.rem_euclid(90.0) == 0.0 {
6071 return String::new();
6072 }
6073 let steps = ((deg.rem_euclid(360.0) / 90.0).round() as i64).rem_euclid(4);
6074 format!("; rotate {} is drawn at {}° (only quarter turns)", compact(deg), steps * 90)
6075}
6076
6077/// One op, with the rounding note for each timeline time it took appended to its line.
6078/// An op aimed at the wrong kind of lane: picture ops on sound clips, sound ops on picture
6079/// clips, and lane gain on a video lane. None when the kind fits, or the address does not
6080/// resolve (the op's own check reports that).
6081fn kind_refusal(s: &PlaybackSession, name: &str, op: &Value) -> Option<String> {
6082 match name {
6083 "color" | "eq" | "visualizer" => {
6084 let addr = op.get("clip")?.as_str()?.trim();
6085 let (lane, idx) = parse::clip(s, addr).ok()?;
6086 let here = parse::lane_name(lane);
6087 match (name, lane.kind) {
6088 // A visualizer is a sound clip's picture: turning one on a video clip names the sound clip of its take.
6089 // on:false only clears a flag, so it is let through.
6090 ("visualizer", LaneKind::Video) if op.get("on") != Some(&Value::Bool(false)) => {
6091 let sound = take_of(s, lane, idx).into_iter().find(|&(l, _)| l.kind == LaneKind::Audio);
6092 Some(match sound {
6093 Some((l, i)) => {
6094 // The sound clip's waveform picture must match its length, so a sound clip off 1x refuses on:true.
6095 let sound = addr_of(s, l, i);
6096 let bounds = if s.speed_of(l, i) == engine::project::Speed::NORMAL {
6097 format!("on:true there places its waveform picture over the span of {sound} on a free video lane")
6098 } else {
6099 format!("its waveform picture must match its length, and {sound} plays at {}x: set its speed to 1x first", compact(s.speed_of(l, i).as_f64()))
6100 };
6101 format!("visualizer {addr} refused: {here} is a video lane; the visualizer is set on the sound clip of its take, {sound} ({sound} is the sound of {addr}); {bounds}")
6102 }
6103 None => format!(
6104 "visualizer {addr} refused: {here} is a video lane with no linked sound clip; the visualizer is set on a sound clip (on:true there places its waveform picture)"
6105 ),
6106 })
6107 }
6108 ("color", LaneKind::Audio) => Some(format!(
6109 "color {addr} refused: {here} is an audio lane; colour is picture, so set it on the video clip split from the same take"
6110 )),
6111 ("eq", LaneKind::Video) => Some(format!(
6112 "eq {addr} refused: {here} is a video lane; the equalizer works on sound, so set it on the audio clip split from the same take"
6113 )),
6114 _ => None,
6115 }
6116 }
6117 "lane_pan" => {
6118 let lane = lane_arg(op, "lane").ok()??;
6119 (lane.kind != LaneKind::Audio).then(|| {
6120 format!("lane_pan {} refused: pan is set on an audio lane (A1..)", parse::lane_name(lane))
6121 })
6122 }
6123 "lane_gain" => {
6124 let lane = lane_arg(op, "lane").ok()??;
6125 (lane.kind == LaneKind::Video).then(|| {
6126 format!(
6127 "lane_gain {} refused: a video lane has no sound of its own; lane gain is set on an audio lane (A1..)",
6128 parse::lane_name(lane)
6129 )
6130 })
6131 }
6132 _ => None,
6133 }
6134}
6135
6136const PICTURE_PARTS: &[&str] = &["color", "transform", "fit", "effects"];
6137const SOUND_PARTS: &[&str] = &["eq", "gain"];
6138
6139/// The parts `copy_look` copies: `what`, default ["color"]. Each is "color", "transform" or "fit"
6140/// (picture parts) or "eq" (the sound's equalizer).
6141fn copy_what(op: &Value) -> Result<Vec<&'static str>, String> {
6142 let list = match op.get("what") {
6143 None | Some(Value::Null) => return Ok(vec!["color"]),
6144 Some(Value::Array(list)) => list,
6145 Some(_) => return Err("copy_look: `what` must be a list of color, transform, fit, effects, eq, gain or speed".into()),
6146 };
6147 let mut out: Vec<&'static str> = Vec::new();
6148 for item in list {
6149 let name = match item.as_str() {
6150 Some("color") => "color",
6151 Some("transform") => "transform",
6152 Some("fit") => "fit",
6153 Some("eq") => "eq",
6154 Some("effects") => "effects",
6155 Some("speed") => "speed",
6156 Some("gain") => "gain",
6157 _ => return Err(format!("copy_look: `what` takes color, transform, fit, effects, eq, gain or speed; {item} is not one of them")),
6158 };
6159 if !out.contains(&name) {
6160 out.push(name);
6161 }
6162 }
6163 if out.is_empty() {
6164 return Err("copy_look: `what` is empty; name what to copy, e.g. [\"color\"]".into());
6165 }
6166 Ok(out)
6167}
6168
6169/// `copy_look {from, to:[addrs] | to_lane, what?}`: copies the look of the clip `from` onto the
6170/// clips `to` (or every clip on `to_lane`), as one batch step. Colour, transform and fit come from
6171/// a picture clip and land on picture clips; eq comes from a sound clip and lands on sound clips.
6172/// A target the part does not fit is skipped and named in the reply. Each target gets exactly the
6173/// source's setting, including none: a source with no colour clears its targets' colour.
6174fn op_copy_look(s: &mut PlaybackSession, op: &Value) -> Result<Done, String> {
6175 if op.get("from").is_none() {
6176 return Err("copy_look needs `from`: the clip whose look to copy, e.g. \"V1@0\"".into());
6177 }
6178 let (from_lane, from_idx) = clip_arg(s, &json!({ "clip": op.get("from").cloned().unwrap_or(Value::Null) }))
6179 .map_err(|e| format!("copy_look from: {e}"))?;
6180 let from_addr = addr_of(s, from_lane, from_idx);
6181 let what = copy_what(op)?;
6182 let picture_part = what.iter().any(|w| PICTURE_PARTS.contains(w));
6183 let sound_part = what.iter().any(|w| SOUND_PARTS.contains(w));
6184 if picture_part && from_lane.kind != LaneKind::Video {
6185 return Err(format!(
6186 "copy_look from {from_addr}: colour, transform, fit and effects come from a picture clip; {from_addr} is a sound clip (use what:[\"eq\"] or [\"gain\"] for its sound)"
6187 ));
6188 }
6189 if sound_part && from_lane.kind != LaneKind::Audio {
6190 return Err(format!(
6191 "copy_look from {from_addr}: eq comes from a sound clip, and so does gain; {from_addr} is a picture clip (its sound is on the audio lane of its take)"
6192 ));
6193 }
6194 // The targets: each `to` address, or every clip on `to_lane`; the source itself is never one.
6195 let mut targets: Vec<(Lane, usize)> = Vec::new();
6196 match (op.get("to"), lane_arg(op, "to_lane")?) {
6197 (Some(_), Some(_)) => return Err("copy_look: give `to` or `to_lane`, not both".into()),
6198 (Some(Value::Array(list)), None) => {
6199 if list.is_empty() {
6200 return Err("copy_look: `to` is empty; give clip addresses such as [\"V1@45\"]".into());
6201 }
6202 for v in list {
6203 targets.push(clip_arg(s, &json!({ "clip": v })).map_err(|e| format!("copy_look to: {e}"))?);
6204 }
6205 }
6206 (Some(_), None) => return Err("copy_look: `to` must be a list of clip addresses, e.g. [\"V1@45\"]".into()),
6207 (None, Some(l)) => {
6208 if !s.lanes().contains(&l) {
6209 return Err(missing_lane(s, l));
6210 }
6211 targets.extend((0..s.lane_clips(l).len()).map(|i| (l, i)));
6212 }
6213 (None, None) => return Err("copy_look needs `to` (clip addresses) or `to_lane`".into()),
6214 }
6215 targets.retain(|&t| t != (from_lane, from_idx));
6216 let mut seen: Vec<(Lane, usize)> = Vec::new();
6217 targets.retain(|t| {
6218 let new = !seen.contains(t);
6219 seen.push(*t);
6220 new
6221 });
6222 if targets.is_empty() {
6223 return Err(format!("copy_look {from_addr}: no clips to copy onto (the source is the only one named)"));
6224 }
6225 let mut unique: Vec<Lane> = Vec::new();
6226 for &(l, _) in &targets {
6227 if !unique.contains(&l) {
6228 unique.push(l);
6229 }
6230 }
6231 check_unlocked(s, &unique)?;
6232
6233 // The source's settings, read before anything changes.
6234 let color = s.color_of(from_lane, from_idx).copied();
6235 let transform = s.transform_of(from_lane, from_idx).copied();
6236 let fit = s.fit_of(from_lane, from_idx);
6237 let eq = s.eq_of(from_lane, from_idx).cloned();
6238 let effects = s.effects_of(from_lane, from_idx).to_vec();
6239 let gain = s.clip_gain_of(from_lane, from_idx).unwrap_or(0.);
6240 let sp = s.lane_clips(from_lane).get(from_idx).map(|c| (c.speed, c.speed_keys.clone(), c.reversed)).ok_or("copy_look: the source clip is gone")?;
6241 let speed_differs = |s: &PlaybackSession, l: Lane, i: usize| {
6242 s.lane_clips(l).get(i).is_some_and(|c| (c.speed, &c.speed_keys, c.reversed) != (sp.0, &sp.1, sp.2))
6243 };
6244
6245 let mut touched: Vec<(Lane, u32)> = Vec::new();
6246 let mut names: Vec<String> = Vec::new();
6247 let mut skipped: Vec<String> = Vec::new();
6248 // Targets that already hold the source's look for every part asked: nothing is written to them.
6249 let mut already: Vec<String> = Vec::new();
6250 let parts = what.join(", ");
6251 for &(l, i) in &targets {
6252 let addr = addr_of(s, l, i);
6253 let start = s.lane_clips(l).get(i).map_or(0, |c| c.start);
6254 let differs = match l.kind {
6255 // A part the lane kind does not take is skipped below, so it counts as a difference here.
6256 LaneKind::Video => {
6257 !(picture_part || what.contains(&"speed"))
6258 || sound_part
6259 || (what.contains(&"color") && s.color_of(l, i).copied() != color)
6260 || (what.contains(&"transform") && s.transform_of(l, i).copied() != transform)
6261 || (what.contains(&"fit") && s.fit_of(l, i) != fit)
6262 || (what.contains(&"effects") && s.effects_of(l, i) != effects.as_slice())
6263 || (what.contains(&"speed") && speed_differs(s, l, i))
6264 }
6265 LaneKind::Audio => {
6266 picture_part
6267 || !(sound_part || what.contains(&"speed"))
6268 || (what.contains(&"eq") && s.eq_of(l, i).cloned() != eq)
6269 || (what.contains(&"gain") && s.clip_gain_of(l, i).unwrap_or(0.) != gain)
6270 || (what.contains(&"speed") && speed_differs(s, l, i))
6271 }
6272 LaneKind::Subtitle => true,
6273 };
6274 if !differs {
6275 already.push(addr);
6276 continue;
6277 }
6278 // `took`: the target received at least one part. A target that took nothing is skipped, not applied.
6279 let mut took = false;
6280 match l.kind {
6281 LaneKind::Video => {
6282 if what.contains(&"color") {
6283 if !s.set_color(l, i, color) {
6284 return Err(format!("copy_look: the colour would not go on {addr}"));
6285 }
6286 took = true;
6287 }
6288 if what.contains(&"transform") {
6289 if !s.set_transform(l, i, transform) {
6290 return Err(format!("copy_look: the transform would not go on {addr}"));
6291 }
6292 took = true;
6293 }
6294 if what.contains(&"fit") {
6295 if !s.set_fit(l, i, fit) {
6296 return Err(format!("copy_look: the fit would not go on {addr}"));
6297 }
6298 took = true;
6299 }
6300 if what.contains(&"effects") {
6301 if !s.set_effects(l, i, effects.clone()) {
6302 return Err(format!("copy_look: the effects would not go on {addr}"));
6303 }
6304 took = true;
6305 }
6306 if sound_part {
6307 skipped.push(format!(
6308 "{} on {addr} (a picture clip has no eq or gain; its sound does)",
6309 what.iter().filter(|w| SOUND_PARTS.contains(w)).copied().collect::<Vec<_>>().join(", ")
6310 ));
6311 }
6312 }
6313 LaneKind::Audio => {
6314 if what.contains(&"eq") {
6315 if !s.set_eq(l, i, eq.clone()) {
6316 return Err(format!("copy_look: the eq would not go on {addr}"));
6317 }
6318 took = true;
6319 }
6320 if what.contains(&"gain") {
6321 if !s.set_clip_gain(l, i, gain) {
6322 return Err(format!("copy_look: the gain would not go on {addr}"));
6323 }
6324 took = true;
6325 }
6326 if picture_part {
6327 skipped.push(format!("{} on {addr} (a sound clip has no picture look)", what.iter().filter(|w| PICTURE_PARTS.contains(w)).copied().collect::<Vec<_>>().join(", ")));
6328 }
6329 }
6330 LaneKind::Subtitle => {
6331 skipped.push(format!("{addr} (a caption lane takes no look)"));
6332 continue;
6333 }
6334 }
6335 if what.contains(&"speed") {
6336 if speed_differs(s, l, i) {
6337 let mut ok = s.reversed_of(l, i) == sp.2 || s.set_reverse(l, i, sp.2).is_ok();
6338 ok &= s.speed_of(l, i) == sp.0 || s.set_speed(l, i, sp.0).is_ok();
6339 if !sp.1.is_empty() {
6340 ok &= s.set_speed_ramp(l, i, &sp.1).is_ok();
6341 }
6342 if ok {
6343 took = true;
6344 } else {
6345 skipped.push(format!("speed on {addr} (no room to change its length there)"));
6346 }
6347 } else {
6348 took = true;
6349 }
6350 }
6351 if !took {
6352 skipped.push(format!("{addr} (no part of {parts} applies to it)"));
6353 continue;
6354 }
6355 names.push(addr);
6356 touched.push((l, start));
6357 }
6358 if names.is_empty() && skipped.is_empty() && !already.is_empty() {
6359 // Nothing changed: the reply says so, and the batch reads as a no-change one.
6360 let (verb, list) = if already.len() == 1 { ("has", already[0].clone()) } else { ("have", already.join(", ")) };
6361 return Ok(plain(format!("{list} already {verb} {from_addr}'s {parts}: nothing to copy"), Vec::new()));
6362 }
6363 let mut text = format!("copy_look {from_addr} → {}: {parts} copied", names.join(", "));
6364 if names.is_empty() {
6365 text = format!("copy_look {from_addr}: no target took {parts}");
6366 }
6367 if what.contains(&"color") && color.is_none() && !names.is_empty() {
6368 text.push_str(&format!("; {from_addr} has no colour, so the targets' colour is cleared"));
6369 }
6370 if !already.is_empty() {
6371 text.push_str(&format!("; already had {parts}: {}", already.join(", ")));
6372 }
6373 if !skipped.is_empty() {
6374 text.push_str(&format!("; skipped: {}", skipped.join("; ")));
6375 }
6376 Ok(plain(text, touched))
6377}
6378
6379/// `replace {clip, source, in?}`: the clip (and the linked other half of its take, when it covers the
6380/// same frames and the source has that half) is overwritten by `source` from `in` (default its start),
6381/// keeping its place and length. Nothing else moves. One undo step.
6382fn op_replace(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Done, String> {
6383 let mut op = op.clone();
6384 if let Some(o) = op.as_object_mut()
6385 && let Some(v) = o.remove("src")
6386 {
6387 if o.contains_key("source") {
6388 return Err("replace: give source or src, not both".into());
6389 }
6390 o.insert("source".into(), v);
6391 }
6392 let op = &op;
6393 let (lane, idx) = clip_arg(s, op)?;
6394 let addr = addr_of(s, lane, idx);
6395 let n = source_arg(s, op)?;
6396 check_unlocked(s, &take_of(s, lane, idx).iter().map(|&(l, _)| l).collect::<Vec<_>>())?;
6397 let path: PathBuf = s.sources()[n].path.clone();
6398 let still = engine::is_still(&path);
6399 let picture = engine::is_image(&path) || engine::probe_media(&path).video.is_some();
6400 let sound = !engine::is_image(&path)
6401 && !AudioSession::probe_streams(&path).map_err(|e| format!("src:{n}: cannot read its sound: {e}"))?.is_empty();
6402 let total = source_frames(s, n, Some(lane), fps);
6403 let (in_f, note) = if still {
6404 if op.get("in").is_some() {
6405 return Err(format!("replace: src:{n} is a still image, which takes no `in`"));
6406 }
6407 (0, String::new())
6408 } else {
6409 let b = Base::of(s, &path);
6410 match opt_source_time(op, "in", b, total)? {
6411 Some((f, note)) => (f, note),
6412 None => (0, String::new()),
6413 }
6414 };
6415 let (at, len, items) = engine::editkeys::replace_plan(s, (lane, idx), n, in_f, total, (picture, sound, still))
6416 .map_err(|e| format!("replace {addr} with src:{n}: {e}"))?;
6417 s.edit_from_source_at(SourceEdit::Overwrite, parse::secs(at, fps), &items)
6418 .map_err(|e| format!("replace {addr} with src:{n}: {e}"))?;
6419 let touched: Vec<(Lane, u32)> = items.iter().map(|(l, _)| (*l, at)).collect();
6420 let names: Vec<String> = touched.iter().map(|&(l, st)| parse::addr(l, st)).collect();
6421 let shown = if still { "(still)".to_string() } else { Base::of(s, &path).span(in_f, in_f + len) };
6422 let text = format!(
6423 "replace {addr} with src:{n} {} {shown}: {} now play it for {}{note}",
6424 source_name(s, n),
6425 names.join(" + "),
6426 secs_text(len, fps)
6427 );
6428 Ok(plain(text, touched))
6429}
6430
6431/// `nudge {clips:[addrs], by}`: the clips (and their groups) move `by` along their lane as one move,
6432/// refused when a neighbour blocks it outright, and stopped short at the room there is. One undo step.
6433fn op_nudge(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Done, String> {
6434 let list = match op.get("clips") {
6435 Some(Value::Array(l)) if !l.is_empty() => l,
6436 Some(Value::String(_)) => return Err("nudge: `clips` must be a list of addresses, e.g. [\"V1@45\"]".into()),
6437 _ => return Err("missing `clips`: a list of clip addresses to move, e.g. [\"V1@45\", \"A1@45\"]".into()),
6438 };
6439 let by = need_by(op, fps)?;
6440 let mut picks: Vec<(Lane, usize)> = Vec::new();
6441 for v in list {
6442 let p = clip_arg(s, &json!({ "clip": v })).map_err(|e| format!("nudge clips: {e}"))?;
6443 if !picks.contains(&p) {
6444 picks.push(p);
6445 }
6446 }
6447 let lanes: Vec<Lane> = picks.iter().map(|p| p.0).collect();
6448 check_unlocked(s, &lanes)?;
6449 if by == 0 {
6450 return Ok(plain("nudge: by 0f, nothing to move".into(), Vec::new()));
6451 }
6452 let &(al, ai) = picks.last().ok_or("nudge: no clips")?;
6453 let anchor = s.lane_clips(al)[ai].clone();
6454 let from = anchor.start;
6455 let before: Vec<(Lane, u32)> = picks.iter().map(|&(l, i)| (l, s.lane_clips(l)[i].start)).collect();
6456 let names: Vec<String> = before.iter().map(|&(l, st)| parse::addr(l, st)).collect();
6457 engine::editkeys::nudge(s, &picks, by).map_err(|why| format!("nudge {} refused: {why}", names.join(", ")))?;
6458 // The move stops at the room there is, so the landing is read back from the anchor, not assumed.
6459 let landed = s
6460 .lane_clips(al)
6461 .iter()
6462 .find(|c| (c.source, c.in_frame, c.out_frame) == (anchor.source, anchor.in_frame, anchor.out_frame) && c.link == anchor.link)
6463 .map_or(from, |c| c.start);
6464 let moved = i64::from(landed) - i64::from(from);
6465 if moved == 0 {
6466 return Err(format!("nudge {} refused: a neighbouring clip is in the way", names.join(", ")));
6467 }
6468 let touched: Vec<(Lane, u32)> = before.iter().map(|&(l, st)| (l, (i64::from(st) + moved).max(0) as u32)).collect();
6469 let now: Vec<String> = touched.iter().map(|&(l, st)| parse::addr(l, st)).collect();
6470 let mut text = format!("nudge {} by {}: now {}", names.join(", "), signed(moved), now.join(", "));
6471 if moved != by {
6472 text.push_str(&format!("; stopped short of {} (the room there is, or the start of the timeline)", signed(by)));
6473 }
6474 Ok(plain(text, touched))
6475}
6476
6477/// Refuses an op that names a lane the timeline does not have, before the op runs. The lanes an op
6478/// names (`lane`, `lanes`, `to_lane`, `audio_lane`, `under`) must be on the timeline, and the refusal
6479/// names the ones that are. Placements (which add a lane with `lane_add` in the fix they name) and
6480/// caption ops (which make a missing caption lane themselves) keep their own checks.
6481fn check_named_lanes(s: &PlaybackSession, name: &str, op: &Value) -> Result<(), String> {
6482 if SUB_OPS.contains(&name) || matches!(name, "place" | "append" | "keep" | "assemble") {
6483 return Ok(());
6484 }
6485 let mut raws: Vec<&str> = ["lane", "to_lane", "audio_lane", "under"].iter().filter_map(|k| op.get(*k)?.as_str()).collect();
6486 if let Some(list) = op.get("lanes").and_then(Value::as_array) {
6487 raws.extend(list.iter().filter_map(Value::as_str));
6488 }
6489 let lanes = s.lanes();
6490 for raw in raws {
6491 // A name that does not parse is the op's own refusal to give.
6492 let Ok(l) = parse::lane(raw) else { continue };
6493 if !lanes.contains(&l) {
6494 let names: Vec<String> = lanes.iter().copied().map(parse::lane_name).collect();
6495 return Err(format!("{raw} is not a lane on this timeline; the lanes are {}", names.join(", ")));
6496 }
6497 }
6498 Ok(())
6499}
6500
6501fn run_op(s: &mut PlaybackSession, name: &str, op: &Value, fps: f64, project: Option<&Path>, tones: Option<&Path>, dry: bool) -> Result<Done, String> {
6502 check_keys(name, op)?;
6503 check_named_lanes(s, name, op)?;
6504 if let Some(msg) = kind_refusal(s, name, op) {
6505 return Err(msg);
6506 }
6507 let mut done = run_op_inner(s, name, op, fps, project, tones, dry).map_err(|e| missing_key_hint(name, op, e))?;
6508 done.text.push_str(&time_notes(name, op, fps));
6509 Ok(done)
6510}
6511
6512fn run_op_inner(s: &mut PlaybackSession, name: &str, op: &Value, fps: f64, project: Option<&Path>, tones: Option<&Path>, dry: bool) -> Result<Done, String> {
6513 let end = parse::session_end(s);
6514 match name {
6515 "place" => op_place(s, op, fps, end),
6516 "insert" => op_three_point(s, SourceEdit::Insert, op, fps, end),
6517 "overwrite" => op_three_point(s, SourceEdit::Overwrite, op, fps, end),
6518 "append" => op_append(s, op, fps, end),
6519 "keep" => op_keep(s, op, fps, end),
6520 "assemble" => op_assemble(s, op, fps, end),
6521 "split" => op_split(s, op, fps, end),
6522 "regroup" => op_regroup(s, op, fps, end),
6523 "copy_paste" => op_copy_paste(s, op, fps, end),
6524 "close_gap" => op_close_gap(s, op, fps, end),
6525 "solo" => op_solo(s, op),
6526 "trim" => op_trim(s, op, fps, end),
6527 "split_edit" => op_split_edit(s, op, fps, end),
6528 "roll" => op_roll(s, op, fps, end),
6529 "slip" => op_slip(s, op, fps),
6530 "slide" => op_slide(s, op, fps),
6531 "move" => op_move(s, op, fps, end),
6532 "copy_look" => op_copy_look(s, op),
6533 "replace" => op_replace(s, op, fps),
6534 "nudge" => op_nudge(s, op, fps),
6535 "delete" => op_delete(s, op, fps),
6536 "lift" => op_lift(s, op),
6537 "swap" => op_swap(s, op),
6538 "ripple_delete" => op_ripple_delete(s, op, fps),
6539 "close_gaps" => op_close_gaps(s, op),
6540 "cut_regions" => op_cut_regions(s, op, fps, end),
6541 "insert_time" => op_insert_time(s, op, fps, end),
6542 "freeze" => op_freeze(s, op, fps, end, project, dry),
6543 "remove_time" => op_remove_time(s, op, fps, end),
6544 "speed" => op_speed(s, op, fps),
6545 "speed_ramp" => op_speed_ramp(s, op, fps),
6546 "reverse" => op_reverse(s, op),
6547 "fade" => op_fade(s, op, fps, end),
6548 "dissolve" | "transition" => op_dissolve(s, op, fps, name == "transition"),
6549 "crossfade" => op_crossfade(s, op, fps),
6550 "visualizer" => op_visualizer(s, op),
6551 "chapter_add" | "chapter_set" | "chapter_remove" => op_chapter(s, name, op, fps, end),
6552 "marker_add" | "marker_set" | "marker_remove" => op_marker(s, name, op, fps, end),
6553 "beats" => op_beats(s, op, fps),
6554 "transform" => match edit_fx::apply(s, op, fps) {
6555 Some(r) => r.map(|applied| {
6556 let mut d = Done::from(off_canvas_note(s, applied));
6557 d.text.push_str(&rotate_note(op));
6558 d
6559 }),
6560 None => Err("transform is not answered here".to_owned()),
6561 },
6562 _ => {
6563 if let Some(r) = generated::apply(s, op, fps, tones) {
6564 return r.map(Done::from);
6565 }
6566 if let Some(r) = edit_fx::apply(s, op, fps) {
6567 return r.map(Done::from);
6568 }
6569 if let Some(r) = edit_subs::apply(s, op, fps) {
6570 return r.map(Done::from);
6571 }
6572 Err(format!(
6573 "unknown op `{name}`; known: {}",
6574 OWN_OPS.iter().chain(FX_OPS.iter()).chain(SUB_OPS.iter()).copied().collect::<Vec<_>>().join(", ")
6575 ))
6576 }
6577 }
6578}
6579
6580// ---- reporting ------------------------------------------------------------
6581
6582/// Every clip and caption on the timeline as (lane, identity, start). A clip's identity is what
6583/// it plays (its source range), which a ripple or a move does not change, so it finds the clip
6584/// again after the op.
6585type Layout = Vec<(Lane, String, u32)>;
6586
6587fn layout(s: &PlaybackSession) -> Layout {
6588 let mut out = Vec::new();
6589 for l in s.lanes() {
6590 if l.kind == LaneKind::Subtitle {
6591 out.extend(s.sub_lane(l).iter().map(|c| (l, format!("caption {}:{}:{}", c.track, c.in_us, c.out_us), c.start)));
6592 } else {
6593 out.extend(s.lane_clips(l).iter().map(|c| (l, format!("clip {}:{}:{}", c.source, c.in_frame, c.out_frame), c.start)));
6594 }
6595 }
6596 out
6597}
6598
6599/// The lane_move checks, before the op runs: `to` is the 1-based position of the lane in the lane
6600/// list, and the refusal shows that list so the position can be read off it.
6601fn lane_move_check(s: &PlaybackSession, op: &Value) -> Result<(), String> {
6602 let lanes = s.lanes();
6603 let n = lanes.len();
6604 let raw = op.get("lane").and_then(Value::as_str).unwrap_or("?");
6605 // A locked lane does not move: the lock is checked before the position, so the refusal names it.
6606 if let Ok(lane) = parse::lane(raw)
6607 && s.lane_locked(lane)
6608 {
6609 return Err(format!("lane_move {raw}: {}", lock_msg(lane)));
6610 }
6611 let list: Vec<String> = lanes.iter().enumerate().map(|(i, l)| format!("{} ({})", parse::lane_name(*l), i + 1)).collect();
6612 let list = list.join(", ");
6613 match op.get("to") {
6614 None | Some(Value::Null) => Err(format!(
6615 "lane_move {raw}: missing `to`; give the 1-based position of the lane in the lane list, 1–{n}. The lanes are: {list}"
6616 )),
6617 Some(v) => match v.as_f64() {
6618 Some(x) if x.fract() == 0.0 && x >= 1.0 && x <= n as f64 => Ok(()),
6619 Some(x) => Err(format!(
6620 "lane_move {raw}: to {x} is not a lane position; `to` is the 1-based position of the lane in the lane list, a whole number 1–{n}. The lanes are: {list}"
6621 )),
6622 None => Err(format!(
6623 "lane_move {raw}: `to` must be the 1-based position of the lane in the lane list (as `timeline` lists lanes), a whole number 1–{n}, not {}. The lanes are: {list}",
6624 parse::kind_of(v)
6625 )),
6626 },
6627 }
6628}
6629
6630/// The clips a lane_move shifted, as (old address, new address). A move renumbers lanes: a label is
6631/// a position among the lanes of its kind, so the lanes between the two positions take the next
6632/// label over. Each lane is followed by its position (old position to new position), and each clip
6633/// is matched on its new lane by what it plays and where it starts; a clip whose address is the same is not listed.
6634fn lane_move_shifts(op: &Value, before_lanes: &[Lane], before: &Layout, after: &Layout, after_lanes: &[Lane]) -> Vec<(String, String)> {
6635 let Some(lane) = op.get("lane").and_then(Value::as_str).and_then(|t| parse::lane(t).ok()) else {
6636 return Vec::new();
6637 };
6638 let (Some(from), Some(to)) = (
6639 before_lanes.iter().position(|l| *l == lane),
6640 op.get("to").and_then(Value::as_f64).filter(|x| *x >= 1.0).map(|x| x as usize - 1),
6641 ) else {
6642 return Vec::new();
6643 };
6644 let new_pos = |p: usize| -> usize {
6645 if p == from {
6646 to
6647 } else if from < to && p > from && p <= to {
6648 p - 1
6649 } else if to < from && p >= to && p < from {
6650 p + 1
6651 } else {
6652 p
6653 }
6654 };
6655 let mut out = Vec::new();
6656 for x in before {
6657 let Some(p) = before_lanes.iter().position(|l| *l == x.0) else { continue };
6658 let Some(&nl) = after_lanes.get(new_pos(p)) else { continue };
6659 if let Some(y) = after.iter().find(|y| y.0 == nl && y.1 == x.1 && y.2 == x.2)
6660 && (y.0, y.2) != (x.0, x.2)
6661 {
6662 out.push((parse::addr(x.0, x.2), parse::addr(y.0, y.2)));
6663 }
6664 }
6665 out
6666}
6667
6668/// The clips an op moved, as (old address, new address). An identity counts only when it occurs
6669/// once on each side, so a clip the op added or removed is never paired with another one: such a
6670/// clip is the same clip wherever it went (a move jumping over others keeps every lane's count).
6671/// The rest follow the lane rule: a lane that kept its item count keeps its items in order.
6672fn shifted_pairs(before: &Layout, after: &Layout) -> Vec<(String, String)> {
6673 shifted_pairs_cut(before, after, None)
6674}
6675
6676/// The span a cutting op removes, as (start, frames), read before the op runs (the clip is gone
6677/// after it). None for an op that cuts nothing out of the timeline.
6678fn ripple_cut(s: &PlaybackSession, name: &str, op: &Value, fps: f64) -> Option<(u32, u32)> {
6679 match name {
6680 "delete" | "ripple_delete" => clip_arg(s, op).ok().map(|(l, i)| {
6681 let c = &s.lane_clips(l)[i];
6682 (c.start, c.frames())
6683 }),
6684 "remove_time" => Some((need(op, "at", fps, u32::MAX).ok()?, need(op, "duration", fps, u32::MAX).ok()?)),
6685 _ => None,
6686 }
6687}
6688
6689/// `shifted_pairs` for an op that cuts `span` (the `(start, frames)` pair) out of the timeline. A
6690/// clip that plays the same source range twice on its lane (two takes cut from one place) cannot
6691/// be paired by its identity alone: the cut says where each one lands. A clip that starts at or
6692/// after the cut's end moves back by the span, so it is paired with the clip now at that start.
6693fn shifted_pairs_cut(before: &Layout, after: &Layout, cut: Option<(u32, u32)>) -> Vec<(String, String)> {
6694 if before == after {
6695 return Vec::new();
6696 }
6697 let mut out = Vec::new();
6698 let mut used = vec![false; after.len()];
6699 let mut taken = vec![false; before.len()];
6700 if let Some((from, span)) = cut {
6701 for (i, x) in before.iter().enumerate() {
6702 let twins = before.iter().filter(|y| y.0 == x.0 && y.1 == x.1).count();
6703 if twins < 2 || (from..from.saturating_add(span)).contains(&x.2) {
6704 continue;
6705 }
6706 let to = if x.2 >= from.saturating_add(span) { x.2 - span } else { x.2 };
6707 if let Some(j) = (0..after.len()).find(|&j| !used[j] && after[j].0 == x.0 && after[j].1 == x.1 && after[j].2 == to) {
6708 used[j] = true;
6709 taken[i] = true;
6710 if to != x.2 {
6711 out.push((parse::addr(x.0, x.2), parse::addr(x.0, to)));
6712 }
6713 }
6714 }
6715 }
6716 let open_before: Layout = before.iter().enumerate().filter(|(i, _)| !taken[*i]).map(|(_, x)| x.clone()).collect();
6717 let mut pend_before: Layout = Vec::new();
6718 // Pass one pairs a clip with the one on its own lane, pass two (a clip sent to another lane)
6719 // with the only one of its identity anywhere; a take's partners share an identity, so they wait for pass one.
6720 for pass in 0..2 {
6721 let mut next_pending: Layout = Vec::new();
6722 for x in if pass == 0 { open_before.clone() } else { std::mem::take(&mut pend_before) } {
6723 let same = |y: &(Lane, String, u32)| y.1 == x.1 && (pass == 1 || y.0 == x.0);
6724 let was = open_before.iter().filter(|y| same(y)).count();
6725 let now: Vec<usize> = (0..after.len()).filter(|&j| same(&after[j]) && !used[j]).collect();
6726 let (pool_now, pool_was) = (now.len(), was);
6727 if pass == 1 && pool_was == 1 && pool_now == 1 || pass == 0 && pool_was == 1 && pool_now == 1 {
6728 let j = now[0];
6729 used[j] = true;
6730 let y = &after[j];
6731 if (y.0, y.2) != (x.0, x.2) {
6732 out.push((parse::addr(x.0, x.2), parse::addr(y.0, y.2)));
6733 }
6734 } else {
6735 next_pending.push(x);
6736 }
6737 }
6738 pend_before = next_pending;
6739 }
6740 let pend_after: Layout = after.iter().enumerate().filter(|(j, _)| !used[*j]).map(|(_, y)| y.clone()).collect();
6741 let mut lanes_seen: Vec<Lane> = Vec::new();
6742 for x in &pend_before {
6743 if !lanes_seen.contains(&x.0) {
6744 lanes_seen.push(x.0);
6745 }
6746 }
6747 let mut paired: Vec<Lane> = Vec::new();
6748 for &l in &lanes_seen {
6749 let b: Vec<&(Lane, String, u32)> = pend_before.iter().filter(|x| x.0 == l).collect();
6750 let a: Vec<&(Lane, String, u32)> = pend_after.iter().filter(|x| x.0 == l).collect();
6751 if a.len() == b.len() {
6752 paired.push(l);
6753 for (x, y) in b.iter().zip(a.iter()) {
6754 if x.2 != y.2 {
6755 out.push((parse::addr(l, x.2), parse::addr(l, y.2)));
6756 }
6757 }
6758 }
6759 }
6760 let rest_before: Layout = pend_before.iter().filter(|x| !paired.contains(&x.0)).cloned().collect();
6761 let rest_after: Layout = pend_after.iter().filter(|x| !paired.contains(&x.0)).cloned().collect();
6762 out.extend(identity_pairs(&rest_before, &rest_after));
6763 out
6764}
6765
6766/// The clips of lanes whose count changed, paired by what they play (`identity_pairs`'s rule).
6767fn identity_pairs(before: &Layout, after: &Layout) -> Vec<(String, String)> {
6768 if before == after {
6769 return Vec::new();
6770 }
6771 let mut out = Vec::new();
6772 for (i, (lane, key, start)) in before.iter().enumerate() {
6773 let was = before.iter().filter(|x| x.1 == *key).count();
6774 let now: Vec<&(Lane, String, u32)> = after.iter().filter(|x| x.1 == *key).collect();
6775 if now.len() != was {
6776 continue;
6777 }
6778 let nth = before[..i].iter().filter(|x| x.1 == *key).count();
6779 let (nl, _, ns) = now[nth];
6780 if (*nl, *ns) != (*lane, *start) {
6781 out.push((parse::addr(*lane, *start), parse::addr(*nl, *ns)));
6782 }
6783 }
6784 out
6785}
6786
6787/// Lane lines: `V1: @0 0.000–15.000 src:0 · @450 15.000–30.000 src:0`.
6788fn digest(s: &PlaybackSession, lanes: &[Lane], fps: f64) -> String {
6789 const MAX: usize = 12;
6790 let mut out = Vec::new();
6791 for l in s.lanes() {
6792 if !lanes.contains(&l) {
6793 continue;
6794 }
6795 let items: Vec<String> = if l.kind == LaneKind::Subtitle {
6796 s.sub_lane(l)
6797 .iter()
6798 .map(|c| {
6799 let end = c.start.saturating_add(c.frames);
6800 format!("@{} {:.3}–{:.3} caption", c.start, parse::secs(c.start, fps), parse::secs(end, fps))
6801 })
6802 .collect()
6803 } else {
6804 s.lane_clips(l)
6805 .iter()
6806 .map(|c| {
6807 format!(
6808 "@{} {:.3}–{:.3} src:{}",
6809 c.start,
6810 parse::secs(c.start, fps),
6811 parse::secs(c.end(), fps),
6812 c.source
6813 )
6814 })
6815 .collect()
6816 };
6817 let body = if items.is_empty() {
6818 "no clips".to_string()
6819 } else {
6820 let mut shown: Vec<String> = items.iter().take(MAX).cloned().collect();
6821 if items.len() > MAX {
6822 shown.push(format!("… {} more", items.len() - MAX));
6823 }
6824 shown.join(" · ")
6825 };
6826 out.push(format!("{}: {body}", parse::lane_name(l)));
6827 }
6828 out.join("\n")
6829}
6830
6831/// One op as a short name for the undo report: `split @45`, `fade V1@0`, `place src:0`.
6832fn op_tag(op: &Value) -> String {
6833 let name = op.get("op").and_then(Value::as_str).unwrap_or("?");
6834 let text = |v: &Value| match v {
6835 Value::String(t) => t.clone(),
6836 other => other.to_string(),
6837 };
6838 let target = if let Some(c) = op.get("clip") {
6839 text(c)
6840 } else if let Some(t) = op.get("title") {
6841 text(t)
6842 } else if let Some(l) = op.get("lane") {
6843 text(l)
6844 } else if let Some(k) = op.get("kind") {
6845 text(k)
6846 } else if let Some(src) = op.get("source") {
6847 format!("src:{}", text(src).trim_start_matches("src:"))
6848 } else if let Some(a) = op.get("at") {
6849 format!("@{}", text(a))
6850 } else {
6851 String::new()
6852 };
6853 if target.is_empty() {
6854 name.to_string()
6855 } else {
6856 format!("{name} {target}")
6857 }
6858}
6859
6860/// One clip op as the apply reply names it: the op and the clips it touched (`fade V1@0, A1@0`), so a
6861/// linked fade reads with its sound. None for an op with no `clip` or that touched nothing.
6862fn clip_tag(op: &Value, touched: &[String]) -> Option<String> {
6863 if op.get("clip").is_none() || touched.is_empty() {
6864 return None;
6865 }
6866 const NAMED: usize = 3;
6867 let mut text = touched.iter().take(NAMED).cloned().collect::<Vec<_>>().join(", ");
6868 if touched.len() > NAMED {
6869 text.push_str(&format!(" +{} more", touched.len() - NAMED));
6870 }
6871 let name = op.get("op").and_then(Value::as_str).unwrap_or("?");
6872 Some(format!("{name} {text}"))
6873}
6874
6875/// A batch's default undo label: its first two ops, then how many more. A clip op is named by the
6876/// clips its apply reply names (`touched`, one list per op), so the label matches what was applied.
6877fn summarize(ops: &[Value], touched: &[Vec<String>]) -> String {
6878 let tags: Vec<String> = ops
6879 .iter()
6880 .enumerate()
6881 .map(|(k, op)| clip_tag(op, touched.get(k).map_or(&[][..], Vec::as_slice)).unwrap_or_else(|| op_tag(op)))
6882 .collect();
6883 match tags.len() {
6884 0 => "edit".to_string(),
6885 1 | 2 => tags.join(" + "),
6886 n => format!("{} + {} (+{} more)", tags[0], tags[1], n - 2),
6887 }
6888}
6889
6890/// Takes `n` engine undo steps back. False if the engine would not take one.
6891/// "1 edit batch" or "3 edit batches", for the undo and redo refusals.
6892fn batches(n: usize) -> String {
6893 if n == 1 {
6894 "1 edit batch".to_string()
6895 } else {
6896 format!("{n} edit batches")
6897 }
6898}
6899
6900fn undo_n(s: &mut PlaybackSession, n: usize) -> bool {
6901 (0..n).all(|_| s.undo())
6902}
6903
6904fn redo_n(s: &mut PlaybackSession, n: usize) -> bool {
6905 (0..n).all(|_| s.redo())
6906}
6907
6908thread_local! {
6909 /// What the batch being run wrote outside the project file: the freeze stills it saved and the
6910 /// `freeze` folder it made, in the order written. A refused batch takes these back.
6911 static BATCH_WRITES: std::cell::RefCell<Vec<PathBuf>> = const { std::cell::RefCell::new(Vec::new()) };
6912}
6913
6914/// Notes a path the current batch wrote, so a refusal can take it back.
6915fn note_write(path: PathBuf) {
6916 BATCH_WRITES.with(|w| w.borrow_mut().push(path));
6917}
6918
6919/// Takes back what the current batch wrote, newest first: each still, then the folder it made
6920/// (which goes only when empty). Files the batch did not create are never noted, so never removed.
6921fn take_back_writes() {
6922 let writes = BATCH_WRITES.with(|w| std::mem::take(&mut *w.borrow_mut()));
6923 for p in writes.iter().rev() {
6924 let _ = if p.is_dir() { std::fs::remove_dir(p) } else { std::fs::remove_file(p) };
6925 }
6926}
6927
6928/// Where a batch starts: the engine's push count, the source count, and whether the project was
6929/// clean (saved and unchanged), which a rollback restores.
6930struct BatchMark {
6931 pushes: u64,
6932 sources: usize,
6933 clean: bool,
6934 /// The redo history the batch found, until it is put back or kept (see [`SavedRedo`]).
6935 redo: Option<SavedRedo>,
6936}
6937
6938/// What a batch found before its ops ran: the engine's redo stack and the ledger's redo entries, and
6939/// the undo cap held open. The ops clear the redo stack and their pushes can evict the oldest undo
6940/// step, and the rollback fills the redo stack, so a batch that is rolled back puts all of it back
6941/// and one that is kept lets it go.
6942struct SavedRedo {
6943 stack: RedoCheckpoint,
6944 ledger: Vec<Entry>,
6945}
6946
6947impl SavedRedo {
6948 fn take(s: &mut PlaybackSession, ledger: &mut Vec<Entry>) -> Self {
6949 s.hold_history(true);
6950 Self { stack: s.take_redo(), ledger: std::mem::take(ledger) }
6951 }
6952}
6953
6954/// Puts back the redo history a rolled-back batch took out, if it has not been put back yet.
6955fn put_back_redo(mark: &mut BatchMark, s: &mut PlaybackSession, ledger: &mut Vec<Entry>) {
6956 if let Some(saved) = mark.redo.take() {
6957 s.restore_redo(saved.stack);
6958 *ledger = saved.ledger;
6959 s.hold_history(false);
6960 }
6961}
6962
6963/// Lets go of the redo history a kept batch took out: its own edits cleared it, as they always did.
6964fn keep_redo(mark: &mut BatchMark, s: &mut PlaybackSession) {
6965 if mark.redo.take().is_some() {
6966 s.hold_history(false);
6967 }
6968}
6969
6970/// Takes back the sources a rolled-back batch imported (a freeze's still), newest first, with
6971/// `remove_unused_source`, which keeps the undo and redo history: a source that an undo or redo step
6972/// still names stays, and the caller says so. Returns how many were taken back.
6973fn drop_batch_sources(s: &mut PlaybackSession, sources_before: usize) -> usize {
6974 let mut taken = 0;
6975 while s.sources().len() > sources_before {
6976 let Some(src) = s.sources().last().cloned() else { break };
6977 if s.remove_unused_source(&src.path, src.audio_stream).is_err() {
6978 break;
6979 }
6980 taken += 1;
6981 }
6982 taken
6983}
6984
6985/// A failed batch: roll back what it pushed, take back the sources it imported, and say so.
6986fn refuse(srv: &mut Server, mark: BatchMark, k: usize, name: &str, msg: &str) -> Reply {
6987 let tail = roll_back(srv, mark);
6988 Reply::err(format!("op {k} ({name}) failed: {msg}; {tail}"))
6989}
6990
6991/// An op that is not an object with an `op` name: the refusal says what the op must look like,
6992/// with no name to show, and the batch is rolled back the same way.
6993fn refuse_shape(srv: &mut Server, mark: BatchMark, k: usize, msg: &str) -> Reply {
6994 let tail = roll_back(srv, mark);
6995 Reply::err(format!("op {k} {msg}; {tail}"))
6996}
6997
6998/// Rolls a refused batch back and returns the words that say so for the refusal.
6999fn roll_back(srv: &mut Server, mut mark: BatchMark) -> String {
7000 let Some(s) = srv.session.as_mut() else {
7001 return NO_PROJECT.to_string();
7002 };
7003 let n = pushed_since(s, mark.pushes);
7004 let note = if undo_n(s, n) {
7005 ""
7006 } else {
7007 " (the engine would not undo every step; check the project before going on)"
7008 };
7009 // The undo above left the rolled-back states on the redo history: they are not a branch to redo,
7010 // so the history the batch found goes back in their place.
7011 put_back_redo(&mut mark, s, &mut srv.redo_ledger);
7012 drop_batch_sources(s, mark.sources);
7013 take_back_writes();
7014 if mark.clean {
7015 // The rollback leaves the project as it was: a project that was clean reads clean again.
7016 srv.saved_depth = Some(s.undo_depth());
7017 srv.saved_pushes = Some(s.history_pushes());
7018 srv.saved_sources = Some(s.sources().len());
7019 }
7020 // A source a batch imported stays in the library when it could not be taken back unharmed.
7021 let kept_note = if s.sources().len() > mark.sources {
7022 " (the still stays in the media library; media_remove drops it)"
7023 } else {
7024 ""
7025 };
7026 srv.trim_ledger();
7027 format!("batch rolled back, nothing changed{note}{kept_note}")
7028}
7029
7030/// Snapshots the engine pushed since `start` (a `history_pushes` reading). Exact
7031/// even at the cap, where the undo depth no longer grows.
7032fn pushed_since(s: &PlaybackSession, start: u64) -> usize {
7033 s.history_pushes().saturating_sub(start) as usize
7034}
7035
7036/// The whole project as text: the engine's own project dump (sources, lanes with their gain,
7037/// flags, clips, eq, color, transform, captions, cues, titles, settings and the limiter). Two equal
7038/// texts are the same state, so a batch whose state matches the state before it changed nothing.
7039/// Only the undo bookkeeping is left out: `pushes` counts every snapshot ever taken and an undo
7040/// never restores it, and `revision` is minted by every snapshot (a no-op's too), so either would
7041/// make every batch look like a change.
7042fn state_of(s: &PlaybackSession) -> String {
7043 let (project, _meta) = s.raw_snapshot();
7044 without_tables(&without_counters(&format!("{project:?}")))
7045}
7046
7047/// `dump` with the append-only effect tables (eq, color, transform) removed. An undo never takes
7048/// their entries back, so a grade undone would read as a change; each clip still names its own
7049/// entry (`color: Some(n)`), so a real change to a clip's grade is still seen.
7050fn without_tables(dump: &str) -> String {
7051 let mut out = dump.to_string();
7052 for key in ["eq: [", "color: [", "transform: ["] {
7053 // A field of its own name only: `box_color: [` (a title's box) is not the `color: [` table.
7054 let mut from = 0;
7055 while let Some(i) = out[from..].find(key).map(|i| i + from) {
7056 if out[..i].chars().next_back().is_some_and(|c| c.is_alphanumeric() || c == '_') {
7057 from = i + key.len();
7058 continue;
7059 }
7060 let open = i + key.len() - 1;
7061 let mut depth = 0usize;
7062 let mut end = None;
7063 for (k, ch) in out[open..].char_indices() {
7064 match ch {
7065 '[' => depth += 1,
7066 ']' => {
7067 depth -= 1;
7068 if depth == 0 {
7069 end = Some(open + k + 1);
7070 break;
7071 }
7072 }
7073 _ => {}
7074 }
7075 }
7076 let Some(end) = end else { break };
7077 let tail = if out[end..].starts_with(", ") { end + 2 } else { end };
7078 out.replace_range(i..tail, "");
7079 }
7080 }
7081 out
7082}
7083
7084/// `dump` with the value of every bookkeeping id removed: `pushes: N` (the snapshot count) and
7085/// `revision: N` (the state id, which every snapshot mints afresh, a no-op batch's included, and an
7086/// undo restores). Neither is timeline content, so neither makes a batch a change.
7087fn without_counters(dump: &str) -> String {
7088 ["pushes: ", "revision: "].iter().fold(dump.to_string(), |text, key| without_value(&text, key))
7089}
7090
7091/// `dump` with the digits after every `key` removed (the key itself stays).
7092fn without_value(dump: &str, key: &str) -> String {
7093 let mut out = String::with_capacity(dump.len());
7094 let mut rest = dump;
7095 while let Some(i) = rest.find(key) {
7096 out.push_str(&rest[..i + key.len()]);
7097 rest = &rest[i + key.len()..];
7098 let digits = rest.bytes().take_while(u8::is_ascii_digit).count();
7099 rest = &rest[digits..];
7100 }
7101 out.push_str(rest);
7102 out
7103}
7104
7105/// Notes on the timeline's ends for a batch reply: a video lane that stops short of the
7106/// timeline end, and picture that ends before sound (black after the picture). Empty when the
7107/// ends agree to within a frame.
7108fn tail_notes(s: &PlaybackSession, fps: f64) -> Vec<String> {
7109 let end = parse::session_end(s);
7110 let mut notes = Vec::new();
7111 let mut video_end: Option<u32> = None;
7112 let mut audio_end: Option<u32> = None;
7113 for l in s.lanes() {
7114 if l.kind == LaneKind::Subtitle {
7115 continue;
7116 }
7117 let Some(lane_end) = s.lane_clips(l).iter().map(|c| c.end()).max() else {
7118 continue;
7119 };
7120 if l.kind == LaneKind::Video {
7121 video_end = Some(video_end.map_or(lane_end, |v| v.max(lane_end)));
7122 if lane_end + 1 < end {
7123 notes.push(format!(
7124 "{} ends {} before the timeline end",
7125 parse::lane_name(l),
7126 secs_text(end - lane_end, fps)
7127 ));
7128 }
7129 } else {
7130 audio_end = Some(audio_end.map_or(lane_end, |a| a.max(lane_end)));
7131 }
7132 }
7133 if let (Some(v), Some(a)) = (video_end, audio_end)
7134 && a > v + 1
7135 {
7136 notes.push(format!(
7137 "picture ends at {} but sound runs to {} — {} of black",
7138 secs_text(v, fps),
7139 secs_text(a, fps),
7140 secs_text(a - v, fps)
7141 ));
7142 }
7143 // A picture lane above the picture underneath that runs past its end shows over black there (a logo
7144 // left after the picture shrank): named by its lane. The picture underneath is the lowest video lane
7145 // with clips (V1 unless a lane_move put another lane below it), and only lanes above it are checked.
7146 let video: Vec<Lane> = s.lanes().into_iter().filter(|l| l.kind == LaneKind::Video).collect();
7147 if let Some(&base) = video.iter().find(|&&l| !s.lane_clips(l).is_empty()) {
7148 let base_end = s.lane_clips(base).iter().map(|c| c.end()).max().unwrap_or(0);
7149 for &l in video.iter().skip_while(|&&l| l != base).skip(1) {
7150 let Some(e) = s.lane_clips(l).iter().map(|c| c.end()).max() else {
7151 continue;
7152 };
7153 if e > base_end + 1 {
7154 notes.push(format!(
7155 "{} runs {} past the picture's end at {}",
7156 parse::lane_name(l),
7157 secs_text(e - base_end, fps),
7158 secs_text(base_end, fps)
7159 ));
7160 }
7161 }
7162 }
7163 // A caption or title that runs past the last picture frame shows over black: name it.
7164 if let Some(v) = video_end {
7165 for l in s.lanes().into_iter().filter(|l| l.kind == LaneKind::Subtitle) {
7166 let Some(e) = s.sub_lane(l).iter().map(|c| c.start + c.frames).max() else {
7167 continue;
7168 };
7169 if e > v + 1 {
7170 notes.push(format!(
7171 "{} runs {} past the picture's end at {}",
7172 parse::lane_name(l),
7173 secs_text(e - v, fps),
7174 secs_text(v, fps)
7175 ));
7176 }
7177 }
7178 for (i, t) in s.titles().iter().enumerate() {
7179 let e = t.start + t.frames;
7180 if e > v + 1 {
7181 notes.push(format!(
7182 "T{} runs {} past the picture's end at {}",
7183 i + 1,
7184 secs_text(e - v, fps),
7185 secs_text(v, fps)
7186 ));
7187 }
7188 }
7189 }
7190 notes
7191}
7192
7193/// One clip or caption for an op's side effects: its lane, what it plays (its source and in
7194/// point, which a move, a ripple or an out-edge trim leaves alone), its start and its link.
7195type Item = (Lane, String, u32, Option<u32>);
7196
7197/// The timeline's shape for one op's side effects: every clip and caption as an `Item`, and each
7198/// lane's clip count and gap count.
7199pub(crate) struct Shape {
7200 items: Vec<Item>,
7201 clips: Vec<(Lane, usize)>,
7202 holes: Vec<(Lane, usize)>,
7203 /// The empty spans between a lane's clips, in frames, so a hole the op left can be named by its range.
7204 gaps: Vec<(Lane, u32, u32)>,
7205 /// The gaps close_gaps would leave open, with the reason (see `take_gap_refusal`).
7206 stuck: Vec<(Lane, u32, u32, String)>,
7207 /// The timeline's frame rate, for naming those spans in seconds.
7208 fps: f64,
7209 /// Per media lane: its dissolves (count and total frames) and its clips with a fade.
7210 marks: Vec<(Lane, Marks)>,
7211 /// Every clip with a dissolve out, and the clip the engine blends it into (the one right after it,
7212 /// only while the two are adjacent: a gap makes it a hard cut).
7213 joins: Vec<Join>,
7214}
7215
7216/// A dissolve out: the clip that owns it (`lane`, its identity, its start) and the clip it joins.
7217#[derive(Clone)]
7218struct Join {
7219 lane: Lane,
7220 ident: String,
7221 start: u32,
7222 next: Option<(String, u32)>,
7223}
7224
7225/// What a lane's transitions and fades add up to: dissolves (clips and frames), fades (clips).
7226#[derive(Clone, Copy, Default)]
7227struct Marks {
7228 dissolves: usize,
7229 dissolve_frames: u32,
7230 fades: usize,
7231}
7232
7233pub(crate) fn shape(s: &PlaybackSession) -> Shape {
7234 let mut items = Vec::new();
7235 let mut clips = Vec::new();
7236 let mut holes = Vec::new();
7237 let mut marks = Vec::new();
7238 let mut gaps = Vec::new();
7239 let mut stuck = Vec::new();
7240 let mut joins = Vec::new();
7241 for l in s.lanes() {
7242 holes.push((l, s.gap_count(l)));
7243 if l.kind != LaneKind::Subtitle {
7244 let mut prev_end: Option<u32> = None;
7245 for c in s.lane_clips(l) {
7246 if let Some(p) = prev_end.filter(|&p| c.start > p) {
7247 gaps.push((l, p, c.start));
7248 if let Some(why) = take_gap_refusal(s, l, p, c.start - p) {
7249 stuck.push((l, p, c.start, why));
7250 }
7251 }
7252 prev_end = Some(prev_end.map_or(c.end(), |p| p.max(c.end())));
7253 }
7254 }
7255 if l.kind == LaneKind::Subtitle {
7256 items.extend(s.sub_lane(l).iter().map(|c| (l, format!("caption {}:{}", c.track, c.in_us), c.start, c.link)));
7257 } else {
7258 let lane_clips = s.lane_clips(l);
7259 clips.push((l, lane_clips.len()));
7260 items.extend(lane_clips.iter().map(|c| (l, format!("clip {}:{}", c.source, c.in_frame), c.start, c.link)));
7261 for (i, c) in lane_clips.iter().enumerate().filter(|(_, c)| c.transition_out > 0) {
7262 let next = lane_clips.get(i + 1).filter(|b| b.start == c.end()).map(|b| (format!("clip {}:{}", b.source, b.in_frame), b.start));
7263 joins.push(Join { lane: l, ident: format!("clip {}:{}", c.source, c.in_frame), start: c.start, next });
7264 }
7265 let dissolving = lane_clips.iter().filter(|c| c.transition_out > 0);
7266 marks.push((
7267 l,
7268 Marks {
7269 dissolves: dissolving.clone().count(),
7270 dissolve_frames: dissolving.map(|c| c.transition_out).sum(),
7271 fades: lane_clips.iter().filter(|c| c.fade_in > 0 || c.fade_out > 0).count(),
7272 },
7273 ));
7274 }
7275 }
7276 Shape { items, clips, holes, gaps, stuck, fps: parse::session_fps(s), marks, joins }
7277}
7278
7279/// The item in `shape` that is the clip `lane`, `ident` starts at `start`. A clip's identity is what
7280/// it plays, so two clips of one source at one in-point on one lane share it (a copy placed earlier
7281/// on the lane, say): the one at `start` is taken, else the only one there is. Several with none at
7282/// `start` are ambiguous, and None: a clip is never matched to the wrong partner's state.
7283fn same_clip<'a>(shape: &'a Shape, lane: Lane, ident: &str, start: u32) -> Option<&'a Item> {
7284 let cands: Vec<&Item> = shape.items.iter().filter(|x| x.0 == lane && x.1 == ident).collect();
7285 match cands.iter().find(|x| x.2 == start) {
7286 Some(x) => Some(*x),
7287 None if cands.len() == 1 => Some(cands[0]),
7288 None => None,
7289 }
7290}
7291
7292/// The link of the item in `shape` that is `a` (same lane, same source): `None` when there is no such item.
7293fn matched_link(shape: &Shape, a: &Item) -> Option<Option<u32>> {
7294 same_clip(shape, a.0, &a.1, a.2).map(|x| x.3)
7295}
7296
7297/// Whether a lane that gained clips was split rather than given a clip from elsewhere. A split leaves
7298/// a new piece of a clip the lane already had (the same source, a new in-point); a clip moved or
7299/// copied in from another lane brings a source the lane did not hold, so it is not a split.
7300fn lane_split(before: &Shape, after: &Shape, l: Lane) -> bool {
7301 let source = |id: &str| id.split(':').next().unwrap_or("").to_string();
7302 let was: Vec<&Item> = before.items.iter().filter(|x| x.0 == l).collect();
7303 after.items.iter().filter(|x| x.0 == l).any(|a| {
7304 !was.iter().any(|b| b.1 == a.1) && was.iter().any(|b| source(&b.1) == source(&a.1))
7305 })
7306}
7307
7308/// The lanes an op left a hole on, each with the gaps it added there: frames (start, end) and the reason
7309/// close_gaps would keep the gap open, None when it closes. A lane that was empty before has no hole
7310/// to leave: the silence before a first clip is the lane's own. A lane op leaves none.
7311pub(crate) fn holes_added(before: &Shape, after: &Shape, name: &str) -> Vec<(Lane, Gaps)> {
7312 if matches!(name, "lane_move" | "lane_add" | "lane_remove") {
7313 return Vec::new();
7314 }
7315 // Frames of empty time on a lane: a hole can grow without a new gap (an insert into a gap it left).
7316 let empty = |sh: &Shape, l: Lane| -> u32 { sh.gaps.iter().filter(|g| g.0 == l).map(|g| g.2 - g.1).sum() };
7317 let mut out = Vec::new();
7318 for &(l, _) in &after.holes {
7319 if !before.items.iter().any(|x| x.0 == l) {
7320 continue;
7321 }
7322 if empty(after, l) > empty(before, l) {
7323 // A gap the op only moved (a cut before it, an insert of a freeze) was there already: each
7324 // gap before the op answers for at most one gap after it, the same span first, else one of
7325 // the same length. What is left over is the hole the op made.
7326 let mut was_gaps: Vec<(u32, u32)> = before.gaps.iter().filter(|g| g.0 == l).map(|g| (g.1, g.2)).collect();
7327 let mut added: Gaps = Vec::new();
7328 for g in after.gaps.iter().filter(|g| g.0 == l) {
7329 let span = (g.1, g.2);
7330 let found = was_gaps
7331 .iter()
7332 .position(|x| *x == span)
7333 .or_else(|| was_gaps.iter().position(|x| x.1 - x.0 == span.1 - span.0));
7334 match found {
7335 Some(i) => {
7336 was_gaps.remove(i);
7337 }
7338 None => {
7339 let why = after.stuck.iter().find(|x| x.0 == g.0 && x.1 == g.1 && x.2 == g.2).map(|x| x.3.clone());
7340 added.push((g.1, g.2, why));
7341 }
7342 }
7343 }
7344 if !added.is_empty() {
7345 out.push((l, added));
7346 }
7347 }
7348 }
7349 out
7350}
7351
7352/// The gaps one op left on a lane, as [`batch_hole_lines`] reads them: frames (start, end) and the
7353/// reason close_gaps keeps each open (None when it closes).
7354type Gaps = Vec<(u32, u32, Option<String>)>;
7355
7356/// The gaps one op left on each lane (see [`holes_added`]).
7357type Holes = Vec<(Lane, Gaps)>;
7358
7359/// What to tell the caller about closing the gaps a hole left on `lane`: the close_gaps call when it
7360/// would close them, else why it cannot (a take with a partner that has no gap there), so no reply
7361/// sends the caller to a close_gaps that reports nothing closed. `plural` for a line naming several.
7362fn close_clause(lane: Lane, gaps: &[(u32, u32, Option<String>)], plural: bool) -> String {
7363 let name = parse::lane_name(lane);
7364 let it = if plural { "them" } else { "it" };
7365 let mut reasons: Vec<&str> = Vec::new();
7366 for why in gaps.iter().filter_map(|g| g.2.as_deref()) {
7367 if !reasons.contains(&why) {
7368 reasons.push(why);
7369 }
7370 }
7371 let stuck = gaps.iter().filter(|g| g.2.is_some()).count();
7372 if stuck == 0 {
7373 format!("close_gaps {{lane:\"{name}\"}} closes {it}")
7374 } else if stuck == gaps.len() {
7375 format!("close_gaps cannot close {it}: {}", reasons.join("; "))
7376 } else {
7377 format!("close_gaps {{lane:\"{name}\"}} closes the others; {}", reasons.join("; "))
7378 }
7379}
7380
7381/// The summary lines for a batch in which more than one op left a hole: one line per lane, naming the
7382/// gaps the batch left there in order (the first two, then `…`). Each line is paired with the index of
7383/// the op it prints under, the first op to leave a hole on that lane.
7384fn batch_hole_lines(holes: &[Holes], fps: f64) -> Vec<(usize, String)> {
7385 let mut lanes: Vec<(Lane, usize, Gaps)> = Vec::new();
7386 for (k, ops) in holes.iter().enumerate() {
7387 for (l, gaps) in ops {
7388 let i = match lanes.iter().position(|x| x.0 == *l) {
7389 Some(i) => i,
7390 None => {
7391 lanes.push((*l, k, Vec::new()));
7392 lanes.len() - 1
7393 }
7394 };
7395 // A gap that a repeated op leaves again starts at the same frame: it is named once.
7396 for g in gaps {
7397 if !lanes[i].2.iter().any(|x| x.0 == g.0) {
7398 lanes[i].2.push(g.clone());
7399 }
7400 }
7401 }
7402 }
7403 lanes
7404 .into_iter()
7405 .map(|(l, k, gaps)| {
7406 let name = parse::lane_name(l);
7407 let at = if gaps.is_empty() {
7408 String::new()
7409 } else {
7410 let shown: Vec<String> = gaps.iter().take(2).map(|g| format!("{:.3}s", parse::secs(g.0, fps))).collect();
7411 let more = if gaps.len() > 2 { ", …" } else { "" };
7412 format!(" at {}{more}", shown.join(", "))
7413 };
7414 (k, format!("holes left on {name}{at} ({})", close_clause(l, &gaps, true)))
7415 })
7416 .collect()
7417}
7418
7419/// The note for a placement that left a gap before the clip it put down: longer than 10 s, or longer
7420/// than the timeline was before the op (`end_then`). `touched` is the op's clips, the first one the
7421/// placed clip. None when the clip sits against what is before it.
7422fn placement_gap_note(s: &PlaybackSession, touched: &[(Lane, u32)], end_then: u32, fps: f64) -> Option<String> {
7423 let &(lane, start) = touched.iter().find(|(l, _)| l.kind != LaneKind::Subtitle)?;
7424 let prev_end = s.lane_clips(lane).iter().filter(|c| c.start < start).map(|c| c.end()).max().unwrap_or(0);
7425 let gap = start.saturating_sub(prev_end);
7426 let long = parse::secs(gap, fps) > 10.0;
7427 if gap == 0 || !(long || (end_then > 0 && gap > end_then)) {
7428 return None;
7429 }
7430 Some(format!(
7431 "left a {} gap before it on {} (the timeline was {})",
7432 secs_text(gap, fps),
7433 parse::lane_name(lane),
7434 secs_text(end_then, fps)
7435 ))
7436}
7437
7438/// The side effects of one op beyond its own edit, diffed from the state before and after it:
7439/// clips split, holes left, takes unlinked (a take that lost members is still whole when the
7440/// members left share a link), and takes linked by a group.
7441pub(crate) fn side_effects(before: &Shape, after: &Shape, name: &str) -> Vec<String> {
7442 let mut out = Vec::new();
7443 // A lane op renames lanes (lane_move reorders them), so per-lane counts say nothing there.
7444 if matches!(name, "lane_move" | "lane_add" | "lane_remove") {
7445 return out;
7446 }
7447 // A visualizer on a sound clip places its picture as a new clip, which is a placement, not a split.
7448 let placing = matches!(name, "place" | "append" | "keep" | "assemble" | "generator_add" | "adjustment_add" | "freeze" | "title_add" | "subtitles_import" | "lane_add" | "visualizer");
7449 let mut split = false;
7450 if !placing {
7451 for &(l, n) in &after.clips {
7452 let was = before.clips.iter().find(|x| x.0 == l).map_or(0, |x| x.1);
7453 if n > was && lane_split(before, after, l) {
7454 split = true;
7455 out.push(format!("split {} ×{}", parse::lane_name(l), n - was));
7456 }
7457 }
7458 }
7459 for (l, added) in holes_added(before, after, name) {
7460 // Named by the span it is: the gaps the op added on this lane, in seconds.
7461 let spans: Vec<String> = added
7462 .iter()
7463 .map(|&(a, b, _)| format!("{:.3}–{:.3}s", parse::secs(a, after.fps), parse::secs(b, after.fps)))
7464 .collect();
7465 let range = if spans.is_empty() { String::new() } else { format!(" at {}", spans.join(", ")) };
7466 out.push(format!("hole left on {}{range} by {name}; {}", parse::lane_name(l), close_clause(l, &added, false)));
7467 }
7468 // A transition or fade the op took away is named, so it is never dropped silently: a dissolve
7469 // whose clip or successor went (dropped), or one that kept its clip but lost frames (shortened).
7470 for &(l, now) in &after.marks {
7471 let was = before.marks.iter().find(|x| x.0 == l).map_or(Marks::default(), |x| x.1);
7472 let name = parse::lane_name(l);
7473 if now.dissolves < was.dissolves {
7474 // Named by the clip whose dissolve went, as it was before the op; a count the names do not
7475 // account for keeps the lane's count.
7476 let gone: Vec<String> = dropped_joins(before, after, l).iter().map(|j| parse::addr(l, j.start)).collect();
7477 if gone.len() == was.dissolves - now.dissolves {
7478 out.extend(gone.iter().map(|a| format!("dissolve dropped on {a}")));
7479 } else {
7480 out.push(format!("dissolve dropped on {name} ×{}", was.dissolves - now.dissolves));
7481 }
7482 } else if now.dissolve_frames < was.dissolve_frames {
7483 out.push(format!("dissolve shortened on {name} by {}f", was.dissolve_frames - now.dissolve_frames));
7484 }
7485 if now.fades < was.fades {
7486 out.push(format!("fade dropped on {name} ×{}", was.fades - now.fades));
7487 }
7488 }
7489 // A dissolve that survives may now blend into another clip: the one after it moved, went, or its gap
7490 // closed. The engine blends only into the next clip while they are adjacent, so that is what is named.
7491 for j in &before.joins {
7492 let Some(item) = same_clip(after, j.lane, &j.ident, j.start) else { continue };
7493 let Some(now) = after.joins.iter().find(|a| a.lane == j.lane && a.ident == item.1 && a.start == item.2) else { continue };
7494 let owner = parse::addr(j.lane, item.2);
7495 match (&j.next, &now.next) {
7496 (Some((bi, bs)), Some((ai, a_start))) if bi != ai => {
7497 let was = if same_clip(after, j.lane, bi, *bs).is_some() { parse::addr(j.lane, *bs) } else { "the deleted clip".to_string() };
7498 out.push(format!("{owner}'s dissolve now joins {} (was {was})", parse::addr(j.lane, *a_start)));
7499 }
7500 (Some(_), None) => out.push(format!("{owner}'s dissolve has no clip right after it now: it plays as a hard cut")),
7501 (None, Some((_, a_start))) => out.push(format!("{owner}'s dissolve now joins {}", parse::addr(j.lane, *a_start))),
7502 _ => {}
7503 }
7504 }
7505 // A trim keeps its take's links on purpose (its own reply says so).
7506 if !matches!(name, "trim" | "sub_trim") {
7507 let mut ids: Vec<u32> = before.items.iter().filter_map(|x| x.3).collect();
7508 ids.sort_unstable();
7509 ids.dedup();
7510 for id in ids {
7511 let members: Vec<&Item> = before.items.iter().filter(|x| x.3 == Some(id)).collect();
7512 if members.len() < 2 {
7513 // An orphan link (one member) was already unlinked before the op.
7514 continue;
7515 }
7516 // Each member is found again by the clip it is, not by what it plays alone: a copy of the
7517 // same source at the same in-point elsewhere on its lane must not stand in for it.
7518 let found: Vec<(&Item, Option<&Item>)> = members.iter().map(|m| (*m, same_clip(after, m.0, &m.1, m.2))).collect();
7519 let survivors: Vec<&Item> = found.iter().filter(|(_, a)| a.is_some()).map(|(m, _)| *m).collect();
7520 if survivors.is_empty() {
7521 continue;
7522 }
7523 // `now` is one new link per survivor, in the survivors' order.
7524 let now: Vec<Option<u32>> = found.iter().filter_map(|(_, a)| a.map(|a| a.3)).collect();
7525 // A survivor is a take partner while another survivor shares its new link; only the rest detach.
7526 let shares = |i: usize| now[i].is_some() && now.iter().enumerate().any(|(j, x)| j != i && *x == now[i]);
7527 if name == "ungroup" {
7528 // Survivors that still share one link are one take: named once, with the partners in order.
7529 let mut links: Vec<u32> = now.iter().flatten().copied().collect();
7530 links.sort_unstable();
7531 links.dedup();
7532 for l in links {
7533 let kept: Vec<String> = survivors.iter().zip(&now).filter(|(_, x)| **x == Some(l)).map(|(m, _)| parse::addr(m.0, m.2)).collect();
7534 if kept.len() >= 2 {
7535 out.push(format!("{} stay one take", kept.join("+")));
7536 }
7537 }
7538 }
7539 // One line per detached survivor: the words `clip_info` and the timeline use.
7540 let why = if survivors.len() < members.len() { " (its partner was removed)" } else { "" };
7541 for (i, m) in survivors.iter().enumerate() {
7542 if shares(i) {
7543 continue;
7544 }
7545 let addr = parse::addr(m.0, m.2);
7546 out.push(if split {
7547 format!("{addr} is now detached at the cut")
7548 } else {
7549 format!("{addr} is now detached{why}")
7550 });
7551 }
7552 }
7553 }
7554 // Clips that now share a link, which the op's own group made: members whose
7555 // earlier links differ, or that were unlinked before.
7556 let mut ids: Vec<u32> = after.items.iter().filter_map(|x| x.3).collect();
7557 ids.sort_unstable();
7558 ids.dedup();
7559 for id in ids {
7560 let members: Vec<&Item> = after.items.iter().filter(|x| x.3 == Some(id)).collect();
7561 if members.len() < 2 {
7562 continue;
7563 }
7564 let was: Vec<Option<u32>> = members.iter().filter_map(|m| matched_link(before, m)).collect();
7565 if was.is_empty() || was.iter().all(|x| *x == was[0]) && was[0].is_some() {
7566 continue;
7567 }
7568 let addrs: Vec<String> = members.iter().map(|m| parse::addr(m.0, m.2)).collect();
7569 out.push(format!("linked: {}", addrs.join(" + ")));
7570 }
7571 out
7572}
7573
7574/// The clips on the lanes (not captions) that lie wholly inside `start..end` now, as `(lane, start, link)`:
7575/// what a delete of that span takes out. Read before the op.
7576fn clips_within(s: &PlaybackSession, lanes: &[Lane], start: u32, end: u32) -> Vec<(Lane, u32, Option<u32>)> {
7577 lanes
7578 .iter()
7579 .filter(|l| l.kind != LaneKind::Subtitle)
7580 .flat_map(|&l| s.lane_clips(l).iter().filter(move |c| c.start >= start && c.end() <= end).map(move |c| (l, c.start, c.link)))
7581 .collect()
7582}
7583
7584/// `; removed V1@150 and A1@150 (its take)`: the clips a delete took out, named as they were. The take says
7585/// so when they were all one take. Empty when nothing was removed.
7586fn removed_words(gone: &[(Lane, u32, Option<u32>)]) -> String {
7587 if gone.is_empty() {
7588 return String::new();
7589 }
7590 let addrs: Vec<String> = gone.iter().map(|&(l, st, _)| parse::addr(l, st)).collect();
7591 let list = match addrs.split_last() {
7592 Some((last, rest)) if !rest.is_empty() => format!("{} and {last}", rest.join(", ")),
7593 _ => addrs.join(", "),
7594 };
7595 let take = gone.len() >= 2 && gone[0].2.is_some() && gone.iter().all(|g| g.2 == gone[0].2);
7596 format!("; removed {list}{}", if take { " (its take)" } else { "" })
7597}
7598
7599/// The dissolves on `lane` that the op took away, as they were before it: the clip that owned one is gone,
7600/// or no longer dissolves out.
7601fn dropped_joins<'a>(before: &'a Shape, after: &Shape, lane: Lane) -> Vec<&'a Join> {
7602 before
7603 .joins
7604 .iter()
7605 .filter(|j| j.lane == lane)
7606 .filter(|j| !same_clip(after, lane, &j.ident, j.start).is_some_and(|item| after.joins.iter().any(|a| a.lane == lane && a.ident == item.1 && a.start == item.2)))
7607 .collect()
7608}
7609
7610/// A batch op that names a clip the earlier ops moved gets the reason and the op that moved it,
7611/// so the fix is to re-address or delete from the end. `msg` unchanged for other errors.
7612fn stale_address_hint(shifts: &[Vec<(String, String)>], msg: &str) -> String {
7613 let Some(rest) = msg.strip_prefix("no clip at ") else {
7614 return msg.to_string();
7615 };
7616 let addr = rest.split(';').next().unwrap_or("").trim();
7617 let lane: String = addr.chars().take_while(|c| *c != '@' && *c != '#').collect();
7618 let moved = shifts.iter().enumerate().find_map(|(j, v)| v.iter().find(|(a, _)| a == addr).map(|(_, b)| (j, b.clone())));
7619 match moved {
7620 Some((j, to)) => format!(
7621 "{msg}; ops run in order; op {} moved this clip (now {to}) — earlier ops in this batch shifted {lane} (see their shifted lists); delete from the end or use the new address",
7622 j + 1
7623 ),
7624 None if shifts.iter().flatten().any(|(a, _)| a.starts_with(&lane)) => format!(
7625 "{msg}; ops run in order; earlier ops in this batch shifted {lane} (see their shifted lists); delete from the end or use the new address"
7626 ),
7627 None => msg.to_string(),
7628 }
7629}
7630
7631/// A sound clip with no sound clip meeting it at its end (a gap, or the lane's end) fades out to
7632/// silence over `frames`, and the next clip after a gap fades in from silence over the same. None
7633/// when the next clip meets it: then there is a crossfade to make, not a fade.
7634fn fade_to_silence(s: &mut PlaybackSession, lane: Lane, idx: usize, frames: u32) -> Option<String> {
7635 let (cur_end, cur_frames, next) = {
7636 let clips = s.lane_clips(lane);
7637 let cur = clips.get(idx)?;
7638 (cur.end(), cur.frames(), clips.get(idx + 1).map(|n| (n.start, n.frames())))
7639 };
7640 if matches!(next, Some((st, _)) if st == cur_end) {
7641 return None;
7642 }
7643 let addr = addr_of(s, lane, idx);
7644 let out_n = frames.min(cur_frames);
7645 if !s.set_fade_out(lane, idx, out_n) {
7646 return None;
7647 }
7648 let mut text = format!("sound on {addr} faded out {out_n}f to silence (no sound clip meets it)");
7649 if let Some((st, len)) = next {
7650 let gap = st.saturating_sub(cur_end);
7651 let in_n = frames.min(len);
7652 if s.set_fade_in(lane, idx + 1, in_n) {
7653 text.push_str(&format!(
7654 " and {} faded in from silence over {in_n}f after a {gap}f gap",
7655 addr_of(s, lane, idx + 1)
7656 ));
7657 }
7658 }
7659 Some(text)
7660}
7661
7662pub(super) fn run_edit(srv: &mut Server, args: &Value) -> Reply {
7663 let Some(ops) = args.get("ops").and_then(Value::as_array).filter(|o| !o.is_empty()) else {
7664 return Reply::err(
7665 "missing argument `ops`: give a non-empty list of {op: \"...\", ...} objects; the edit tool description lists each op",
7666 );
7667 };
7668 let dry = opt_bool(args, "dry_run").unwrap_or(false);
7669 let label = opt_str(args, "label").map(str::to_string);
7670 BATCH_WRITES.with(|w| w.borrow_mut().clear());
7671 // A dry run rolls its edits back, but the engine's push count only grows, so the project
7672 // would read as dirty; when it was clean, its save marks are moved past the rolled-back steps.
7673 let was_clean = !super::project::dirty(srv);
7674 let Some(s) = srv.session.as_mut() else {
7675 return Reply::err(NO_PROJECT);
7676 };
7677 let fps = parse::session_fps(s);
7678 let start = s.history_pushes();
7679 let mut mark = BatchMark {
7680 pushes: start,
7681 sources: s.sources().len(),
7682 clean: was_clean,
7683 redo: Some(SavedRedo::take(s, &mut srv.redo_ledger)),
7684 };
7685 let state_before = state_of(s);
7686 let sources_before = s.sources().len();
7687 let end_before = parse::session_end(s);
7688 let project = srv.path.clone();
7689 let tones = crate::server::tone_folder(srv.path.as_deref(), srv.data_home.as_deref());
7690
7691 // The notes that were already true before the batch are not repeated: only what it changed is.
7692 let notes_before = tail_notes(s, fps);
7693 let mut done: Vec<(String, Done)> = Vec::with_capacity(ops.len());
7694 let mut shifts: Vec<Vec<(String, String)>> = Vec::with_capacity(ops.len());
7695 let mut effects: Vec<Vec<String>> = Vec::with_capacity(ops.len());
7696 let mut holes: Vec<Holes> = Vec::with_capacity(ops.len());
7697 let mut gap_notes: Vec<String> = Vec::new();
7698 for (k, op) in ops.iter().enumerate() {
7699 let k1 = k + 1;
7700 if !op.is_object() {
7701 return refuse_shape(srv, mark, k1, "is not an op object: give {\"op\":\"<name>\", …}");
7702 }
7703 let name = op.get("op").and_then(Value::as_str).unwrap_or("").to_string();
7704 if name.is_empty() {
7705 return refuse_shape(
7706 srv,
7707 mark,
7708 k1,
7709 "has no \"op\" name (each op is flat: {\"op\":\"place\",\"source\":\"src:0\",\"at\":\"0s\"})",
7710 );
7711 }
7712 let before = layout(s);
7713 let lanes_before = s.lanes();
7714 let shape_before = shape(s);
7715 let end_then = parse::session_end(s);
7716 let mut op = op.clone();
7717 if let Err(msg) = resolve_title(s, &mut op, fps) {
7718 return refuse(srv, mark, k1, &name, &msg);
7719 }
7720 if name == "lane_move"
7721 && let Err(msg) = lane_move_check(s, &op)
7722 {
7723 return refuse(srv, mark, k1, &name, &msg);
7724 }
7725 let cut = ripple_cut(s, &name, &op, fps);
7726 match run_op(s, &name, &op, fps, project.as_deref(), tones.as_deref(), dry) {
7727 Ok(mut d) => {
7728 if matches!(name.as_str(), "title_add" | "title_set")
7729 && let Some(t) = title_index_in(&d.text).and_then(|i| s.titles().get(i))
7730 {
7731 d.text.push_str(&format!(" (T@{})", t.start));
7732 }
7733 // A placement never ripples, so a clip it "moved" is one it overwrote: the overwrite is named
7734 // as removed or cut in the op's own text, and pairing the removed clip with its replacement
7735 // would list a shift that never happened.
7736 let placing = matches!(name.as_str(), "place" | "append" | "keep" | "assemble" | "generator_add" | "adjustment_add");
7737 if placing && let Some(g) = placement_gap_note(s, &d.touched, end_then, fps) {
7738 gap_notes.push(g);
7739 }
7740 shifts.push(if placing {
7741 Vec::new()
7742 } else if name == "lane_move" {
7743 lane_move_shifts(&op, &lanes_before, &before, &layout(s), &s.lanes())
7744 } else {
7745 shifted_pairs_cut(&before, &layout(s), cut)
7746 });
7747 let shape_after = shape(s);
7748 effects.push(side_effects(&shape_before, &shape_after, &name));
7749 holes.push(holes_added(&shape_before, &shape_after, &name));
7750 done.push((name, d));
7751 }
7752 Err(msg) => {
7753 let msg = stale_address_hint(&shifts, &msg);
7754 return refuse(srv, mark, k1, &name, &msg);
7755 }
7756 }
7757 }
7758
7759 let mut delta = pushed_since(s, start);
7760 // A batch that left the timeline exactly as it was is not an undo step: it is rolled back, and
7761 // the reply says why (an op that found nothing to do names it).
7762 let mut noop_why: Option<String> = None;
7763 if !dry && delta > 0 && state_of(s) == state_before {
7764 let rolled = undo_n(s, delta);
7765 put_back_redo(&mut mark, s, &mut srv.redo_ledger);
7766 drop_batch_sources(s, mark.sources);
7767 take_back_writes();
7768 if mark.clean {
7769 // The rollback leaves the project as it was: a project that was clean reads clean again.
7770 srv.saved_depth = Some(s.undo_depth());
7771 srv.saved_pushes = Some(s.history_pushes());
7772 srv.saved_sources = Some(s.sources().len());
7773 }
7774 noop_why = Some(
7775 done.iter()
7776 .map(|(_, d)| d.text.clone())
7777 .find(|t| t.contains("nothing to cut") || t.contains("nothing to copy") || t.contains("already crossfade"))
7778 .unwrap_or_else(|| "the batch leaves the timeline as it was".to_string())
7779 + if rolled { "" } else { " (could not roll every step back; check the project)" },
7780 );
7781 delta = 0;
7782 }
7783 let end_after = parse::session_end(s);
7784 let mut lanes_touched: Vec<Lane> = Vec::new();
7785 let mut lines = Vec::with_capacity(done.len());
7786 let mut applied = Vec::with_capacity(done.len());
7787 // Holes left by more than one op of the batch are one summary line per lane, under the first op
7788 // that left one there, in place of a line per op. A single op keeps its own hole lines.
7789 if holes.iter().filter(|h| !h.is_empty()).count() > 1 {
7790 for e in effects.iter_mut() {
7791 e.retain(|x| !x.starts_with("hole left on "));
7792 }
7793 for (k, line) in batch_hole_lines(&holes, fps) {
7794 effects[k].push(line);
7795 }
7796 }
7797 // How often each effect line occurs across the batch: a 200-op batch that leaves the same hole
7798 // 199 times prints it once, with the count.
7799 let mut effect_counts: Vec<(&str, usize)> = Vec::new();
7800 for e in effects.iter().flatten() {
7801 match effect_counts.iter_mut().find(|(x, _)| x == e) {
7802 Some(c) => c.1 += 1,
7803 None => effect_counts.push((e.as_str(), 1)),
7804 }
7805 }
7806 let mut printed_effects: Vec<&str> = Vec::new();
7807 for (k, (name, d)) in done.iter().enumerate() {
7808 let show = k < OP_LINES_CAP;
7809 let addrs: Vec<String> = d.touched.iter().map(|&(l, st)| parse::addr(l, st)).collect();
7810 let mut line = format!("{}. {}", k + 1, d.text);
7811 // The clips an op touched read as "→ …" after its text. When the text ends with a list of
7812 // clips left in place, that arrow would read as more of them, so the touched clips get their
7813 // own line there.
7814 let left = d.text.contains("; left in place");
7815 if !addrs.is_empty() && !left {
7816 line.push_str(" → ");
7817 line.push_str(&addrs.join(", "));
7818 }
7819 if show {
7820 lines.push(line);
7821 if !addrs.is_empty() && left {
7822 lines.push(format!(" now at: {}", addrs.join(", ")));
7823 }
7824 }
7825 let moved: Vec<String> = shifts[k].iter().map(|(a, b)| format!("{a}→{b}")).collect();
7826 if !moved.is_empty() && show && name == "lane_move" {
7827 // A lane move renames each lane's clips: one line per rename, so a swap reads as two lines.
7828 for pair in moved.iter().take(SHIFT_CAP) {
7829 lines.push(format!(" shifted: {pair}"));
7830 }
7831 if moved.len() > SHIFT_CAP {
7832 lines.push(format!(" shifted: +{} more", moved.len() - SHIFT_CAP));
7833 }
7834 } else if !moved.is_empty() && show {
7835 let more = if moved.len() > SHIFT_CAP { format!(", +{} more", moved.len() - SHIFT_CAP) } else { String::new() };
7836 let shown: Vec<&str> = moved.iter().take(SHIFT_CAP).map(String::as_str).collect();
7837 lines.push(format!(" shifted: {}{more}", shown.join(", ")));
7838 }
7839 // An effect printed under the first op that makes it; a repeat is only counted.
7840 let mut fresh: Vec<String> = Vec::new();
7841 for e in &effects[k] {
7842 if printed_effects.contains(&e.as_str()) {
7843 continue;
7844 }
7845 let n = effect_counts.iter().find(|(x, _)| *x == e.as_str()).map_or(1, |c| c.1);
7846 // The count is how many of the batch's ops make this effect, not a multiplier of it.
7847 fresh.push(if n > 1 { format!("{e} (in {n} ops)") } else { e.clone() });
7848 if show {
7849 printed_effects.push(e.as_str());
7850 }
7851 }
7852 if !fresh.is_empty() && show {
7853 lines.push(format!(" effects: {}", fresh.join("; ")));
7854 }
7855 applied.push(json!({ "op": name, "text": d.text, "touched": addrs, "shifted": moved, "effects": effects[k] }));
7856 for l in d.lanes.iter().copied().chain(d.touched.iter().map(|&(l, _)| l)) {
7857 if !lanes_touched.contains(&l) {
7858 lanes_touched.push(l);
7859 }
7860 }
7861 }
7862 if done.len() > OP_LINES_CAP {
7863 lines.push(format!("… and {} more ops", done.len() - OP_LINES_CAP));
7864 }
7865 // The digest is the state after the batch, so it is read before any rollback.
7866 let body = digest(s, &lanes_touched, fps);
7867 let mut notes: Vec<String> = tail_notes(s, fps).into_iter().filter(|n| !notes_before.contains(n)).collect();
7868 notes.extend(gap_notes);
7869 // Something other than the timeline changed (a caption track or a library row was added).
7870 let outside = s.sources().len() != sources_before || done.iter().any(|(_, d)| d.text.starts_with("imported"));
7871
7872 // A dry run rolls back only now, after the digest read the state it reports. Then the redo
7873 // history goes back as it was, and a batch that changed nothing keeps it; only a kept batch lets go.
7874 let rolled = !dry || undo_n(s, delta);
7875 if dry || delta == 0 {
7876 put_back_redo(&mut mark, s, &mut srv.redo_ledger);
7877 } else {
7878 keep_redo(&mut mark, s);
7879 }
7880 let header = if dry {
7881 if was_clean {
7882 srv.saved_pushes = Some(s.history_pushes());
7883 srv.saved_sources = Some(s.sources().len());
7884 }
7885 let note = if rolled { "" } else { " (could not roll every step back; check the project)" };
7886 format!("dry run — would apply {} op(s); nothing changed{note}", done.len())
7887 } else if delta > 0 {
7888 let before = srv.ledger.len();
7889 let named: Vec<Vec<String>> = done.iter().map(|(_, d)| d.touched.iter().map(|&(l, st)| parse::addr(l, st)).collect()).collect();
7890 srv.ledger.push(Entry::new(delta, label.clone().unwrap_or_else(|| summarize(ops, &named))));
7891 srv.history_lost_on_open = false;
7892 // The step number is the batch's place in the history that remains: at the cap the oldest
7893 // step is dropped to make room, so the number stays at the cap and says so.
7894 srv.trim_ledger();
7895 let dropped = srv.ledger.len() <= before;
7896 let oldest = if dropped { " (oldest step dropped)" } else { "" };
7897 format!("applied {} op(s) as undo step {}{oldest}", done.len(), srv.ledger.len())
7898 } else if outside {
7899 format!("applied {} op(s); the timeline is unchanged", done.len())
7900 } else {
7901 let nothing_to_cut = done.iter().map(|(_, d)| d.text.clone()).find(|t| t.contains("nothing to cut") || t.contains("nothing to copy") || t.contains("already crossfade"));
7902 let why = noop_why
7903 .or(nothing_to_cut)
7904 .unwrap_or_else(|| format!("{} op(s) ran and left the timeline as it was", done.len()));
7905 format!("no change: {why}")
7906 };
7907 // A dry run at the cap evicted the oldest steps; a kept batch may have too.
7908 srv.trim_ledger();
7909 let header = match &label {
7910 Some(l) => format!("[{l}] {header}"),
7911 None => header,
7912 };
7913 let mut text = header;
7914 for l in &lines {
7915 text.push('\n');
7916 text.push_str(l);
7917 }
7918 if !body.is_empty() {
7919 text.push('\n');
7920 text.push_str(&body);
7921 }
7922 for note in &notes {
7923 text.push_str(&format!("\nnote: {note}"));
7924 }
7925 if end_after != end_before {
7926 text.push_str(&format!(
7927 "\ntimeline {:.3}s → {:.3}s",
7928 parse::secs(end_before, fps),
7929 parse::secs(end_after, fps)
7930 ));
7931 }
7932 Reply::ok(text).with(json!({ "applied": applied, "undo_steps": srv.ledger.len() }))
7933}
7934
7935/// `T@<start>` (a title's frame, like a clip's address) names the title that starts there, so
7936/// the op can name it as `Tn`. Other title forms pass through for the title op to check.
7937fn resolve_title(s: &PlaybackSession, op: &mut Value, fps: f64) -> Result<(), String> {
7938 let Some(raw) = op.get("title").and_then(Value::as_str).map(|t| t.trim().to_string()) else {
7939 return Ok(());
7940 };
7941 let Some(rest) = raw.strip_prefix("T@").or_else(|| raw.strip_prefix("t@")) else {
7942 return Ok(());
7943 };
7944 // Bare digits name a start frame, as `T@1200` and `T@1200f` do in the reply; anything else
7945 // (a timecode, seconds with a unit) goes through the usual time parser.
7946 let digits = rest.trim().trim_end_matches(['f', 'F']);
7947 let start = match digits.parse::<u32>() {
7948 Ok(f) => f,
7949 Err(_) => parse::frame(&Value::String(rest.trim().to_string()), fps, parse::session_end(s))
7950 .map_err(|e| format!("title {raw}: {e}"))?,
7951 };
7952 match s.titles().iter().position(|t| t.start == start) {
7953 Some(i) => {
7954 op["title"] = json!(format!("T{}", i + 1));
7955 Ok(())
7956 }
7957 None => {
7958 let starts: Vec<String> = s.titles().iter().map(|t| format!("T@{}", t.start)).collect();
7959 Err(format!("title {raw} is not on this timeline; the titles are {}", starts.join(", ")))
7960 }
7961 }
7962}
7963
7964/// The title number (0-based) a title op's reply names first, as `T2` gives 1.
7965fn title_index_in(text: &str) -> Option<usize> {
7966 let tok = text.split(|c: char| !c.is_ascii_alphanumeric()).find(|t| t.len() > 1 && t.starts_with('T') && t[1..].chars().all(|c| c.is_ascii_digit()))?;
7967 tok[1..].parse::<usize>().ok()?.checked_sub(1)
7968}
7969
7970// ---- chapters ---------------------------------------------------------------
7971
7972/// The chapter ops. A chapter is named `C@<frame>` (the frame it starts on, bare digits are frames
7973/// as `T@` is) or `C#n` (its place in the frame order, 1 first). Each reply names the chapters after
7974/// the op, so the next op can use the new addresses.
7975fn op_chapter(s: &mut PlaybackSession, name: &str, op: &Value, fps: f64, end: u32) -> Result<Done, String> {
7976 match name {
7977 "chapter_add" => {
7978 let at = op.get("at").ok_or("chapter_add needs `at`: the frame or time the chapter starts on")?;
7979 let frame = parse::frame(at, fps, end).map_err(|e| format!("chapter_add: {e}"))?;
7980 let title = chapter_text(op)?.ok_or("chapter_add needs `title`: the chapter's name")?;
7981 s.add_chapter(frame, &title).map_err(|e| format!("chapter_add: {e}"))?;
7982 let text = format!(
7983 "chapter_add \"{title}\" at {frame}f ({:.3}s) → C@{frame}; chapters: {}",
7984 parse::secs(frame, fps),
7985 chapter_names(s, fps)
7986 );
7987 Ok(plain(text, Vec::new()))
7988 }
7989 "chapter_set" => {
7990 let mut idx = chapter_index(s, op.get("chapter"), fps)?;
7991 let old = s.chapters()[idx].clone();
7992 let title = chapter_text(op)?;
7993 let at = match op.get("at") {
7994 None | Some(Value::Null) => None,
7995 Some(v) => Some(parse::frame(v, fps, end).map_err(|e| format!("chapter_set: {e}"))?),
7996 };
7997 if title.is_none() && at.is_none() {
7998 return Err("chapter_set changes nothing: give `title` and/or `at`".into());
7999 }
8000 if let Some(t) = &title
8001 && *t != old.title
8002 && !s.set_chapter_title(idx, t)
8003 {
8004 return Err(format!("chapter_set: the name {t:?} is refused: a name is 1 to 100 characters"));
8005 }
8006 if let Some(frame) = at
8007 && frame != old.frame
8008 {
8009 idx = s.move_chapter(idx, frame).map_err(|e| format!("chapter_set: {e}"))?;
8010 }
8011 let now = s.chapters()[idx].clone();
8012 let text = format!(
8013 "chapter_set C@{} → C@{} \"{}\"; chapters: {}",
8014 old.frame,
8015 now.frame,
8016 now.title,
8017 chapter_names(s, fps)
8018 );
8019 Ok(plain(text, Vec::new()))
8020 }
8021 _ => {
8022 let idx = chapter_index(s, op.get("chapter"), fps)?;
8023 let gone = s.chapters()[idx].clone();
8024 s.remove_chapter(idx);
8025 let text = format!("chapter_remove C@{} \"{}\"; chapters: {}", gone.frame, gone.title, chapter_names(s, fps));
8026 Ok(plain(text, Vec::new()))
8027 }
8028 }
8029}
8030
8031/// The name a chapter op gives: `title` as text, trimmed. `None` when the op does not name one.
8032fn chapter_text(op: &Value) -> Result<Option<String>, String> {
8033 match op.get("title") {
8034 None | Some(Value::Null) => Ok(None),
8035 Some(Value::String(t)) => Ok(Some(t.trim().to_string())),
8036 Some(_) => Err("`title` must be the chapter's name, as text".into()),
8037 }
8038}
8039
8040/// The index of the chapter `raw` names: `C@<frame>` (bare digits are frames, `f` is allowed, and a
8041/// time works too) or `C#n` (the n-th chapter, 1 first).
8042fn chapter_index(s: &PlaybackSession, raw: Option<&Value>, fps: f64) -> Result<usize, String> {
8043 let Some(raw) = raw.and_then(Value::as_str).map(|t| t.trim().to_string()) else {
8044 return Err("name the chapter as C@<frame> (C@150) or C#n (C#2, its place in the list)".into());
8045 };
8046 let count = s.chapters().len();
8047 if let Some(rest) = raw.strip_prefix("C#").or_else(|| raw.strip_prefix("c#")) {
8048 let n: usize = rest.trim().parse().map_err(|_| format!("chapter {raw}: C#n wants a number, 1 for the first chapter"))?;
8049 return match n.checked_sub(1) {
8050 Some(i) if i < count => Ok(i),
8051 _ => Err(format!("chapter {raw} is not on this timeline; the chapters are {}", chapter_names(s, fps))),
8052 };
8053 }
8054 if let Some(rest) = raw.strip_prefix("C@").or_else(|| raw.strip_prefix("c@")) {
8055 let digits = rest.trim().trim_end_matches(['f', 'F']);
8056 let frame = match digits.parse::<u32>() {
8057 Ok(f) => f,
8058 Err(_) => parse::frame(&Value::String(rest.trim().to_string()), fps, parse::session_end(s))
8059 .map_err(|e| format!("chapter {raw}: {e}"))?,
8060 };
8061 return s
8062 .chapters()
8063 .iter()
8064 .position(|c| c.frame == frame)
8065 .ok_or_else(|| format!("chapter {raw} is not on this timeline; the chapters are {}", chapter_names(s, fps)));
8066 }
8067 Err(format!("chapter {raw}: name a chapter as C@<frame> (C@150) or C#n (C#2)"))
8068}
8069
8070/// The chapters as addresses and names, `C@0 Intro, C@4500 Setup`, or `none`.
8071fn chapter_names(s: &PlaybackSession, fps: f64) -> String {
8072 let _ = fps;
8073 if s.chapters().is_empty() {
8074 return "none".to_string();
8075 }
8076 s.chapters().iter().map(|c| format!("C@{} {}", c.frame, c.title)).collect::<Vec<_>>().join(", ")
8077}
8078
8079// ---- markers ----------------------------------------------------------------
8080
8081/// The marker ops. A marker is named `M@<frame>` (the first one on that frame) or `M#n` (its place
8082/// in the frame order, 1 first). Each reply names the markers after the op, so the next op can use
8083/// the new addresses.
8084fn op_marker(s: &mut PlaybackSession, name: &str, op: &Value, fps: f64, end: u32) -> Result<Done, String> {
8085 use engine::project::{Marker, MarkerColor};
8086 let text_arg = |key: &str| -> Result<Option<String>, String> {
8087 match op.get(key) {
8088 None | Some(Value::Null) => Ok(None),
8089 Some(Value::String(t)) => Ok(Some(t.trim().to_string())),
8090 Some(_) => Err(format!("`{key}` must be text")),
8091 }
8092 };
8093 let color_arg = || -> Result<Option<MarkerColor>, String> {
8094 match text_arg("color")? {
8095 None => Ok(None),
8096 Some(c) => MarkerColor::from_name(&c)
8097 .map(Some)
8098 .ok_or_else(|| format!("color {c:?} is not red, orange, yellow, green, blue or purple")),
8099 }
8100 };
8101 let length_arg = || -> Result<Option<u32>, String> {
8102 match op.get("length") {
8103 None | Some(Value::Null) => Ok(None),
8104 Some(v) => parse::frame(v, fps, u32::MAX).map(Some).map_err(|e| format!("length: {e}")),
8105 }
8106 };
8107 match name {
8108 "marker_add" => {
8109 let at = op.get("at").ok_or("marker_add needs `at`: the frame or time the marker sits on")?;
8110 let frame = parse::frame(at, fps, end).map_err(|e| format!("marker_add: {e}"))?;
8111 let name = text_arg("name")?.ok_or("marker_add needs `name`")?;
8112 let marker = Marker {
8113 frame,
8114 length: length_arg()?.unwrap_or(0),
8115 note: text_arg("note")?.unwrap_or_default(),
8116 color: color_arg()?.unwrap_or_default(),
8117 name,
8118 };
8119 s.add_marker(marker.clone()).map_err(|e| format!("marker_add: {e}"))?;
8120 let text = format!(
8121 "marker_add \"{}\" at {frame}f ({:.3}s) → M@{frame}; markers: {}",
8122 marker.name,
8123 parse::secs(frame, fps),
8124 marker_names(s)
8125 );
8126 Ok(plain(text, Vec::new()))
8127 }
8128 "marker_set" => {
8129 let idx = marker_index(s, op.get("marker"), fps)?;
8130 let old = s.markers()[idx].clone();
8131 let mut new = old.clone();
8132 if let Some(n) = text_arg("name")? {
8133 new.name = n;
8134 }
8135 if let Some(n) = text_arg("note")? {
8136 new.note = n;
8137 }
8138 if let Some(c) = color_arg()? {
8139 new.color = c;
8140 }
8141 if let Some(v) = op.get("at").filter(|v| !v.is_null()) {
8142 new.frame = parse::frame(v, fps, end).map_err(|e| format!("marker_set: {e}"))?;
8143 }
8144 if let Some(l) = length_arg()? {
8145 new.length = l;
8146 }
8147 let now_idx = s.set_marker(idx, new.clone()).map_err(|e| format!("marker_set: {e}"))?;
8148 let _ = now_idx;
8149 let text = format!("marker_set M@{} → M@{} \"{}\"; markers: {}", old.frame, new.frame, new.name, marker_names(s));
8150 Ok(plain(text, Vec::new()))
8151 }
8152 _ => {
8153 let idx = marker_index(s, op.get("marker"), fps)?;
8154 let gone = s.markers()[idx].clone();
8155 s.remove_marker(idx);
8156 let text = format!("marker_remove M@{} \"{}\"; markers: {}", gone.frame, gone.name, marker_names(s));
8157 Ok(plain(text, Vec::new()))
8158 }
8159 }
8160}
8161
8162/// The index of the marker `raw` names: `M@<frame>` (the first marker on it; bare digits are frames,
8163/// `f` is allowed, and a time works too) or `M#n` (the n-th marker, 1 first).
8164fn marker_index(s: &PlaybackSession, raw: Option<&Value>, fps: f64) -> Result<usize, String> {
8165 let Some(raw) = raw.and_then(Value::as_str).map(|t| t.trim().to_string()) else {
8166 return Err("name the marker as M@<frame> (M@150) or M#n (M#2, its place in the list)".into());
8167 };
8168 let count = s.markers().len();
8169 if let Some(rest) = raw.strip_prefix("M#").or_else(|| raw.strip_prefix("m#")) {
8170 let n: usize = rest.trim().parse().map_err(|_| format!("marker {raw}: M#n wants a number, 1 for the first marker"))?;
8171 return match n.checked_sub(1) {
8172 Some(i) if i < count => Ok(i),
8173 _ => Err(format!("marker {raw} is not on this timeline; the markers are {}", marker_names(s))),
8174 };
8175 }
8176 if let Some(rest) = raw.strip_prefix("M@").or_else(|| raw.strip_prefix("m@")) {
8177 let digits = rest.trim().trim_end_matches(['f', 'F']);
8178 let frame = match digits.parse::<u32>() {
8179 Ok(f) => f,
8180 Err(_) => parse::frame(&Value::String(rest.trim().to_string()), fps, parse::session_end(s))
8181 .map_err(|e| format!("marker {raw}: {e}"))?,
8182 };
8183 return s
8184 .markers()
8185 .iter()
8186 .position(|m| m.frame == frame)
8187 .ok_or_else(|| format!("marker {raw} is not on this timeline; the markers are {}", marker_names(s)));
8188 }
8189 Err(format!("marker {raw}: name a marker as M@<frame> (M@150) or M#n (M#2)"))
8190}
8191
8192/// The markers as addresses and names, `M@0 Intro, M@4500 Fix`, or `none`.
8193fn marker_names(s: &PlaybackSession) -> String {
8194 if s.markers().is_empty() {
8195 return "none".to_string();
8196 }
8197 s.markers().iter().map(|m| format!("M@{} {}", m.frame, m.name)).collect::<Vec<_>>().join(", ")
8198}
8199
8200/// `steps` for undo and redo: a whole number of at least 1, and 1 when absent.
8201/// Anything else (zero, negative, fractional, text) is refused, the same for both.
8202fn steps_arg(args: &Value) -> Result<usize, Reply> {
8203 match args.get("steps") {
8204 None | Some(Value::Null) => Ok(1),
8205 Some(v) => match v.as_u64() {
8206 Some(n) if n >= 1 => Ok(n as usize),
8207 _ => Err(Reply::err(format!("`steps` must be a whole number of at least 1, not {v}"))),
8208 },
8209 }
8210}
8211
8212pub(super) fn run_undo(srv: &mut Server, args: &Value) -> Reply {
8213 let want = tri!(steps_arg(args));
8214 if srv.session.is_none() {
8215 return Reply::err(NO_PROJECT_UNDO);
8216 }
8217 srv.trim_ledger();
8218 if srv.ledger.is_empty() {
8219 const CHECKPOINTS: &str = "checkpoints survive: checkpoint {name} before risky edits, restore {name} to go back";
8220 // Undone batches wait on the redo ledger: that is the history there is, not one that was lost.
8221 if !srv.redo_ledger.is_empty() {
8222 let capped = if srv.history_capped { "; older history was dropped by the 100-step cap" } else { "" };
8223 return Reply::err(format!(
8224 "nothing left to undo ({} steps undone; redo brings them back){capped}",
8225 srv.redo_ledger.len()
8226 ));
8227 }
8228 return Reply::err(if srv.history_capped {
8229 format!("nothing to undo: older history was dropped by the 100-step cap; {CHECKPOINTS}")
8230 } else {
8231 let lost = if srv.history_lost_on_open { " (history does not survive project_open)" } else { "" };
8232 format!("nothing to undo yet{lost}; {CHECKPOINTS}")
8233 });
8234 }
8235 let Some(s) = srv.session.as_mut() else {
8236 return Reply::err(NO_PROJECT);
8237 };
8238 let mut names: Vec<String> = Vec::new();
8239 while names.len() < want {
8240 let Some(entry) = srv.ledger.last().cloned() else { break };
8241 if !undo_n(s, entry.steps) {
8242 return Reply::err(format!(
8243 "undo stopped after {} batch(es): the engine would not undo the next batch in full; check the project before going on",
8244 names.len()
8245 ));
8246 }
8247 srv.ledger.pop();
8248 names.push(entry.label.clone());
8249 srv.redo_ledger.push(entry);
8250 }
8251 let fps = parse::session_fps(s);
8252 let lanes = s.lanes();
8253 let body = digest(s, &lanes, fps);
8254 let next = srv.ledger.last().map(|e| format!(" · next undo: {}", e.label)).unwrap_or_default();
8255 let dropped = if names.len() < want && srv.ledger.is_empty() && srv.history_capped {
8256 " · older history was dropped by the 100-step cap"
8257 } else {
8258 ""
8259 };
8260 let short = if names.len() < want {
8261 format!(" · asked for {want}, only {} can be undone", batches(names.len()))
8262 } else {
8263 String::new()
8264 };
8265 let text = format!(
8266 "undid: {} · undo {} · redo {}{short}{next}{dropped}\n{body}",
8267 names.join(" · "),
8268 srv.ledger.len(),
8269 srv.redo_ledger.len()
8270 );
8271 Reply::ok(text).with(json!({ "undone": names, "undo_steps": srv.ledger.len(), "redo_steps": srv.redo_ledger.len() }))
8272}
8273
8274fn run_redo(srv: &mut Server, args: &Value) -> Reply {
8275 let want = tri!(steps_arg(args));
8276 if srv.session.is_none() {
8277 return Reply::err(NO_PROJECT_REDO);
8278 }
8279 if srv.redo_ledger.is_empty() {
8280 return Reply::err("nothing to redo (an edit clears redo history)");
8281 }
8282 let Some(s) = srv.session.as_mut() else {
8283 return Reply::err(NO_PROJECT);
8284 };
8285 let mut names: Vec<String> = Vec::new();
8286 while names.len() < want {
8287 let Some(entry) = srv.redo_ledger.last().cloned() else { break };
8288 if !redo_n(s, entry.steps) {
8289 return Reply::err(format!(
8290 "redo stopped after {} batch(es): the engine would not redo the next batch in full; check the project before going on",
8291 names.len()
8292 ));
8293 }
8294 srv.redo_ledger.pop();
8295 names.push(entry.label.clone());
8296 srv.ledger.push(entry);
8297 srv.history_lost_on_open = false;
8298 }
8299 let fps = parse::session_fps(s);
8300 let lanes = s.lanes();
8301 let body = digest(s, &lanes, fps);
8302 let next = srv.redo_ledger.last().map(|e| format!(" · next redo: {}", e.label)).unwrap_or_default();
8303 let short = if names.len() < want {
8304 format!(" · asked for {want}, only {} can be redone", batches(names.len()))
8305 } else {
8306 String::new()
8307 };
8308 let text = format!(
8309 "redid: {} · undo {} · redo {}{short}{next}\n{body}",
8310 names.join(" · "),
8311 srv.ledger.len(),
8312 srv.redo_ledger.len()
8313 );
8314 Reply::ok(text).with(json!({ "redone": names, "undo_steps": srv.ledger.len(), "redo_steps": srv.redo_ledger.len() }))
8315}
8316
8317// ---- checkpoints ----------------------------------------------------------
8318
8319#[cfg(test)]
8320thread_local! {
8321 /// A test's own checkpoint folder, set by `own_checkpoints`, so no two tests share one.
8322 static TEST_CHECKPOINTS: std::cell::RefCell<Option<PathBuf>> = const { std::cell::RefCell::new(None) };
8323}
8324
8325/// Where the checkpoints of the open project are kept: `<project dir>/checkpoints/<stem>/`,
8326/// beside the project, so they outlive the server process (as freeze stills do). With no
8327/// project path yet, the temp-dir fallback of `temp_checkpoint_dir`.
8328fn checkpoint_dir(srv: &Server) -> PathBuf {
8329 match srv.path.as_deref() {
8330 Some(project) => engine::versions::dir_beside(project),
8331 None => temp_checkpoint_dir(),
8332 }
8333}
8334
8335/// The fallback with no project path: a directory per process under the temp dir, so
8336/// two servers never read each other's copies. Lost on reboot or a temp cleanup.
8337fn temp_checkpoint_dir() -> PathBuf {
8338 #[cfg(test)]
8339 {
8340 if let Some(dir) = TEST_CHECKPOINTS.with(|d| d.borrow().clone()) {
8341 return dir;
8342 }
8343 }
8344 std::env::temp_dir().join(format!("edith_mcp-{}", std::process::id())).join("checkpoints")
8345}
8346
8347fn checkpoint_file(srv: &Server, name: &str) -> PathBuf {
8348 engine::versions::file(&checkpoint_dir(srv), name)
8349}
8350
8351/// A checkpoint name: 1 to 40 letters, digits, `-` or `_`, so it is a safe file name
8352/// ([`engine::versions::valid_name`], which the window's Save version uses too).
8353fn checkpoint_name(args: &Value) -> Result<String, Reply> {
8354 let name = arg_str(args, "name")?;
8355 if !engine::versions::valid_name(name) {
8356 return Err(Reply::err(format!(
8357 "checkpoint name `{name}` is not usable: 1 to 40 letters, digits, - or _"
8358 )));
8359 }
8360 Ok(name.to_string())
8361}
8362
8363fn run_checkpoint(srv: &mut Server, args: &Value) -> Reply {
8364 let name = tri!(checkpoint_name(args));
8365 let dir = checkpoint_dir(srv);
8366 let Some(s) = srv.session.as_ref() else {
8367 return Reply::err(NO_PROJECT);
8368 };
8369 // An existing checkpoint of this name is overwritten; the reply says so and how old it was.
8370 let saved = match engine::versions::save(s, &dir, &name) {
8371 Ok(saved) => saved,
8372 Err(e) => return Reply::err(format!("checkpoint {name} failed: {e}")),
8373 };
8374 let fps = parse::session_fps(s);
8375 let head = match saved.replaced {
8376 Some(t) => format!("replaced checkpoint {name} (was from {})", age_text(t)),
8377 None => format!("checkpoint {name} saved"),
8378 };
8379 // Without a project path the copy is in the temp dir; say so, since it will not survive a restart.
8380 let kept = if srv.path.is_some() {
8381 format!("kept in {}", dir.display())
8382 } else {
8383 "kept in the temp directory only (no project path yet: save the project to keep checkpoints beside it)".to_string()
8384 };
8385 Reply::ok(format!(
8386 "{head}: {} placement(s), {}, {kept}. restore {name} returns to this.",
8387 saved.clips,
8388 parse::tc(parse::session_end(s), fps)
8389 ))
8390}
8391
8392/// How long ago a file was written, as the checkpoint reply words it: `40 s ago`, `3 min ago`.
8393fn age_text(t: std::time::SystemTime) -> String {
8394 engine::versions::age_text(t)
8395}
8396
8397/// Saves the open state as a checkpoint named `before-restore-<name>` (a suffix when that name is
8398/// taken, and cut to the 40 characters a checkpoint name may hold), so a restore never discards
8399/// unsaved edits. Returns the name it saved under; None when no project is open.
8400fn save_before_restore(srv: &Server, name: &str) -> Result<Option<String>, String> {
8401 let Some(s) = srv.session.as_ref() else {
8402 return Ok(None);
8403 };
8404 engine::versions::save_before_restore(s, &checkpoint_dir(srv), name).map(Some).map_err(|e| e.to_string())
8405}
8406
8407fn run_restore(srv: &mut Server, args: &Value) -> Reply {
8408 let name = tri!(checkpoint_name(args));
8409 let path = checkpoint_file(srv, &name);
8410 if !path.is_file() {
8411 return Reply::err(format!(
8412 "no checkpoint named {name} in {}; checkpoints lists the ones there",
8413 path.parent().unwrap_or(&path).display()
8414 ));
8415 }
8416 // The open state is kept first, so the restore can be undone by restoring it back.
8417 let saved = match save_before_restore(srv, &name) {
8418 Ok(saved) => saved,
8419 Err(e) => return Reply::err(format!("restore {name} refused: could not save the open state first ({e}); nothing was restored")),
8420 };
8421 let session = match PlaybackSession::open_project(&path) {
8422 Ok(s) => s,
8423 Err(e) => return Reply::err(format!("restore {name} failed: {e}")),
8424 };
8425 // What the checkpoint needed fixing for, said as project_open says it (the same wording).
8426 let fixes: String = session
8427 .load_warnings()
8428 .iter()
8429 .map(|w| format!("warning: the file needed fixing to open: {w} — save to keep the fix\n"))
8430 .collect();
8431 // The file the project is saved to is not touched. Its mtime and path stay,
8432 // and `saved_depth` is cleared so the restored state reads as unsaved.
8433 srv.session = Some(session);
8434 srv.saved_depth = None;
8435 srv.saved_pushes = None;
8436 srv.history_lost_on_open = false;
8437 srv.ledger.clear();
8438 srv.redo_ledger.clear();
8439 srv.history_capped = false;
8440 let s = srv.session.as_ref().expect("session was just installed");
8441 let fps = parse::session_fps(s);
8442 let lanes = s.lanes();
8443 let body = digest(s, &lanes, fps);
8444 let kept = match saved {
8445 Some(auto) => format!(" (the state before the restore is kept as checkpoint {auto}: restore {auto} goes back to it)"),
8446 None => String::new(),
8447 };
8448 Reply::ok(format!(
8449 "restored checkpoint {name}; undo and redo history cleared, project is unsaved{kept}\n{fixes}{body}"
8450 ))
8451}
8452
8453/// Lists the checkpoint files on disk in this project's checkpoint folder, by name.
8454fn run_checkpoints(srv: &mut Server, _args: &Value) -> Reply {
8455 let dir = checkpoint_dir(srv);
8456 let mut names: Vec<String> = engine::versions::list(&dir).into_iter().map(|v| v.name).collect();
8457 names.sort();
8458 if names.is_empty() {
8459 return Reply::ok(format!("no checkpoints in {}; `checkpoint {{name}}` saves one", dir.display()));
8460 }
8461 Reply::ok(format!("{} checkpoint(s) in {}:\n{}", names.len(), dir.display(), names.join("\n")))
8462 .with(json!({ "checkpoints": names, "dir": dir.display().to_string() }))
8463}
8464
8465#[cfg(test)]
8466mod tests {
8467 use super::*;
8468 use crate::testutil::TestDir;
8469 use std::path::Path;
8470
8471 fn open() -> Server {
8472 engine::ao::set_silent_output();
8473 let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
8474 let sess = PlaybackSession::open(p).expect("open test asset");
8475 Server { session: Some(sess), ..Server::default() }
8476 }
8477
8478 type Snap = Vec<(Lane, Vec<(u32, u32, u32, usize, Option<u32>)>)>;
8479
8480 fn snapshot(srv: &Server) -> Snap {
8481 let s = srv.session.as_ref().expect("session");
8482 s.lanes()
8483 .into_iter()
8484 .filter(|l| l.kind != LaneKind::Subtitle)
8485 .map(|l| {
8486 let clips = s
8487 .lane_clips(l)
8488 .iter()
8489 .map(|c| (c.start, c.in_frame, c.out_frame, c.source, c.link))
8490 .collect();
8491 (l, clips)
8492 })
8493 .collect()
8494 }
8495
8496 fn first_len(srv: &Server) -> u32 {
8497 srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].frames()
8498 }
8499
8500 fn ed(srv: &mut Server, ops: Value) -> Reply {
8501 run_edit(srv, &json!({ "ops": ops }))
8502 }
8503
8504 /// `beats` on a click track at 120 BPM (a 20 ms burst every half second, ten seconds): the tempo
8505 /// is read back, the beats are yellow "Beat" markers at `every`, and a second run replaces the
8506 /// first instead of doubling it.
8507 #[test]
8508 fn beats_marks_a_click_track_and_a_second_run_replaces_it() {
8509 let dir = crate::testutil::TestDir::new("beats-op");
8510 let wav = dir.join("click120.wav");
8511 let status = std::process::Command::new("ffmpeg")
8512 .args(["-v", "error", "-y", "-f", "lavfi", "-i"])
8513 .arg("aevalsrc='0.8*sin(2*PI*1000*t)*lt(mod(t,0.5),0.02)':d=10:s=44100:c=mono")
8514 .args(["-c:a", "pcm_s16le"])
8515 .arg(&wav)
8516 .status()
8517 .expect("ffmpeg runs");
8518 assert!(status.success(), "ffmpeg made the click track");
8519 let mut srv = open();
8520 srv.session.as_mut().unwrap().import(&wav).expect("import click track");
8521 let r = ed(&mut srv, json!([{ "op": "lane_add", "kind": "audio" }]));
8522 assert!(!r.is_error, "{}", r.text);
8523 let r = ed(&mut srv, json!([{ "op": "place", "source": 1, "lane": "A2", "at": "0s" }]));
8524 assert!(!r.is_error, "{}", r.text);
8525
8526 let r = ed(&mut srv, json!([{ "op": "beats", "clip": "A2@0" }]));
8527 assert!(!r.is_error, "{}", r.text);
8528 assert!(r.text.contains("BPM") && r.text.contains("M@"), "{}", r.text);
8529 let s = srv.session.as_ref().unwrap();
8530 let beat_count = |s: &PlaybackSession| {
8531 s.markers().iter().filter(|m| m.note == engine::beats::BEAT_NOTE).count()
8532 };
8533 let first = beat_count(s);
8534 assert!((18..=21).contains(&first), "{first} beat markers: {}", r.text);
8535 assert!(s.markers().iter().filter(|m| m.note == "Beat").all(|m| m.color == engine::beats::BEAT_COLOR));
8536 // The reply reads "beats A2@0: 120.0 BPM; ...".
8537 let bpm: f64 = r.text.split(": ").nth(1).and_then(|t| t.split(" BPM").next()).and_then(|t| t.trim().parse().ok()).unwrap_or(0.);
8538 assert!((bpm - 120.).abs() <= 2., "bpm in the reply: {}", r.text);
8539
8540 // Every 2nd beat, replacing the first run's markers: about half as many, none left over.
8541 let r = ed(&mut srv, json!([{ "op": "beats", "clip": "A2@0", "every": 2 }]));
8542 assert!(!r.is_error && r.text.contains("replacing"), "{}", r.text);
8543 let s = srv.session.as_ref().unwrap();
8544 let second = beat_count(s);
8545 assert!((9..=11).contains(&second), "{second} after every 2: {}", r.text);
8546
8547 let bad = ed(&mut srv, json!([{ "op": "beats", "clip": "A2@0", "every": 0 }]));
8548 assert!(bad.is_error && bad.text.contains("every"), "{}", bad.text);
8549 }
8550
8551 #[test]
8552 fn chapter_ops_add_set_remove_and_name_the_new_addresses() {
8553 let mut srv = open();
8554 let r = ed(&mut srv, json!([{ "op": "chapter_add", "at": "0s", "title": "Intro" }]));
8555 assert!(!r.is_error && r.text.contains("C@0"), "{}", r.text);
8556 let r = ed(&mut srv, json!([{ "op": "chapter_add", "at": "150f", "title": "Setup" }]));
8557 assert!(!r.is_error && r.text.contains("C@150") && r.text.contains("C@0 Intro, C@150 Setup"), "{}", r.text);
8558 let dup = ed(&mut srv, json!([{ "op": "chapter_add", "at": "150f", "title": "Again" }]));
8559 assert!(dup.is_error && dup.text.contains("already starts at frame 150"), "{}", dup.text);
8560 let r = ed(&mut srv, json!([{ "op": "chapter_set", "chapter": "C#2", "title": "Begin", "at": "160f" }]));
8561 assert!(!r.is_error && r.text.contains("C@150 → C@160") && r.text.contains("\"Begin\""), "{}", r.text);
8562 let clash = ed(&mut srv, json!([{ "op": "chapter_set", "chapter": "C@0", "at": "160f" }]));
8563 assert!(clash.is_error, "{}", clash.text);
8564 let missing = ed(&mut srv, json!([{ "op": "chapter_set", "chapter": "C@999", "title": "X" }]));
8565 assert!(missing.is_error && missing.text.contains("not on this timeline"), "{}", missing.text);
8566 let nothing = ed(&mut srv, json!([{ "op": "chapter_set", "chapter": "C#1" }]));
8567 assert!(nothing.is_error && nothing.text.contains("changes nothing"), "{}", nothing.text);
8568 let r = ed(&mut srv, json!([{ "op": "chapter_remove", "chapter": "C@0" }]));
8569 assert!(!r.is_error && r.text.contains("chapters: C@160 Begin"), "{}", r.text);
8570 assert_eq!(srv.session.as_ref().unwrap().chapters().len(), 1);
8571 }
8572
8573 #[test]
8574 fn marker_ops_add_set_remove_and_follow_a_ripple() {
8575 let mut srv = open();
8576 let r = ed(&mut srv, json!([{ "op": "marker_add", "at": "0s", "name": "Intro", "color": "red", "note": "hi" }]));
8577 assert!(!r.is_error && r.text.contains("M@0"), "{}", r.text);
8578 let r = ed(&mut srv, json!([{ "op": "marker_add", "at": "90f", "name": "Range", "length": "30f", "color": "purple" }]));
8579 assert!(!r.is_error, "{}", r.text);
8580 let bad = ed(&mut srv, json!([{ "op": "marker_add", "at": "5f", "name": "X", "color": "pink" }]));
8581 assert!(bad.is_error && bad.text.contains("not red, orange"), "{}", bad.text);
8582 let no = ed(&mut srv, json!([{ "op": "marker_add", "at": "5f" }]));
8583 assert!(no.is_error, "{}", no.text);
8584 let r = ed(&mut srv, json!([{ "op": "marker_set", "marker": "M#2", "name": "Fix", "color": "green", "at": "100f", "length": 0 }]));
8585 assert!(!r.is_error && r.text.contains("M@100 Fix"), "{}", r.text);
8586 let m = srv.session.as_ref().unwrap().markers().to_vec();
8587 assert_eq!((m[1].frame, m[1].length, m[1].color.name()), (100, 0, "green"));
8588 assert_eq!(m[0].note, "hi");
8589 let r = ed(&mut srv, json!([{ "op": "marker_set", "marker": "M@0", "note": "" }]));
8590 assert!(!r.is_error && srv.session.as_ref().unwrap().markers()[0].note.is_empty(), "{}", r.text);
8591 let nothing = ed(&mut srv, json!([{ "op": "marker_set", "marker": "M@0" }]));
8592 assert!(nothing.is_error, "{}", nothing.text);
8593 let missing = ed(&mut srv, json!([{ "op": "marker_remove", "marker": "M@999" }]));
8594 assert!(missing.is_error && missing.text.contains("markers are"), "{}", missing.text);
8595 // Inserting 30 frames at 50 pushes the marker at 100 on; the one at 0 stays.
8596 let r = ed(&mut srv, json!([{ "op": "insert_time", "at": "50f", "duration": "30f" }]));
8597 assert!(!r.is_error, "{}", r.text);
8598 let frames: Vec<u32> = srv.session.as_ref().unwrap().markers().iter().map(|m| m.frame).collect();
8599 assert_eq!(frames, vec![0, 130]);
8600 let r = ed(&mut srv, json!([{ "op": "marker_remove", "marker": "M@130" }]));
8601 assert!(!r.is_error && r.text.contains("markers: M@0 Intro"), "{}", r.text);
8602 }
8603
8604 #[test]
8605 fn chapters_move_with_a_cut_and_a_chapter_inside_lands_at_its_start() {
8606 let mut srv = open();
8607 ed(&mut srv, json!([{ "op": "chapter_add", "at": "0s", "title": "Intro" }]));
8608 ed(&mut srv, json!([{ "op": "chapter_add", "at": "45f", "title": "Inside" }]));
8609 ed(&mut srv, json!([{ "op": "chapter_add", "at": "90f", "title": "Late" }]));
8610 // A 30-frame span from frame 30: the chapter at 45 lands on its start, the one at 90 moves back 30.
8611 let r = ed(&mut srv, json!([{ "op": "remove_time", "at": "30f", "duration": "30f" }]));
8612 assert!(!r.is_error, "{}", r.text);
8613 let frames: Vec<(u32, String)> =
8614 srv.session.as_ref().unwrap().chapters().iter().map(|c| (c.frame, c.title.clone())).collect();
8615 assert_eq!(frames, [(0, "Intro".into()), (30, "Inside".into()), (60, "Late".into())], "{:?}", frames);
8616 // Inserting 30 frames at 30 pushes the later ones on, and the chapter at 30 moves with it.
8617 let r = ed(&mut srv, json!([{ "op": "insert_time", "at": "30f", "duration": "30f" }]));
8618 assert!(!r.is_error, "{}", r.text);
8619 let frames: Vec<u32> = srv.session.as_ref().unwrap().chapters().iter().map(|c| c.frame).collect();
8620 assert_eq!(frames, [0, 60, 90]);
8621 }
8622
8623 #[test]
8624 fn split_move_fade_is_one_undo_step() {
8625 let mut srv = open();
8626 let len = first_len(&srv);
8627 let half = len / 2;
8628 let far = len + 60;
8629 let r = ed(
8630 &mut srv,
8631 json!([
8632 { "op": "split", "at": format!("{half}f") },
8633 { "op": "move", "clip": format!("V1@{half}"), "at": format!("{far}f") },
8634 { "op": "fade", "clip": format!("V1@{far}"), "out": "5f" }
8635 ]),
8636 );
8637 assert!(!r.is_error, "{}", r.text);
8638 assert!(r.text.contains("applied 3 op(s) as undo step 1"), "{}", r.text);
8639 assert_eq!(srv.ledger.len(), 1);
8640 assert!(srv.redo_ledger.is_empty());
8641 }
8642
8643 #[test]
8644 fn op_shape_refusals_name_the_fault() {
8645 let mut srv = open();
8646 let before = snapshot(&srv);
8647 let not_object = ed(&mut srv, json!([{ "op": "split", "at": "1s" }, null]));
8648 assert!(not_object.is_error);
8649 assert!(not_object.text.starts_with("op 2 is not an op object: give {\"op\":\"<name>\""), "{}", not_object.text);
8650 assert!(!not_object.text.contains("(?)"), "{}", not_object.text);
8651 assert!(not_object.text.contains("batch rolled back, nothing changed"), "{}", not_object.text);
8652 for bad in [json!([{}]), json!([{ "op": null }]), json!([{ "op": 7 }])] {
8653 let r = ed(&mut srv, bad);
8654 assert!(r.is_error);
8655 assert_eq!(
8656 r.text.split(';').next().unwrap(),
8657 "op 1 has no \"op\" name (each op is flat: {\"op\":\"place\",\"source\":\"src:0\",\"at\":\"0s\"})",
8658 "{}",
8659 r.text
8660 );
8661 }
8662 assert_eq!(snapshot(&srv), before, "a refused shape changes nothing");
8663 }
8664
8665 #[test]
8666 fn undo_step_number_stops_at_the_cap() {
8667 let mut srv = open();
8668 let mut last = String::new();
8669 for i in 0..101 {
8670 let r = ed(&mut srv, json!([{ "op": "lane_flags", "lane": "V1", "hidden": i % 2 == 0 }]));
8671 assert!(!r.is_error, "{}", r.text);
8672 last = r.text;
8673 }
8674 assert_eq!(srv.ledger.len(), 100, "the history keeps 100 steps");
8675 assert!(last.contains("as undo step 100 (oldest step dropped)"), "{last}");
8676 }
8677
8678 #[test]
8679 fn long_batch_prints_capped_op_lines_and_counts_repeated_effects() {
8680 let mut srv = open();
8681 let ops: Vec<Value> = (0..45).map(|i| json!({ "op": "lane_flags", "lane": "V1", "hidden": i % 2 == 0 })).collect();
8682 let r = ed(&mut srv, Value::Array(ops));
8683 assert!(!r.is_error, "{}", r.text);
8684 assert!(r.text.contains("\n40. "), "{}", r.text);
8685 assert!(!r.text.contains("\n41. "), "{}", r.text);
8686 assert!(r.text.contains("… and 5 more ops"), "{}", r.text);
8687
8688 // Four identical place-and-lift pairs leave the same hole four times: the batch names it once,
8689 // as a summary line for the lane, with the one gap start it has.
8690 let mut srv = open();
8691 let pair = [
8692 json!({ "op": "place", "source": 0, "lane": "V1", "at": "60s", "audio": false }),
8693 json!({ "op": "lift", "clip": "V1@60s" }),
8694 ];
8695 let ops: Vec<Value> = (0..4).flat_map(|_| pair.clone()).collect();
8696 let r = ed(&mut srv, Value::Array(ops));
8697 assert!(!r.is_error, "{}", r.text);
8698 assert_eq!(r.text.matches("holes left on V1").count(), 1, "{}", r.text);
8699 assert!(r.text.contains("holes left on V1 at 5.000s (close_gaps cannot close them: the V1 clip at V1@0 is one take with the A1 clip at A1@0"), "{}", r.text);
8700 }
8701
8702 #[test]
8703 fn failing_second_op_rolls_the_batch_back() {
8704 let mut srv = open();
8705 let before = snapshot(&srv);
8706 let depth = srv.session.as_ref().unwrap().undo_depth();
8707 let half = first_len(&srv) / 2;
8708 let r = ed(
8709 &mut srv,
8710 json!([
8711 { "op": "split", "at": format!("{half}f") },
8712 { "op": "trim", "clip": "V1@999999f", "edge": "out", "to": "1f" }
8713 ]),
8714 );
8715 assert!(r.is_error);
8716 assert!(r.text.contains("op 2 (trim) failed"), "{}", r.text);
8717 assert!(r.text.contains("batch rolled back, nothing changed"), "{}", r.text);
8718 assert_eq!(snapshot(&srv), before);
8719 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth);
8720 assert!(srv.ledger.is_empty());
8721 }
8722
8723 /// Fills the engine's history to the 100-step cap with single-op batches,
8724 /// each one split at its own frame, so each pushes exactly one snapshot.
8725 fn at_the_cap() -> Server {
8726 let mut srv = open();
8727 assert!(first_len(&srv) > 120, "the test asset is long enough for 115 splits");
8728 for f in 1..=105 {
8729 let r = ed(&mut srv, json!([{ "op": "split", "at": format!("{f}f") }]));
8730 assert!(!r.is_error, "split {f}: {}", r.text);
8731 }
8732 let s = srv.session.as_ref().unwrap();
8733 assert_eq!(s.undo_depth(), 100, "the cap holds the depth at 100");
8734 assert_eq!(srv.ledger.len(), 100);
8735 srv
8736 }
8737
8738 #[test]
8739 fn two_op_batch_at_the_cap_is_one_step_and_undo_restores_it() {
8740 let mut srv = at_the_cap();
8741 let before = snapshot(&srv);
8742 let r = ed(&mut srv, json!([{ "op": "split", "at": "110f" }, { "op": "split", "at": "115f" }]));
8743 assert!(!r.is_error, "{}", r.text);
8744 assert!(r.text.contains("as undo step 99 (oldest step dropped)"), "the batch counted both steps: {}", r.text);
8745 assert_eq!(srv.ledger.last().unwrap().steps, 2, "exact at the cap, not a zero delta");
8746 assert_eq!(srv.ledger.len(), 99, "the two oldest single-op entries were evicted with their steps");
8747 assert_ne!(snapshot(&srv), before);
8748
8749 let u = run_undo(&mut srv, &json!({}));
8750 assert!(!u.is_error, "{}", u.text);
8751 assert_eq!(snapshot(&srv), before, "undo restores exactly the state before the batch");
8752 assert_eq!(srv.ledger.len(), 98);
8753 let s = srv.session.as_ref().unwrap();
8754 assert_eq!(s.undo_depth(), 98, "the engine and the ledger agree");
8755 assert_eq!(srv.ledger.iter().map(|e| e.steps).sum::<usize>(), 98);
8756 assert_eq!(s.redo_depth(), 2, "the batch's two steps are on the redo stack");
8757 assert_eq!(srv.redo_ledger.len(), 1);
8758 }
8759
8760 #[test]
8761 fn dry_run_at_the_cap_leaves_the_timeline_unchanged() {
8762 let mut srv = at_the_cap();
8763 let before = snapshot(&srv);
8764 let r = run_edit(
8765 &mut srv,
8766 &json!({ "ops": [{ "op": "split", "at": "110f" }, { "op": "split", "at": "115f" }], "dry_run": true }),
8767 );
8768 assert!(!r.is_error, "{}", r.text);
8769 assert!(r.text.contains("dry run"), "{}", r.text);
8770 assert_eq!(snapshot(&srv), before, "rolled back exactly");
8771 let s = srv.session.as_ref().unwrap();
8772 assert_eq!(s.redo_depth(), 0, "the rolled-back states are not a branch to redo");
8773 assert!(srv.redo_ledger.is_empty());
8774 // The dry run's pushes evict nothing: the cap is held while it runs, so the
8775 // history and the ledger read exactly as they did before it.
8776 assert_eq!(s.undo_depth(), 100);
8777 assert_eq!(srv.ledger.len(), 100);
8778 assert_eq!(srv.ledger.iter().map(|e| e.steps).sum::<usize>(), s.undo_depth());
8779 assert!(srv.history_capped);
8780 }
8781
8782 #[test]
8783 fn failing_batch_at_the_cap_rolls_back_and_keeps_the_ledger() {
8784 let mut srv = at_the_cap();
8785 let before = snapshot(&srv);
8786 let r = ed(&mut srv, json!([{ "op": "split", "at": "110f" }, { "op": "no_such_op" }]));
8787 assert!(r.is_error, "{}", r.text);
8788 assert_eq!(snapshot(&srv), before);
8789 // The refused batch's push evicts nothing while it runs, so the rollback
8790 // leaves the history and the ledger as they were.
8791 let s = srv.session.as_ref().unwrap();
8792 assert_eq!(srv.ledger.len(), 100);
8793 assert_eq!(srv.ledger.iter().map(|e| e.steps).sum::<usize>(), s.undo_depth());
8794 }
8795
8796 #[test]
8797 fn undo_past_the_cap_says_the_history_was_dropped() {
8798 let mut srv = at_the_cap();
8799 let r = run_undo(&mut srv, &json!({ "steps": 200 }));
8800 assert!(!r.is_error, "{}", r.text);
8801 assert!(r.text.contains("older history was dropped by the 100-step cap"), "{}", r.text);
8802 assert!(srv.ledger.is_empty());
8803 let again = run_undo(&mut srv, &json!({}));
8804 assert!(again.is_error);
8805 assert!(again.text.contains("older history was dropped by the 100-step cap"), "{}", again.text);
8806 }
8807
8808 /// Splits, undoes the split so the redo history holds it, and returns the server with the
8809 /// redo entry's serial, which a batch that leaves no trace must keep.
8810 fn undone_split() -> (Server, u64) {
8811 let mut srv = open();
8812 let half = first_len(&srv) / 2;
8813 assert!(!ed(&mut srv, json!([{ "op": "split", "at": format!("{half}f") }])).is_error);
8814 assert!(!run_undo(&mut srv, &json!({})).is_error);
8815 assert_eq!(srv.redo_ledger.len(), 1);
8816 let serial = srv.redo_ledger[0].serial;
8817 (srv, serial)
8818 }
8819
8820 #[test]
8821 fn dry_run_keeps_the_redo_history_and_the_dirty_state() {
8822 let (mut srv, serial) = undone_split();
8823 let undone = snapshot(&srv);
8824 {
8825 let s = srv.session.as_ref().unwrap();
8826 srv.saved_depth = Some(s.undo_depth());
8827 srv.saved_pushes = Some(s.history_pushes());
8828 srv.saved_sources = Some(s.sources().len());
8829 }
8830 srv.saved_top = srv.ledger_top();
8831 assert!(!crate::tools::project::dirty(&srv), "the test starts clean");
8832 let half = first_len(&srv) / 2;
8833 let r = run_edit(
8834 &mut srv,
8835 &json!({ "ops": [{ "op": "split", "at": format!("{}f", half / 2) }], "dry_run": true }),
8836 );
8837 assert!(!r.is_error, "{}", r.text);
8838 assert_eq!(snapshot(&srv), undone, "rolled back exactly");
8839 assert_eq!(srv.session.as_ref().unwrap().redo_depth(), 1, "the redo step survives the dry run");
8840 assert_eq!(srv.redo_ledger.len(), 1);
8841 assert_eq!(srv.redo_ledger[0].serial, serial, "the entry is the same one");
8842 assert!(!crate::tools::project::dirty(&srv), "a dry run leaves the project clean");
8843 let rd = run_redo(&mut srv, &json!({}));
8844 assert!(!rd.is_error, "{}", rd.text);
8845 assert!(srv.redo_ledger.is_empty());
8846 }
8847
8848 #[test]
8849 fn failed_batch_keeps_the_redo_history() {
8850 let (mut srv, serial) = undone_split();
8851 let undone = snapshot(&srv);
8852 let half = first_len(&srv) / 2;
8853 let r = ed(&mut srv, json!([{ "op": "split", "at": format!("{}f", half / 2) }, { "op": "no_such_op" }]));
8854 assert!(r.is_error, "{}", r.text);
8855 assert_eq!(snapshot(&srv), undone);
8856 assert_eq!(srv.session.as_ref().unwrap().redo_depth(), 1);
8857 assert_eq!(srv.redo_ledger.len(), 1);
8858 assert_eq!(srv.redo_ledger[0].serial, serial);
8859 assert!(!run_redo(&mut srv, &json!({})).is_error);
8860 }
8861
8862 #[test]
8863 fn batch_that_changes_nothing_keeps_the_redo_history() {
8864 let (mut srv, serial) = undone_split();
8865 let undone = snapshot(&srv);
8866 let r = ed(&mut srv, json!([{ "op": "remove_time", "at": "1000000f" }]));
8867 assert!(r.is_error || r.text.contains("left the timeline as it was"), "{}", r.text);
8868 assert_eq!(snapshot(&srv), undone);
8869 assert_eq!(srv.session.as_ref().unwrap().redo_depth(), 1);
8870 assert_eq!(srv.redo_ledger[0].serial, serial);
8871 }
8872
8873 #[test]
8874 fn dry_run_keeps_the_redo_history_at_the_cap() {
8875 let mut srv = at_the_cap();
8876 assert!(!ed(&mut srv, json!([{ "op": "split", "at": "120f" }])).is_error);
8877 assert!(!run_undo(&mut srv, &json!({})).is_error);
8878 let undone = snapshot(&srv);
8879 let r = run_edit(
8880 &mut srv,
8881 &json!({ "ops": [{ "op": "split", "at": "110f" }, { "op": "split", "at": "115f" }], "dry_run": true }),
8882 );
8883 assert!(!r.is_error, "{}", r.text);
8884 assert_eq!(snapshot(&srv), undone);
8885 let s = srv.session.as_ref().unwrap();
8886 assert_eq!(s.redo_depth(), 1);
8887 assert_eq!(s.undo_depth(), 99, "the undo left one step short of the cap, and the dry run keeps that depth");
8888 assert_eq!(srv.ledger.len(), 99);
8889 }
8890
8891 #[test]
8892 fn dry_run_changes_nothing_and_keeps_no_entry() {
8893 let mut srv = open();
8894 let before = snapshot(&srv);
8895 let half = first_len(&srv) / 2;
8896 let r = run_edit(
8897 &mut srv,
8898 &json!({ "ops": [{ "op": "split", "at": format!("{half}f") }], "dry_run": true }),
8899 );
8900 assert!(!r.is_error, "{}", r.text);
8901 assert!(r.text.contains("dry run"), "{}", r.text);
8902 assert_eq!(snapshot(&srv), before);
8903 assert!(srv.ledger.is_empty());
8904 }
8905
8906 #[test]
8907 fn undo_then_redo_restores() {
8908 let mut srv = open();
8909 let before = snapshot(&srv);
8910 let half = first_len(&srv) / 2;
8911 let r = ed(&mut srv, json!([{ "op": "split", "at": format!("{half}f") }]));
8912 assert!(!r.is_error, "{}", r.text);
8913 let after = snapshot(&srv);
8914 assert_ne!(after, before);
8915
8916 let u = run_undo(&mut srv, &json!({}));
8917 assert!(!u.is_error, "{}", u.text);
8918 assert_eq!(snapshot(&srv), before);
8919 assert!(srv.ledger.is_empty());
8920 assert_eq!(srv.redo_ledger.len(), 1);
8921
8922 let rd = run_redo(&mut srv, &json!({}));
8923 assert!(!rd.is_error, "{}", rd.text);
8924 assert_eq!(snapshot(&srv), after);
8925 assert_eq!(srv.ledger.len(), 1);
8926 assert!(srv.redo_ledger.is_empty());
8927
8928 assert!(run_redo(&mut srv, &json!({})).is_error);
8929 }
8930
8931 #[test]
8932 fn keep_three_ranges_lays_them_back_to_back() {
8933 let mut srv = open();
8934 let (fps, end, n_before) = {
8935 let s = srv.session.as_ref().unwrap();
8936 (parse::session_fps(s), parse::session_end(s), s.lane_clips(Lane::V1).len())
8937 };
8938 let r = ed(
8939 &mut srv,
8940 json!([{ "op": "keep", "source": 0, "ranges": [["0s", "1s"], ["2s", "3s"], ["4s", "5s"]] }]),
8941 );
8942 assert!(!r.is_error, "{}", r.text);
8943 let s = srv.session.as_ref().unwrap();
8944 let v1 = s.lane_clips(Lane::V1);
8945 assert_eq!(v1.len(), n_before + 3, "{}", r.text);
8946 let tail = &v1[n_before..];
8947 assert_eq!(tail[0].start, end);
8948 for w in tail.windows(2) {
8949 assert_eq!(w[0].end(), w[1].start);
8950 }
8951 assert_eq!(tail[0].frames(), fps.round() as u32);
8952 assert_eq!(srv.ledger.len(), 1);
8953 }
8954
8955 #[test]
8956 fn assemble_lays_two_items_end_to_end() {
8957 let mut srv = open();
8958 let (end, n_before) = {
8959 let s = srv.session.as_ref().unwrap();
8960 (parse::session_end(s), s.lane_clips(Lane::V1).len())
8961 };
8962 let r = ed(
8963 &mut srv,
8964 json!([{ "op": "assemble", "items": [
8965 { "source": 0, "in": "0s", "out": "1s" },
8966 { "source": 0, "in": "2s", "out": "3s" }
8967 ] }]),
8968 );
8969 assert!(!r.is_error, "{}", r.text);
8970 let s = srv.session.as_ref().unwrap();
8971 let v1 = s.lane_clips(Lane::V1);
8972 assert_eq!(v1.len(), n_before + 2, "{}", r.text);
8973 let tail = &v1[n_before..];
8974 assert_eq!(tail[0].start, end);
8975 assert_eq!(tail[0].end(), tail[1].start);
8976 assert_eq!(srv.ledger.len(), 1);
8977 }
8978
8979 #[test]
8980 fn assemble_refuses_gap_without_lane_and_bad_source() {
8981 let mut srv = open();
8982 let depth = srv.session.as_ref().unwrap().undo_depth();
8983 let r = ed(
8984 &mut srv,
8985 json!([{ "op": "assemble", "gap": "1s", "items": [{ "source": 0, "in": "0s", "out": "1s" }] }]),
8986 );
8987 assert!(r.is_error);
8988 assert!(r.text.contains("gap needs `lane`"), "{}", r.text);
8989 let r = ed(&mut srv, json!([{ "op": "assemble", "items": [{ "source": 7 }] }]));
8990 assert!(r.is_error);
8991 assert!(r.text.contains("there is no src:7"), "{}", r.text);
8992 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth);
8993 }
8994
8995 /// Gives this test its own checkpoint folder inside `td`.
8996 fn own_checkpoints(td: &TestDir) {
8997 TEST_CHECKPOINTS.with(|d| *d.borrow_mut() = Some(td.join("checkpoints")));
8998 }
8999
9000 #[test]
9001 fn checkpoint_edit_restore_returns_to_the_checkpoint() {
9002 let td = TestDir::new("checkpoint-edit-restore");
9003 own_checkpoints(&td);
9004 let mut srv = open();
9005 let half = first_len(&srv) / 2;
9006 let c = run_checkpoint(&mut srv, &json!({ "name": "ck_edit_restore" }));
9007 assert!(!c.is_error, "{}", c.text);
9008 let before = snapshot(&srv);
9009
9010 let r = ed(&mut srv, json!([{ "op": "split", "at": format!("{half}f") }]));
9011 assert!(!r.is_error, "{}", r.text);
9012 assert_ne!(snapshot(&srv), before);
9013
9014 let rs = run_restore(&mut srv, &json!({ "name": "ck_edit_restore" }));
9015 assert!(!rs.is_error, "{}", rs.text);
9016 assert_eq!(snapshot(&srv), before);
9017 assert!(srv.ledger.is_empty());
9018 assert!(srv.redo_ledger.is_empty());
9019 assert!(crate::tools::project::dirty(&srv), "a restored checkpoint reads as unsaved");
9020
9021 let list = run_checkpoints(&mut srv, &json!({}));
9022 assert!(list.text.contains("ck_edit_restore"), "{}", list.text);
9023 }
9024
9025 #[test]
9026 fn restore_refuses_an_unknown_name_and_bad_names() {
9027 let mut srv = open();
9028 assert!(run_restore(&mut srv, &json!({ "name": "never_made" })).is_error);
9029 assert!(run_checkpoint(&mut srv, &json!({ "name": "has space" })).is_error);
9030 assert!(run_checkpoint(&mut srv, &json!({ "name": "../escape" })).is_error);
9031 }
9032
9033 /// A session with no clips yet and the 30 fps test asset imported as src:0.
9034 fn empty_with_av() -> Server {
9035 engine::ao::set_silent_output();
9036 let mut sess = PlaybackSession::empty(1280, 720, 30.0).expect("empty session");
9037 sess.import(&asset("test_av.mp4")).expect("import test asset");
9038 Server { session: Some(sess), ..Server::default() }
9039 }
9040
9041 #[test]
9042 fn digest_says_no_clips_for_an_empty_lane() {
9043 let srv = empty_with_av();
9044 let s = srv.session.as_ref().unwrap();
9045 let fps = parse::session_fps(s);
9046 let body = digest(s, &[Lane::V1], fps);
9047 assert_eq!(body, "V1: no clips", "{body}");
9048 }
9049
9050 #[test]
9051 fn place_without_a_lane_honours_at() {
9052 let mut srv = empty_with_av();
9053 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "20s" }]));
9054 assert!(!r.is_error, "{}", r.text);
9055 let s = srv.session.as_ref().unwrap();
9056 let at = (20.0 * parse::session_fps(s)).round() as u32;
9057 assert_eq!(s.lane_clips(Lane::V1)[0].start, at, "the pair lands at 20s, not at 0");
9058 assert!(r.text.contains(&format!("at timeline {at}f")), "{}", r.text);
9059 assert!(s.lane_clips(Lane::A1).iter().any(|c| c.start == at), "the sound half lands there too");
9060 }
9061
9062 #[test]
9063 fn place_on_a_video_lane_pairs_the_sound_on_a1_as_one_take() {
9064 let mut srv = empty_with_av();
9065 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "1s" }]));
9066 assert!(!r.is_error, "{}", r.text);
9067 let s = srv.session.as_ref().unwrap();
9068 let at = (1.0 * parse::session_fps(s)).round() as u32;
9069 let v = s.lane_clips(Lane::V1).iter().find(|c| c.start == at).expect("picture on V1");
9070 let a = s.lane_clips(Lane::A1).iter().find(|c| c.start == at).expect("sound on A1");
9071 assert!(v.link.is_some() && v.link == a.link, "the halves share one link");
9072 assert_eq!(v.frames(), a.frames());
9073 assert!(r.text.contains(&format!("at timeline {at}f")), "{}", r.text);
9074 }
9075
9076 #[test]
9077 fn place_on_a_video_lane_with_audio_false_is_picture_only() {
9078 let mut srv = empty_with_av();
9079 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "1s", "audio": false }]));
9080 assert!(!r.is_error, "{}", r.text);
9081 let s = srv.session.as_ref().unwrap();
9082 assert_eq!(s.lane_clips(Lane::V1).len(), 1);
9083 assert!(s.lane_clips(Lane::A1).is_empty(), "no sound half");
9084 }
9085
9086 #[test]
9087 fn place_on_a_video_lane_sound_goes_to_audio_lane_when_given() {
9088 let mut srv = empty_with_av();
9089 let r = ed(&mut srv, json!([{ "op": "lane_add", "kind": "audio" }]));
9090 assert!(!r.is_error, "{}", r.text);
9091 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s", "audio_lane": "A2" }]));
9092 assert!(!r.is_error, "{}", r.text);
9093 let s = srv.session.as_ref().unwrap();
9094 let added: Vec<Lane> = s.lanes().into_iter().filter(|l| l.kind == LaneKind::Audio && *l != Lane::A1).collect();
9095 assert_eq!(added.len(), 1, "one new audio lane");
9096 assert_eq!(s.lane_clips(added[0]).len(), 1, "the sound went to A2");
9097 assert!(s.lane_clips(Lane::A1).is_empty());
9098 assert!(s.lane_clips(Lane::V1)[0].link.is_some());
9099 }
9100
9101 #[test]
9102 fn place_on_a_video_lane_refuses_an_occupied_audio_lane_and_changes_nothing() {
9103 let mut srv = empty_with_av();
9104 let first = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "0s" }]));
9105 assert!(!first.is_error, "{}", first.text);
9106 let before = snapshot(&srv);
9107 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s" }]));
9108 assert!(r.is_error, "{}", r.text);
9109 assert!(r.text.contains("would overlap A1@0"), "{}", r.text);
9110 assert!(r.text.contains("audio:false") && r.text.contains("audio_lane"), "{}", r.text);
9111 assert_eq!(snapshot(&srv), before, "a refused placement changes nothing");
9112 }
9113
9114 #[test]
9115 fn keep_on_a_video_lane_pairs_its_sound() {
9116 let mut srv = empty_with_av();
9117 let r = ed(&mut srv, json!([{ "op": "keep", "source": 0, "lane": "V1", "ranges": [["0s", "1s"], ["2s", "3s"]] }]));
9118 assert!(!r.is_error, "{}", r.text);
9119 let s = srv.session.as_ref().unwrap();
9120 assert_eq!(s.lane_clips(Lane::V1).len(), 2);
9121 assert_eq!(s.lane_clips(Lane::A1).len(), 2, "each range's sound is on A1");
9122 }
9123
9124 #[test]
9125 fn audio_options_must_be_sane() {
9126 let mut srv = empty_with_av();
9127 let wrong_kind = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s", "audio_lane": "V2" }]));
9128 assert!(wrong_kind.text.contains("`audio_lane` must be an audio lane"), "{}", wrong_kind.text);
9129 let no_video = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "0s", "audio": false }]));
9130 assert!(no_video.text.contains("give `lane` a video lane"), "{}", no_video.text);
9131 let bad = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s", "audio": "no" }]));
9132 assert!(bad.text.contains("`audio` must be true or false"), "{}", bad.text);
9133 let clash = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s", "audio": false, "audio_lane": "A1" }]));
9134 assert!(clash.text.contains("contradict"), "{}", clash.text);
9135 assert!(srv.session.as_ref().unwrap().lane_clips(Lane::V1).is_empty(), "refusals change nothing");
9136 }
9137
9138 #[test]
9139 fn move_reply_has_one_arrow() {
9140 let mut srv = open();
9141 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@0", "at": "2s" }]));
9142 assert!(!r.is_error, "{}", r.text);
9143 let line = r.text.lines().find(|l| l.starts_with("1. ")).expect("op line");
9144 assert_eq!(line.matches('→').count(), 1, "{line}");
9145 }
9146
9147 #[test]
9148 fn undo_and_redo_refuse_bad_steps_the_same_way() {
9149 let mut srv = open();
9150 let half = first_len(&srv) / 2;
9151 let r = ed(&mut srv, json!([{ "op": "split", "at": format!("{half}f") }]));
9152 assert!(!r.is_error, "{}", r.text);
9153 for bad in [json!(-1), json!(0), json!(1.5), json!("2")] {
9154 let u = run_undo(&mut srv, &json!({ "steps": bad }));
9155 assert!(u.is_error && u.text.contains("whole number of at least 1"), "{}", u.text);
9156 let d = run_redo(&mut srv, &json!({ "steps": bad }));
9157 assert!(d.is_error && d.text.contains("whole number of at least 1"), "{}", d.text);
9158 }
9159 assert_eq!(srv.ledger.len(), 1, "refused steps change nothing");
9160 }
9161
9162 #[test]
9163 fn undo_names_a_short_ledger() {
9164 let mut srv = open();
9165 let half = first_len(&srv) / 2;
9166 let r = ed(&mut srv, json!([{ "op": "split", "at": format!("{half}f") }]));
9167 assert!(!r.is_error, "{}", r.text);
9168 let u = run_undo(&mut srv, &json!({ "steps": 5 }));
9169 assert!(!u.is_error, "{}", u.text);
9170 assert!(u.text.contains("asked for 5, only 1 edit batch can be undone"), "{}", u.text);
9171 assert!(srv.ledger.is_empty());
9172 }
9173
9174 #[test]
9175 fn speed_with_a_text_x_says_it_must_be_a_number() {
9176 let mut srv = open();
9177 let r = ed(&mut srv, json!([{ "op": "speed", "clip": "V1@0", "x": "fast" }]));
9178 assert!(r.is_error, "{}", r.text);
9179 assert!(r.text.contains("`x` must be a number"), "{}", r.text);
9180 let missing = ed(&mut srv, json!([{ "op": "speed", "clip": "V1@0" }]));
9181 assert!(missing.text.contains("missing `x`"), "{}", missing.text);
9182 }
9183
9184 #[test]
9185 fn remove_time_after_a_speed_change_leaves_no_hole_and_says_so() {
9186 // The 5 s test clip slowed to half speed is 300 frames; a cut at 55f splits it where
9187 // 27 source frames would give a 54-frame piece, one frame short of the cut.
9188 let mut srv = open();
9189 let r = ed(&mut srv, json!([{ "op": "speed", "clip": "V1@0", "x": 0.5, "ripple": true }]));
9190 assert!(!r.is_error, "{}", r.text);
9191 let r = ed(&mut srv, json!([{ "op": "remove_time", "at": "55f", "duration": "30f" }]));
9192 assert!(!r.is_error, "{}", r.text);
9193 assert!(r.text.contains("the cut moved from 55f to 54f"), "{}", r.text);
9194 assert!(!r.text.contains("hole left"), "{}", r.text);
9195 let s = srv.session.as_ref().unwrap();
9196 for lane in [Lane::V1, Lane::A1] {
9197 assert_eq!(s.gap_count(lane), 0, "{lane:?} keeps a hole: {}", r.text);
9198 let clips = s.lane_clips(lane);
9199 assert!(clips.windows(2).all(|w| w[0].end() == w[1].start), "{lane:?} clips do not abut: {}", r.text);
9200 }
9201 }
9202
9203 #[test]
9204 fn a_hole_a_take_cannot_close_is_not_sent_to_close_gaps() {
9205 // A1 alone is trimmed, so its gap has a linked V1 clip with no gap there: close_gaps cannot close it.
9206 let mut srv = open();
9207 let r = ed(&mut srv, json!([{ "op": "append", "source": "src:0", "lane": "V1" }]));
9208 assert!(!r.is_error, "{}", r.text);
9209 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "A1@0", "edge": "out", "to": "2s", "scope": "clip" }]));
9210 assert!(!r.is_error, "{}", r.text);
9211 assert!(r.text.contains("close_gaps cannot close it") && !r.text.contains("closes it"), "{}", r.text);
9212 let r = ed(&mut srv, json!([{ "op": "close_gaps", "lane": "A1" }]));
9213 assert!(r.text.contains("closed 0") && r.text.contains("the gap stays open") && !r.text.contains("ungroup them"), "{}", r.text);
9214 assert!(!r.text.contains("gap there too"), "{}", r.text);
9215 }
9216
9217 #[test]
9218 fn move_insert_names_the_clip_it_splits() {
9219 let mut srv = open();
9220 let r = ed(&mut srv, json!([{ "op": "append", "source": "src:0", "lane": "V1" }]));
9221 assert!(!r.is_error, "{}", r.text);
9222 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@150", "at": "60f", "insert": true }]));
9223 assert!(!r.is_error, "{}", r.text);
9224 assert!(r.text.contains("split V1@0 at 2.0s"), "{}", r.text);
9225 }
9226
9227 #[test]
9228 fn split_edit_moves_one_half_of_the_take_and_unlinks_the_pair() {
9229 let mut srv = open();
9230 let r = ed(&mut srv, json!([{ "op": "append", "source": "src:0", "lane": "V1" }]));
9231 assert!(!r.is_error, "{}", r.text);
9232 let end_v = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].end();
9233 // An L-cut: the sound's out edge comes back to 1 s; the picture keeps its end.
9234 let r = ed(&mut srv, json!([{ "op": "split_edit", "clip": "V1@0", "side": "audio", "edge": "out", "to": "1s" }]));
9235 assert!(!r.is_error, "{}", r.text);
9236 assert!(r.text.contains("split_edit A1@0 audio out") && r.text.contains("the pair is unlinked"), "{}", r.text);
9237 {
9238 let s = srv.session.as_ref().unwrap();
9239 assert_eq!(s.lane_clips(Lane::V1)[0].end(), end_v, "the picture moved: {}", r.text);
9240 let one_sec = s.meta().frame_rate.round() as u32;
9241 assert_eq!(s.lane_clips(Lane::A1)[0].end(), one_sec, "the sound is one second: {}", r.text);
9242 assert!(s.lane_clips(Lane::V1)[0].link.is_none() || s.lane_clips(Lane::V1)[0].link != s.lane_clips(Lane::A1)[0].link);
9243 }
9244 // one undo step takes the whole split back
9245 let u = super::super::edit::run_undo(&mut srv, &json!({ "steps": 1 }));
9246 assert!(!u.is_error, "{}", u.text);
9247 let s = srv.session.as_ref().unwrap();
9248 assert_eq!(s.lane_clips(Lane::A1)[0].end(), end_v, "undo restores the sound");
9249 assert_eq!(s.lane_clips(Lane::V1)[0].link, s.lane_clips(Lane::A1)[0].link, "undo relinks the pair");
9250 }
9251
9252 #[test]
9253 fn split_edit_on_the_sound_moves_the_picture_in_edge() {
9254 let mut srv = open();
9255 let r = ed(&mut srv, json!([{ "op": "append", "source": "src:0", "lane": "V1" }]));
9256 assert!(!r.is_error, "{}", r.text);
9257 // Anchored on A1, side video: the picture's in edge comes to 0.5 s and the sound stays at 0.
9258 let r = ed(&mut srv, json!([{ "op": "split_edit", "clip": "A1@0", "side": "video", "edge": "in", "to": "0.5s" }]));
9259 assert!(!r.is_error, "{}", r.text);
9260 assert!(r.text.contains("split_edit V1@") && r.text.contains("video in"), "{}", r.text);
9261 let s = srv.session.as_ref().unwrap();
9262 assert!(s.lane_clips(Lane::V1)[0].start > 0, "the picture's in edge moved: {}", r.text);
9263 assert_eq!(s.lane_clips(Lane::A1)[0].start, 0, "the sound stays put: {}", r.text);
9264 }
9265
9266 #[test]
9267 fn split_edit_refuses_a_bad_side_edge_or_frame_and_changes_nothing() {
9268 let mut srv = open();
9269 let r = ed(&mut srv, json!([{ "op": "append", "source": "src:0", "lane": "V1" }]));
9270 assert!(!r.is_error, "{}", r.text);
9271 let before = snapshot(&srv);
9272 for (op, want) in [
9273 (json!({ "op": "split_edit", "clip": "V1@0", "edge": "out", "to": "1s" }), "`side` must be"),
9274 (json!({ "op": "split_edit", "clip": "V1@0", "side": "both", "edge": "out", "to": "1s" }), "`side` must be"),
9275 (json!({ "op": "split_edit", "clip": "V1@0", "side": "audio", "to": "1s" }), "`edge` must be"),
9276 (json!({ "op": "split_edit", "clip": "V1@0", "side": "audio", "edge": "in", "to": "end" }), "would pass the out edge"),
9277 (json!({ "op": "split_edit", "clip": "V1@0", "side": "audio", "edge": "out", "to": "0" }), "would pass the in edge"),
9278 ] {
9279 let r = ed(&mut srv, json!([op]));
9280 assert!(r.is_error && r.text.contains(want), "{want}: {}", r.text);
9281 }
9282 assert_eq!(snapshot(&srv), before, "a refused split_edit changes nothing");
9283 }
9284
9285 #[test]
9286 fn insert_time_reports_only_the_hole_it_made() {
9287 // The gap 60f..150f was there before the insert: the insert moves it to 90f..180f and leaves its own.
9288 let mut srv = open();
9289 let r = ed(&mut srv, json!([{ "op": "append", "source": "src:0", "lane": "V1" }]));
9290 assert!(!r.is_error, "{}", r.text);
9291 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "V1@0", "edge": "out", "to": "2s", "scope": "clip" }]));
9292 assert!(!r.is_error, "{}", r.text);
9293 let r = ed(&mut srv, json!([{ "op": "insert_time", "at": "30f", "duration": "30f" }]));
9294 assert!(!r.is_error, "{}", r.text);
9295 assert!(r.text.contains("hole left on V1 at 1.000–2.000s"), "{}", r.text);
9296 assert!(!r.text.contains("3.000–6.000s"), "the old gap moved, it was not made here: {}", r.text);
9297 }
9298
9299 #[test]
9300 fn a_still_placed_on_a_missing_lane_names_the_lane() {
9301 engine::ao::set_silent_output();
9302 let mut sess = PlaybackSession::open(asset("test_av.mp4")).expect("open test asset");
9303 sess.import(&asset("test_still.png")).expect("import still");
9304 let mut srv = Server { session: Some(sess), ..Server::default() };
9305 let r = ed(&mut srv, json!([{ "op": "place", "source": "src:1", "at": "1s", "lane": "V2" }]));
9306 assert!(r.is_error && r.text.contains("lane V2 is not on this timeline"), "{}", r.text);
9307 assert!(!r.text.contains("did not place"), "{}", r.text);
9308 }
9309
9310 #[test]
9311 fn picture_end_note_follows_the_lowest_video_lane_with_clips() {
9312 // V1 is emptied, so the picture underneath is V2 and the logo on V3 runs past its end.
9313 let mut srv = open();
9314 let r = ed(
9315 &mut srv,
9316 json!([
9317 { "op": "lift", "clip": "V1@0" },
9318 { "op": "lane_add", "kind": "video" },
9319 { "op": "place", "source": "src:0", "lane": "V2", "at": "0s", "audio": false },
9320 { "op": "lane_add", "kind": "video" },
9321 { "op": "place", "source": "src:0", "lane": "V3", "at": "0s", "audio": false },
9322 { "op": "append", "source": "src:0", "lane": "V3", "audio": false }
9323 ]),
9324 );
9325 assert!(!r.is_error, "{}", r.text);
9326 assert!(r.text.contains("V3 runs 5.0s past the picture's end at 5.0s"), "{}", r.text);
9327 }
9328
9329 #[test]
9330 fn freeze_inserted_inside_audio_warns_and_names_the_clip() {
9331 let dir = TestDir::new("freeze-warn");
9332 let mut srv = open();
9333 srv.path = Some(dir.join("cut.edith"));
9334 // The test asset's take starts at 0, so 1s is strictly inside its audio.
9335 let r = ed(&mut srv, json!([{ "op": "freeze", "at": "1s", "duration": "1s" }]));
9336 assert!(!r.is_error, "{}", r.text);
9337 assert!(r.text.contains("warning: the insert cut audio clip A1@0"), "{}", r.text);
9338 assert!(r.text.contains("insert:false"), "{}", r.text);
9339 }
9340
9341 #[test]
9342 fn checkpoints_live_beside_the_project_and_survive_a_restart() {
9343 let dir = TestDir::new("checkpoint-beside");
9344 let project = dir.join("cut.edith");
9345 let mut srv = open();
9346 srv.path = Some(project.clone());
9347 let half = first_len(&srv) / 2;
9348 let c = run_checkpoint(&mut srv, &json!({ "name": "before_split" }));
9349 assert!(!c.is_error, "{}", c.text);
9350 assert!(dir.join("checkpoints").join("cut").join("before_split.edith").is_file());
9351 let before = snapshot(&srv);
9352
9353 // A fresh server, as after a restart: only the project path and the files on disk.
9354 let mut fresh = open();
9355 fresh.path = Some(project);
9356 let list = run_checkpoints(&mut fresh, &json!({}));
9357 assert!(list.text.contains("before_split"), "{}", list.text);
9358 let r = ed(&mut fresh, json!([{ "op": "split", "at": format!("{half}f") }]));
9359 assert!(!r.is_error, "{}", r.text);
9360 let rs = run_restore(&mut fresh, &json!({ "name": "before_split" }));
9361 assert!(!rs.is_error, "{}", rs.text);
9362 assert_eq!(snapshot(&fresh), before);
9363 assert!(run_restore(&mut fresh, &json!({ "name": "never_made" })).is_error);
9364 }
9365
9366 #[test]
9367 fn checkpoint_without_a_project_path_says_it_is_temporary() {
9368 let td = TestDir::new("checkpoint-temp");
9369 own_checkpoints(&td);
9370 let mut srv = open();
9371 let c = run_checkpoint(&mut srv, &json!({ "name": "scratch_only" }));
9372 assert!(!c.is_error, "{}", c.text);
9373 assert!(c.text.contains("temp directory only"), "{}", c.text);
9374 }
9375
9376 fn asset(name: &str) -> PathBuf {
9377 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
9378 }
9379
9380 /// A session opened on one asset from the assets folder, the way `open` opens test_av.mp4.
9381 fn open_asset(name: &str) -> Server {
9382 engine::ao::set_silent_output();
9383 let sess = PlaybackSession::open(asset(name)).expect("open test asset");
9384 Server { session: Some(sess), ..Server::default() }
9385 }
9386
9387 /// A 25 fps timeline with the 30 fps test_av.mp4 imported as src:1.
9388 fn open_25_with_30() -> Server {
9389 engine::ao::set_silent_output();
9390 let mut sess = PlaybackSession::open(asset("test_25fps.mp4")).expect("open 25 fps asset");
9391 sess.import(&asset("test_av.mp4")).expect("import 30 fps asset");
9392 Server { session: Some(sess), ..Server::default() }
9393 }
9394
9395 #[test]
9396 fn source_seconds_use_the_source_fps_on_a_25_fps_timeline() {
9397 let mut srv = open_25_with_30();
9398 {
9399 let s = srv.session.as_ref().unwrap();
9400 assert_eq!(parse::session_fps(s), 25.0);
9401 assert!((s.file_fps(&asset("test_av.mp4")) - 30.0).abs() < 1e-3);
9402 }
9403 let r = ed(&mut srv, json!([{ "op": "keep", "source": 1, "ranges": [["0.5s", "2.0s"]] }]));
9404 assert!(!r.is_error, "{}", r.text);
9405 // The length is the duration in timeline frames: 1.5 s at 25 fps is 37.5, rounded up to 38f. The
9406 // in still snaps to native frame 15 (0.5 s), so the source end reads 2.033s, one source frame past 2.0s.
9407 assert!(r.text.contains("src 0.500s–2.033s"), "{}", r.text);
9408 let s = srv.session.as_ref().unwrap();
9409 let c = s.lane_clips(Lane::V1).last().expect("the keep placed a clip");
9410 assert_eq!(c.frames(), 38, "round(1.5 s x 25 fps)");
9411 assert_eq!((f64::from(c.in_frame) * 30.0 / 25.0).floor() as u32, 15, "in is 0.5s of the source");
9412 }
9413
9414 #[test]
9415 fn source_range_errors_name_source_frames_and_seconds() {
9416 let mut srv = open_25_with_30();
9417 let depth = srv.session.as_ref().unwrap().undo_depth();
9418 let r = ed(&mut srv, json!([{ "op": "keep", "source": 1, "ranges": [["0s", "99s"]] }]));
9419 assert!(r.is_error);
9420 assert!(r.text.contains("plays 0.000s to 5.000s"), "{}", r.text);
9421 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth);
9422 }
9423
9424 #[test]
9425 fn exact_note_names_the_frame_a_time_rounded_to() {
9426 assert_eq!(exact_note(&json!("1.53s"), 25.0, 38, ""), " (1.53s → 38f)");
9427 assert_eq!(exact_note(&json!(1.53), 25.0, 38, " src"), " (1.53s → 38f src)");
9428 assert_eq!(exact_note(&json!("1.52s"), 25.0, 38, ""), "", "1.52s is exactly frame 38");
9429 assert_eq!(exact_note(&json!("450f"), 25.0, 450, ""), "", "frames are never rounded");
9430 assert_eq!(exact_note(&json!("00:00:01:12"), 25.0, 37, ""), "", "timecodes are exact");
9431 }
9432
9433 #[test]
9434 fn off_frame_times_are_noted_in_the_op_line() {
9435 let mut srv = open();
9436 let fps = parse::session_fps(srv.session.as_ref().unwrap());
9437 let r = ed(&mut srv, json!([{ "op": "split", "at": 1.53 }]));
9438 assert!(!r.is_error, "{}", r.text);
9439 let want = (1.53 * fps).round() as u32;
9440 assert!(r.text.contains(&format!("(1.53s → {want}f)")), "{}", r.text);
9441 let exact = ed(&mut srv, json!([{ "op": "split", "at": "1.0s" }]));
9442 assert!(!exact.is_error, "{}", exact.text);
9443 assert!(!exact.text.contains("s → "), "an exact time adds no note: {}", exact.text);
9444 }
9445
9446 /// A slowed clip (0.333x) trimmed out past its source's end, with the next clip far off or
9447 /// close by: the reply names the wall that stopped it, from the bound the engine gave.
9448 #[test]
9449 fn trim_names_the_wall_that_stopped_it() {
9450 // Far neighbour: the source's end is the wall, and the reply says so.
9451 let mut srv = open();
9452 let r = ed(&mut srv, json!([
9453 { "op": "speed", "clip": "V1@0", "x": 0.333 },
9454 { "op": "place", "source": 0, "at": "60s", "lane": "V1", "audio": false }
9455 ]));
9456 assert!(!r.is_error, "{}", r.text);
9457 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "V1@0", "edge": "out", "to": "100s", "scope": "clip" }]));
9458 assert!(!r.is_error, "{}", r.text);
9459 assert!(r.text.contains("clamped at the source's end ("), "{}", r.text);
9460 assert!(!r.text.contains("neighbouring") && !r.text.contains("meets"), "{}", r.text);
9461 // The edge is now where the source ends: asking again says it cannot go further.
9462 let again = ed(&mut srv, json!([{ "op": "trim", "clip": "V1@0", "edge": "out", "to": "100s", "scope": "clip" }]));
9463 assert!(!again.is_error, "{}", again.text);
9464 assert!(again.text.contains("already at") && again.text.contains("clamped at the source's end"), "{}", again.text);
9465
9466 // Close neighbour: the clip it meets is named by its address.
9467 // The slowed clip runs to 15 s, so it is shortened first to leave room for the neighbour at 8 s.
9468 let mut srv = open();
9469 let r = ed(&mut srv, json!([
9470 { "op": "speed", "clip": "V1@0", "x": 0.333 },
9471 { "op": "trim", "clip": "V1@0", "edge": "out", "to": "5s", "scope": "clip" },
9472 { "op": "place", "source": 0, "at": "8s", "lane": "V1", "audio": false }
9473 ]));
9474 assert!(!r.is_error, "{}", r.text);
9475 let next = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[1].start;
9476 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "V1@0", "edge": "out", "to": "100s", "scope": "clip" }]));
9477 assert!(!r.is_error, "{}", r.text);
9478 assert!(r.text.contains(&format!("clamped where it meets V1@{next}")), "{}", r.text);
9479 assert!(!r.text.contains("source's end"), "{}", r.text);
9480 }
9481
9482 #[test]
9483 fn trim_follows_the_linked_take_by_default() {
9484 let mut srv = open();
9485 let half = first_len(&srv) / 2;
9486 assert!(!ed(&mut srv, json!([{ "op": "split", "at": format!("{half}f") }])).is_error);
9487 let to = half / 2;
9488 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "V1@0", "edge": "out", "to": format!("{to}f") }]));
9489 assert!(!r.is_error, "{}", r.text);
9490 assert!(r.text.contains("(with A1@0)"), "{}", r.text);
9491 let s = srv.session.as_ref().unwrap();
9492 assert_eq!(s.lane_clips(Lane::V1)[0].end(), to);
9493 assert_eq!(s.lane_clips(Lane::A1)[0].end(), to, "the sound followed the picture");
9494 }
9495
9496 #[test]
9497 fn trim_scope_clip_trims_only_that_clip() {
9498 let mut srv = open();
9499 let half = first_len(&srv) / 2;
9500 assert!(!ed(&mut srv, json!([{ "op": "split", "at": format!("{half}f") }])).is_error);
9501 let to = half / 2;
9502 let r = ed(
9503 &mut srv,
9504 json!([{ "op": "trim", "clip": "V1@0", "edge": "out", "to": format!("{to}f"), "scope": "clip" }]),
9505 );
9506 assert!(!r.is_error, "{}", r.text);
9507 let s = srv.session.as_ref().unwrap();
9508 assert_eq!(s.lane_clips(Lane::V1)[0].end(), to);
9509 assert_eq!(s.lane_clips(Lane::A1)[0].end(), half, "the partner keeps its span");
9510 let bad = ed(&mut srv, json!([{ "op": "trim", "clip": "V1@0", "edge": "out", "to": "1f", "scope": "all" }]));
9511 assert!(bad.is_error && bad.text.contains("scope `all`"), "{}", bad.text);
9512 }
9513
9514 /// `test_av.mp4` is 150 frames at 30 fps: cut at 30f and 90f into V1+A1 clips 0..30, 30..90, 90..150.
9515 fn three_clips() -> Server {
9516 let mut srv = open();
9517 let r = ed(&mut srv, json!([{ "op": "split", "at": "30f" }, { "op": "split", "at": "90f" }]));
9518 assert!(!r.is_error, "{}", r.text);
9519 srv
9520 }
9521
9522 /// `(start, end, in, out)` of every clip on a lane.
9523 fn spans(srv: &Server, lane: Lane) -> Vec<(u32, u32, u32, u32)> {
9524 let s = srv.session.as_ref().unwrap();
9525 s.lane_clips(lane).iter().map(|c| (c.start, c.end(), c.in_frame, c.out_frame)).collect()
9526 }
9527
9528 #[test]
9529 fn roll_moves_the_cut_of_the_take_and_names_the_new_addresses() {
9530 let mut srv = three_clips();
9531 let depth = srv.session.as_ref().unwrap().undo_depth();
9532 let r = ed(&mut srv, json!([{ "op": "roll", "clip": "V1@0", "by": "+10f" }]));
9533 assert!(!r.is_error, "{}", r.text);
9534 assert!(r.text.contains("roll V1@0 cut 30f (1.000s) → 40f (1.333s)"), "{}", r.text);
9535 assert!(r.text.contains("V1@40") && r.text.contains("A1@40"), "the new addresses: {}", r.text);
9536 for lane in [Lane::V1, Lane::A1] {
9537 assert_eq!(spans(&srv, lane), [(0, 40, 0, 40), (40, 90, 40, 90), (90, 150, 90, 150)], "{lane:?}");
9538 }
9539 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth + 1, "one undo step");
9540 // `to` is the absolute cut place, and edge:"in" names the cut before the clip.
9541 let r = ed(&mut srv, json!([{ "op": "roll", "clip": "V1@40", "edge": "in", "to": "1s" }]));
9542 assert!(!r.is_error && r.text.contains("cut 40f (1.333s) → 30f (1.000s)"), "{}", r.text);
9543 assert_eq!(spans(&srv, Lane::V1)[..2], [(0, 30, 0, 30), (30, 90, 30, 90)]);
9544 let run = run_undo(&mut srv, &json!({ "steps": 2 }));
9545 assert!(!run.is_error, "{}", run.text);
9546 for lane in [Lane::V1, Lane::A1] {
9547 assert_eq!(spans(&srv, lane), [(0, 30, 0, 30), (30, 90, 30, 90), (90, 150, 90, 150)], "{lane:?}");
9548 }
9549 }
9550
9551 #[test]
9552 fn roll_says_when_a_limit_clamped_and_refuses_without_a_cut() {
9553 let mut srv = three_clips();
9554 let r = ed(&mut srv, json!([{ "op": "roll", "clip": "V1@0", "to": "end" }]));
9555 assert!(!r.is_error, "{}", r.text);
9556 assert!(r.text.contains("clamped from") && r.text.contains("the cut can travel 1f"), "{}", r.text);
9557 assert_eq!(spans(&srv, Lane::V1)[0].1, 89, "a frame is left for the clip after the cut");
9558 // The last clip has nothing after it; `by` and `to` together are one too many.
9559 let last = ed(&mut srv, json!([{ "op": "roll", "clip": "V1@90", "by": "5f" }]));
9560 assert!(last.is_error && last.text.contains("no clip after V1@90"), "{}", last.text);
9561 let both = ed(&mut srv, json!([{ "op": "roll", "clip": "V1@0", "by": "5f", "to": "9f" }]));
9562 assert!(both.is_error && both.text.contains("`by` or `to`, not both"), "{}", both.text);
9563 let none = ed(&mut srv, json!([{ "op": "roll", "clip": "V1@0" }]));
9564 assert!(none.is_error && none.text.contains("missing `by` or `to`"), "{}", none.text);
9565 // A gap is not a cut.
9566 let mut gap = three_clips();
9567 assert!(!ed(&mut gap, json!([{ "op": "lift", "clip": "V1@30" }])).is_error);
9568 let r = ed(&mut gap, json!([{ "op": "roll", "clip": "V1@0", "by": "5f" }]));
9569 assert!(r.is_error && r.text.contains("a gap, not a cut"), "{}", r.text);
9570 let typo = ed(&mut srv, json!([{ "op": "roll", "clip": "V1@0", "at": "5f" }]));
9571 assert!(typo.is_error && typo.text.contains("unknown key `at`; roll takes clip, by, to, edge"), "{}", typo.text);
9572 }
9573
9574 #[test]
9575 fn roll_at_speed_two_moves_two_source_frames_per_frame() {
9576 let mut srv = three_clips();
9577 // V1@30 and A1@30 play 60 source frames in 30 timeline frames.
9578 let r = ed(&mut srv, json!([{ "op": "speed", "clip": "V1@30", "x": 2.0, "ripple": false }]));
9579 assert!(!r.is_error, "{}", r.text);
9580 assert_eq!(spans(&srv, Lane::V1)[1], (30, 60, 30, 90));
9581 // The gap after it (60..90) is not a cut; roll the cut before it instead.
9582 let r = ed(&mut srv, json!([{ "op": "roll", "clip": "V1@30", "edge": "in", "by": "-10f" }]));
9583 assert!(!r.is_error, "{}", r.text);
9584 assert_eq!(spans(&srv, Lane::V1)[..2], [(0, 20, 0, 20), (20, 60, 10, 90)], "10 timeline frames of speed 2 are 20 source frames");
9585 }
9586
9587 #[test]
9588 fn slip_shifts_the_window_keeps_the_slot_and_is_one_undo() {
9589 let mut srv = three_clips();
9590 let depth = srv.session.as_ref().unwrap().undo_depth();
9591 let r = ed(&mut srv, json!([{ "op": "slip", "clip": "V1@30", "by": "10f" }]));
9592 assert!(!r.is_error, "{}", r.text);
9593 assert!(r.text.contains("source 30f–90f → 40f–100f") && r.text.contains("still 30f"), "{}", r.text);
9594 for lane in [Lane::V1, Lane::A1] {
9595 assert_eq!(spans(&srv, lane)[1], (30, 90, 40, 100), "{lane:?} the take slipped together");
9596 }
9597 // Negative, with a time form: -0.5 s is 15 frames back.
9598 let r = ed(&mut srv, json!([{ "op": "slip", "clip": "V1@30", "by": "-0.5s" }]));
9599 assert!(!r.is_error && r.text.contains("by -15f"), "{}", r.text);
9600 assert_eq!(spans(&srv, Lane::V1)[1], (30, 90, 25, 85));
9601 // Clamped to the file: the clip can only reach back 25 frames.
9602 let r = ed(&mut srv, json!([{ "op": "slip", "clip": "V1@30", "by": "-100f" }]));
9603 assert!(!r.is_error && r.text.contains("clamped from -100 to -25 source frames"), "{}", r.text);
9604 assert_eq!(spans(&srv, Lane::V1)[1], (30, 90, 0, 60));
9605 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth + 3);
9606 let r = ed(&mut srv, json!([{ "op": "slip", "clip": "V1@30", "by": "-5f" }]));
9607 assert!(!r.is_error && r.text.contains("clamped"), "pinned at the start: {}", r.text);
9608 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth + 3, "a pinned slip costs no step");
9609 assert!(!run_undo(&mut srv, &json!({ "steps": 3 })).is_error);
9610 assert_eq!(spans(&srv, Lane::V1)[1], (30, 90, 30, 90));
9611 }
9612
9613 #[test]
9614 fn slip_at_speed_converts_timeline_frames_to_source_frames() {
9615 let mut srv = three_clips();
9616 assert!(!ed(&mut srv, json!([{ "op": "speed", "clip": "V1@30", "x": 2.0, "ripple": false }])).is_error);
9617 let r = ed(&mut srv, json!([{ "op": "slip", "clip": "V1@30", "by": "3f" }]));
9618 assert!(!r.is_error, "{}", r.text);
9619 assert!(r.text.contains("+3f on the timeline is 6 source frames at 2x"), "{}", r.text);
9620 assert_eq!(spans(&srv, Lane::V1)[1], (30, 60, 36, 96), "same slot, 6 source frames later");
9621 // A quarter of a source frame is nothing to slip.
9622 let mut srv = three_clips();
9623 assert!(!ed(&mut srv, json!([{ "op": "speed", "clip": "V1@90", "x": 0.25, "ripple": false }])).is_error);
9624 let r = ed(&mut srv, json!([{ "op": "slip", "clip": "V1@90", "by": "1f" }]));
9625 assert!(!r.is_error && r.text.contains("less than one source frame"), "{}", r.text);
9626 }
9627
9628 #[test]
9629 fn slide_moves_the_clip_between_its_neighbours_keeping_the_length() {
9630 let mut srv = three_clips();
9631 let depth = srv.session.as_ref().unwrap().undo_depth();
9632 let r = ed(&mut srv, json!([{ "op": "slide", "clip": "V1@30", "by": "+0.5s" }]));
9633 assert!(!r.is_error, "{}", r.text);
9634 assert!(r.text.contains("slide V1@30 by +15f: now V1@45") && r.text.contains("V1@0 now ends at 45f"), "{}", r.text);
9635 assert!(r.text.contains("V1@105 now starts at 105f"), "{}", r.text);
9636 for lane in [Lane::V1, Lane::A1] {
9637 assert_eq!(spans(&srv, lane), [(0, 45, 0, 45), (45, 105, 30, 90), (105, 150, 105, 150)], "{lane:?}");
9638 }
9639 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth + 1);
9640 let r = ed(&mut srv, json!([{ "op": "slide", "clip": "V1@45", "by": "-99f" }]));
9641 assert!(!r.is_error && r.text.contains("clamped from -99f to -44f"), "{}", r.text);
9642 assert_eq!(spans(&srv, Lane::V1)[0], (0, 1, 0, 1));
9643 assert!(!run_undo(&mut srv, &json!({ "steps": 2 })).is_error);
9644 for lane in [Lane::V1, Lane::A1] {
9645 assert_eq!(spans(&srv, lane), [(0, 30, 0, 30), (30, 90, 30, 90), (90, 150, 90, 150)], "{lane:?}");
9646 }
9647 }
9648
9649 #[test]
9650 fn slide_needs_a_clip_on_each_side() {
9651 let mut srv = three_clips();
9652 let before = snapshot(&srv);
9653 let first = ed(&mut srv, json!([{ "op": "slide", "clip": "V1@0", "by": "5f" }]));
9654 assert!(first.is_error && first.text.contains("no clip before it on V1"), "{}", first.text);
9655 let last = ed(&mut srv, json!([{ "op": "slide", "clip": "A1@90", "by": "-5f" }]));
9656 assert!(last.is_error && last.text.contains("no clip after it on A1"), "{}", last.text);
9657 let missing = ed(&mut srv, json!([{ "op": "slide", "clip": "V1@30" }]));
9658 assert!(missing.is_error && missing.text.contains("missing `by`"), "{}", missing.text);
9659 assert_eq!(snapshot(&srv), before);
9660 }
9661
9662 #[test]
9663 fn roll_slip_and_slide_refuse_a_locked_lane_of_the_take() {
9664 for op in [
9665 json!({ "op": "roll", "clip": "V1@0", "by": "5f" }),
9666 json!({ "op": "slip", "clip": "V1@30", "by": "5f" }),
9667 json!({ "op": "slide", "clip": "V1@30", "by": "5f" }),
9668 ] {
9669 let mut srv = three_clips();
9670 srv.session.as_mut().unwrap().set_lane_locked(Lane::A1, true);
9671 let before = snapshot(&srv);
9672 let r = ed(&mut srv, json!([op]));
9673 assert!(r.is_error && r.text.contains("lane A1 is locked"), "{}: {}", op, r.text);
9674 assert_eq!(snapshot(&srv), before);
9675 }
9676 }
9677
9678 #[test]
9679 fn a_locked_lane_refuses_by_name() {
9680 let mut srv = open();
9681 srv.session.as_mut().unwrap().set_lane_locked(Lane::A1, true);
9682 let depth = srv.session.as_ref().unwrap().undo_depth();
9683 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "A1", "at": "0s" }]));
9684 assert!(r.is_error);
9685 assert!(r.text.contains("lane A1 is locked"), "{}", r.text);
9686 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth);
9687 }
9688
9689 #[test]
9690 fn a_move_refusal_names_the_clip_it_would_overlap() {
9691 let mut srv = open();
9692 let half = first_len(&srv) / 2;
9693 assert!(!ed(&mut srv, json!([{ "op": "split", "at": format!("{half}f") }])).is_error);
9694 // Two clips and a third lane-mate: moving the first onto the second's start with no room must name it.
9695 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@0", "at": format!("{half}f") }]));
9696 assert!(r.is_error, "{}", r.text);
9697 assert!(r.text.contains(&format!("would overlap V1@{half} (")), "{}", r.text);
9698 assert!(r.text.contains("move V1@0 to V1@"), "{}", r.text);
9699 }
9700
9701 #[test]
9702 fn a_placed_pair_is_one_take_so_trim_moves_both() {
9703 let mut srv = open();
9704 let end = parse::session_end(srv.session.as_ref().unwrap());
9705 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": format!("{end}f"), "in": "0s", "out": "1s" }]));
9706 assert!(!r.is_error, "{}", r.text);
9707 let to = end + 10;
9708 let t = ed(&mut srv, json!([{ "op": "trim", "clip": format!("V1@{end}"), "edge": "out", "to": format!("{}f", end + 15) }]));
9709 assert!(!t.is_error, "{}", t.text);
9710 let s = srv.session.as_ref().unwrap();
9711 let v = s.lane_clips(Lane::V1).iter().find(|c| c.start == end).expect("placed picture");
9712 let a = s.lane_clips(Lane::A1).iter().find(|c| c.start == end).expect("placed sound");
9713 assert_eq!(v.end(), end + 15);
9714 assert_eq!(a.end(), end + 15, "the placed sound followed the picture (to {to})");
9715 }
9716
9717 #[test]
9718 fn a_move_to_where_the_clip_already_is_is_a_no_op() {
9719 let mut srv = open();
9720 let before = snapshot(&srv);
9721 let depth = srv.session.as_ref().unwrap().undo_depth();
9722 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@0", "at": "0s" }]));
9723 assert!(!r.is_error, "{}", r.text);
9724 assert!(r.text.contains("move V1@0: already at 0f (0.000s) — nothing to do"), "{}", r.text);
9725 assert!(r.text.contains("no change"), "{}", r.text);
9726 assert_eq!(snapshot(&srv), before);
9727 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth, "no engine snapshot was pushed");
9728 assert!(srv.ledger.is_empty(), "no ledger entry for a no-op");
9729 }
9730
9731 #[test]
9732 fn a_trim_error_echoes_the_unit_the_caller_wrote() {
9733 let mut srv = open();
9734 let fps = parse::session_fps(srv.session.as_ref().unwrap());
9735 // An out-of-room edge is clamped and the reply names the unit the caller wrote.
9736 let short = ed(&mut srv, json!([{ "op": "trim", "clip": "V1@0", "edge": "out", "to": "3s" }]));
9737 assert!(!short.is_error, "{}", short.text);
9738 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "V1@0", "edge": "out", "to": "99s" }]));
9739 let want = format!("clamped from 99s ({}f)", (99.0 * fps).round() as u32);
9740 assert!(!r.is_error && r.text.contains(&want), "{}", r.text);
9741 let mut fresh = open();
9742 ed(&mut fresh, json!([{ "op": "trim", "clip": "V1@0", "edge": "out", "to": "3s" }]));
9743 let frames = ed(&mut fresh, json!([{ "op": "trim", "clip": "V1@0", "edge": "out", "to": "2970f" }]));
9744 assert!(frames.text.contains("clamped from 2970f"), "a frame count is shown alone: {}", frames.text);
9745 }
9746
9747 #[test]
9748 fn placing_on_a_missing_lane_lists_the_lanes_and_names_the_fix() {
9749 let mut srv = open();
9750 let end = parse::session_end(srv.session.as_ref().unwrap());
9751 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "A2", "at": end }]));
9752 assert!(r.is_error, "{}", r.text);
9753 assert!(r.text.contains("lane A2 is not on this timeline; the lanes are "), "{}", r.text);
9754 assert!(r.text.contains("A1") && r.text.contains("V1"), "{}", r.text);
9755 assert!(r.text.contains(r#"{"op":"lane_add","kind":"audio"}"#), "{}", r.text);
9756 }
9757
9758 #[test]
9759 fn undo_and_redo_name_the_batch_they_move() {
9760 let mut srv = open();
9761 let half = first_len(&srv) / 2;
9762 let a = ed(&mut srv, json!([{ "op": "split", "at": format!("{half}f") }]));
9763 assert!(!a.is_error, "{}", a.text);
9764 let b = run_edit(
9765 &mut srv,
9766 &json!({ "ops": [{ "op": "fade", "clip": "V1@0", "out": "5f" }], "label": "Fade out" }),
9767 );
9768 assert!(!b.is_error, "{}", b.text);
9769 let u = run_undo(&mut srv, &json!({}));
9770 assert!(!u.is_error, "{}", u.text);
9771 let want = format!("undid: Fade out · undo 1 · redo 1 · next undo: split @{half}f");
9772 assert!(u.text.starts_with(&want), "{}", u.text);
9773 let r = run_redo(&mut srv, &json!({}));
9774 assert!(!r.is_error, "{}", r.text);
9775 assert!(r.text.starts_with("redid: Fade out · undo 2 · redo 0"), "{}", r.text);
9776 }
9777
9778 #[test]
9779 fn an_unlabelled_batch_is_named_by_its_ops() {
9780 let ops = json!([
9781 { "op": "split", "at": "1f" },
9782 { "op": "fade", "clip": "V1@0", "out": "5f" },
9783 { "op": "speed", "clip": "V1@0", "x": 2 },
9784 { "op": "title_remove", "title": "T1" }
9785 ]);
9786 assert_eq!(summarize(ops.as_array().unwrap(), &[]), "split @1f + fade V1@0 (+2 more)");
9787 assert_eq!(summarize(&[json!({ "op": "title_remove", "title": "T1" })], &[]), "title_remove T1");
9788 }
9789
9790 /// A clip op's label names the clips its apply reply touched, so a linked fade reads with its
9791 /// sound and a second fade on the sound is not labelled with the picture's address.
9792 #[test]
9793 fn a_clip_op_is_labelled_by_the_clips_it_touched() {
9794 let ops = [json!({ "op": "fade", "clip": "V1@0", "out": "5f" }), json!({ "op": "fade", "clip": "A1@0", "out": "5f" })];
9795 let touched = [vec!["V1@0".to_string(), "A1@0".to_string()], vec!["A1@0".to_string()]];
9796 assert_eq!(summarize(&ops, &touched), "fade V1@0, A1@0 + fade A1@0");
9797 let many: Vec<String> = ["V1@0", "A1@0", "V2@0", "A2@0"].iter().map(|s| s.to_string()).collect();
9798 assert_eq!(summarize(&ops[..1], &[many]), "fade V1@0, A1@0, V2@0 +1 more");
9799 }
9800
9801 #[test]
9802 fn an_unlabelled_linked_batch_is_labelled_with_its_applied_clips() {
9803 let mut srv = linked_take();
9804 let r = ed(&mut srv, json!([{ "op": "fade", "clip": "V1@0", "out": "1.0s" }, { "op": "fade", "clip": "A1@0", "out": "1.0s" }]));
9805 assert!(!r.is_error, "{}", r.text);
9806 let label = &srv.ledger.last().expect("one undo step").label;
9807 assert!(label.contains("V1@0, A1@0") && label.contains("fade A1@0"), "{label}");
9808 assert!(!label.contains("fade V1@0 + fade V1@0"), "{label}");
9809 }
9810
9811 #[test]
9812 fn a_batch_that_changes_the_duration_reports_the_timeline() {
9813 let mut srv = open();
9814 let fps = parse::session_fps(srv.session.as_ref().unwrap());
9815 let before = parse::session_end(srv.session.as_ref().unwrap());
9816 let r = ed(&mut srv, json!([{ "op": "insert_time", "at": "0s", "duration": "1s" }]));
9817 assert!(!r.is_error, "{}", r.text);
9818 let want = format!(
9819 "timeline {:.3}s → {:.3}s",
9820 parse::secs(before, fps),
9821 parse::secs(before, fps) + 1.0
9822 );
9823 assert!(r.text.contains(&want), "{}", r.text);
9824 let same = ed(&mut srv, json!([{ "op": "split", "at": "1.0s" }]));
9825 assert!(!same.text.contains("timeline "), "a batch that keeps the length adds no line: {}", same.text);
9826 }
9827
9828 #[test]
9829 fn insert_time_opens_a_gap_on_every_lane_and_is_one_undo_step() {
9830 let mut srv = open();
9831 let fps = parse::session_fps(srv.session.as_ref().unwrap());
9832 let at = (1.0 * fps).round() as u32;
9833 let dur = (2.0 * fps).round() as u32;
9834 let len = first_len(&srv);
9835 let before = snapshot(&srv);
9836 let r = ed(&mut srv, json!([{ "op": "insert_time", "at": "1s", "duration": "2s" }]));
9837 assert!(!r.is_error, "{}", r.text);
9838 {
9839 let s = srv.session.as_ref().unwrap();
9840 for lane in [Lane::V1, Lane::A1] {
9841 let clips = s.lane_clips(lane);
9842 assert_eq!(clips.len(), 2, "{lane:?}: the clip was cut at 1s");
9843 assert_eq!((clips[0].start, clips[0].end()), (0, at));
9844 assert_eq!(clips[1].start, at + dur, "{lane:?}: the rest moved two seconds later");
9845 assert_eq!(clips[1].frames(), len - at);
9846 }
9847 }
9848 assert_eq!(srv.ledger.len(), 1, "one batch, one undo entry");
9849 let u = run_undo(&mut srv, &json!({}));
9850 assert!(!u.is_error, "{}", u.text);
9851 assert_eq!(snapshot(&srv), before);
9852 }
9853
9854 #[test]
9855 fn insert_time_moves_titles_after_it() {
9856 let mut srv = open();
9857 let fps = parse::session_fps(srv.session.as_ref().unwrap());
9858 let t = ed(&mut srv, json!([{ "op": "title_add", "at": "2s", "duration": "1s", "text": "Hello" }]));
9859 assert!(!t.is_error, "{}", t.text);
9860 let r = ed(&mut srv, json!([{ "op": "insert_time", "at": "0s", "duration": "3s" }]));
9861 assert!(!r.is_error, "{}", r.text);
9862 let title = srv.session.as_ref().unwrap().titles()[0].clone();
9863 assert_eq!(title.start, (5.0 * fps).round() as u32);
9864 }
9865
9866 #[test]
9867 fn title_add_and_set_take_a_colour_weight_alignment_and_box() {
9868 use engine::text::{Align, HPlace, Weight};
9869 let mut srv = open();
9870 let r = ed(&mut srv, json!([{ "op": "title_add", "at": "1s", "duration": "2s", "text": "Jane\nDirector", "place": "bottom",
9871 "hplace": "left", "align": "left", "weight": "bold", "color": "#ffcc00", "boxed": true, "box_color": "#112233", "box_opacity": 0.5 }]));
9872 assert!(!r.is_error, "{}", r.text);
9873 assert!(r.text.contains("colour #ffcc00 bold left align left box #112233/50%"), "{}", r.text);
9874 let st = srv.session.as_ref().unwrap().titles()[0].style.clone();
9875 assert_eq!((st.hplace, st.align, st.weight, st.ink), (HPlace::Left, Align::Left, Weight::Bold, [255, 204, 0]));
9876 assert_eq!(st.box_color, [0x11, 0x22, 0x33, 128]);
9877 // Six digits keep the opacity, eight set it; the rest merges onto the title.
9878 let r = ed(&mut srv, json!([{ "op": "title_set", "title": "T1", "box_color": "000000c8", "align": "right" }]));
9879 assert!(!r.is_error, "{}", r.text);
9880 let st = srv.session.as_ref().unwrap().titles()[0].style.clone();
9881 assert_eq!((st.box_color, st.align, st.weight), ([0, 0, 0, 200], Align::Right, Weight::Bold));
9882 let r = ed(&mut srv, json!([{ "op": "title_set", "title": "T1", "box_color": "#ffffff" }]));
9883 assert_eq!(srv.session.as_ref().unwrap().titles()[0].style.box_color, [255, 255, 255, 200], "{}", r.text);
9884 for (key, val) in [("color", "red"), ("color", "#fff"), ("weight", "heavy"), ("hplace", "middle"), ("align", "justify"), ("box_color", "#12345"), ("box_opacity", "2")] {
9885 let r = ed(&mut srv, json!([{ "op": "title_set", "title": "T1", key: val }]));
9886 assert!(r.is_error, "{key} {val}: {}", r.text);
9887 }
9888 // Plain titles reply as they did.
9889 let r = ed(&mut srv, json!([{ "op": "title_add", "at": "5s", "duration": "1s", "text": "Plain" }]));
9890 assert!(!r.text.contains("colour") && !r.text.contains(" box "), "{}", r.text);
9891 }
9892
9893 #[test]
9894 fn insert_time_refuses_a_locked_lane_it_would_move() {
9895 let mut srv = open();
9896 srv.session.as_mut().unwrap().set_lane_locked(Lane::A1, true);
9897 let depth = srv.session.as_ref().unwrap().undo_depth();
9898 let r = ed(&mut srv, json!([{ "op": "insert_time", "at": "0s", "duration": "1s", "lanes": ["A1"] }]));
9899 assert!(r.is_error, "{}", r.text);
9900 assert!(r.text.contains("lane A1 is locked"), "{}", r.text);
9901 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth);
9902 }
9903
9904 /// An explicit `lanes` that holds a take's sound but not its picture refuses: the cut would split
9905 /// V1 and leave its half behind. The refusal names V1 and the lanes to add; adding it works.
9906 #[test]
9907 fn insert_time_refuses_to_split_a_take_partner_outside_lanes() {
9908 let mut srv = linked_take();
9909 let r = ed(&mut srv, json!([{ "op": "lane_add", "kind": "audio" }, { "op": "place", "source": 0, "lane": "A2", "at": "0s", "in": "0s", "out": "2s" }]));
9910 assert!(!r.is_error, "{}", r.text);
9911 let before = snapshot(&srv);
9912 let depth = srv.session.as_ref().unwrap().undo_depth();
9913 let r = ed(&mut srv, json!([{ "op": "insert_time", "at": "1s", "duration": "1s", "lanes": ["A1", "A2"] }]));
9914 assert!(r.is_error, "{}", r.text);
9915 assert!(r.text.contains("one take with the V1 clip at V1@0"), "{}", r.text);
9916 assert!(r.text.contains("Add V1 to lanes (lanes:[\"A1\",\"A2\",\"V1\"])"), "{}", r.text);
9917 assert_eq!(snapshot(&srv), before, "a refusal changes nothing");
9918 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth);
9919 let r = ed(&mut srv, json!([{ "op": "insert_time", "at": "1s", "duration": "1s", "lanes": ["V1", "A1", "A2"] }]));
9920 assert!(!r.is_error, "{}", r.text);
9921 let s = srv.session.as_ref().unwrap();
9922 let two_s = (2.0 * parse::session_fps(s)).round() as u32;
9923 assert!(s.lane_clips(Lane::V1).iter().any(|c| c.start == two_s), "the picture's second half moved with its sound");
9924 }
9925
9926 /// cut_regions on lanes with nothing in the span says so, instead of only counting the span.
9927 #[test]
9928 fn cut_regions_on_an_empty_lane_says_nothing_lies_in_the_span() {
9929 let mut srv = open();
9930 let r = ed(&mut srv, json!([{ "op": "lane_add", "kind": "audio" }]));
9931 assert!(!r.is_error, "{}", r.text);
9932 let r = ed(&mut srv, json!([{ "op": "cut_regions", "regions": [["1s", "2s"]], "lanes": ["A2"] }]));
9933 assert!(r.text.contains("nothing to cut, nothing on A2 lies in the span(s)"), "{}", r.text);
9934 assert!(r.text.contains("no change"), "{}", r.text);
9935 }
9936
9937 /// A clip wholly inside the span is named as removed, with its linked sound; a clip the span
9938 /// crosses is named as trimmed, with the timeline span it now has.
9939 #[test]
9940 fn remove_time_names_the_clips_it_removes_and_trims() {
9941 let mut srv = open();
9942 let fps = parse::session_fps(srv.session.as_ref().unwrap());
9943 let f = |s: f64| (s * fps).round() as u32;
9944 for at in ["1s", "2s"] {
9945 let r = ed(&mut srv, json!([{ "op": "split", "at": at }]));
9946 assert!(!r.is_error, "{}", r.text);
9947 }
9948 let r = ed(&mut srv, json!([{ "op": "remove_time", "at": "1s", "duration": "1s" }]));
9949 assert!(!r.is_error, "{}", r.text);
9950 assert!(r.text.contains(&format!("removed V1@{} (test_av.mp4)", f(1.0))), "{}", r.text);
9951 assert!(r.text.contains(&format!("A1@{} (test_av.mp4)", f(1.0))), "the linked sound is named too: {}", r.text);
9952
9953 let mut srv = open();
9954 let r = ed(&mut srv, json!([{ "op": "split", "at": "1s" }]));
9955 assert!(!r.is_error, "{}", r.text);
9956 let r = ed(&mut srv, json!([{ "op": "remove_time", "at": "1s", "duration": "1s" }]));
9957 assert!(!r.is_error, "{}", r.text);
9958 assert!(
9959 r.text.contains(&format!("trimmed V1@{} (test_av.mp4) now 1.0s–", f(1.0))),
9960 "the clip the span crosses is named as trimmed with its new span: {}",
9961 r.text
9962 );
9963 }
9964
9965 /// A split names only the clips it cuts: a lane whose clip merely ends at the cut is not one.
9966 #[test]
9967 fn split_names_only_the_clips_it_cut() {
9968 let mut srv = open();
9969 let fps = parse::session_fps(srv.session.as_ref().unwrap());
9970 let f = |s: f64| (s * fps).round() as u32;
9971 let r = ed(&mut srv, json!([{ "op": "split", "at": "1s", "lanes": ["V1"] }]));
9972 assert!(!r.is_error, "{}", r.text);
9973 // V1 now has a cut at 1s, so its clips end there; A1 still runs through it.
9974 let r = ed(&mut srv, json!([{ "op": "split", "at": "1s" }]));
9975 assert!(!r.is_error, "{}", r.text);
9976 assert!(r.text.contains(&format!("→ A1@0, A1@{}", f(1.0))), "{}", r.text);
9977 assert!(!r.text.contains("V1@0"), "V1 was not cut here, so it is not named: {}", r.text);
9978 }
9979
9980 #[test]
9981 fn remove_time_cuts_the_span_and_moves_the_rest_back() {
9982 let mut srv = open();
9983 let fps = parse::session_fps(srv.session.as_ref().unwrap());
9984 let end0 = parse::session_end(srv.session.as_ref().unwrap());
9985 let ok = ed(&mut srv, json!([{ "op": "remove_time", "at": "1s", "duration": "1s" }]));
9986 assert!(!ok.is_error, "{}", ok.text);
9987 let end1 = parse::session_end(srv.session.as_ref().unwrap());
9988 assert_eq!(end0 - end1, (1.0 * fps).round() as u32, "one second came out: {}", ok.text);
9989 }
9990
9991 /// A title wholly inside a removed span goes with it, one that straddles an edge is trimmed to
9992 /// the part outside, and a title after the span moves back. Each is named in the reply.
9993 #[test]
9994 fn remove_time_removes_a_title_inside_the_span_and_trims_a_straddler() {
9995 let mut srv = open();
9996 let fps = parse::session_fps(srv.session.as_ref().unwrap());
9997 let f = |s: f64| (s * fps).round() as u32;
9998 for (at, dur, text) in [("1.2s", "0.5s", "Inside"), ("1.5s", "1s", "Straddles"), ("3s", "1s", "After")] {
9999 let t = ed(&mut srv, json!([{ "op": "title_add", "at": at, "duration": dur, "text": text }]));
10000 assert!(!t.is_error, "{}", t.text);
10001 }
10002 let r = ed(&mut srv, json!([{ "op": "remove_time", "at": "1s", "duration": "1s" }]));
10003 assert!(!r.is_error, "a title inside the span is no refusal: {}", r.text);
10004 assert!(r.text.contains("removed with the span: T1") && r.text.contains("trimmed to the span's edge: T2 now 1.0s–1.5s"), "{}", r.text);
10005 let titles = srv.session.as_ref().unwrap().titles().to_vec();
10006 let texts: Vec<&str> = titles.iter().map(|t| t.text.as_str()).collect();
10007 assert_eq!(texts, ["Straddles", "After"], "the inside title is gone: {}", r.text);
10008 assert_eq!((titles[0].start, titles[0].frames), (f(1.0), f(0.5)), "the straddler keeps the part before the span's end");
10009 assert_eq!(titles[1].start, f(2.0), "the title after the span moves back by it");
10010 }
10011
10012 /// A move carries a title wholly over the clip by default, says which title stays put when
10013 /// it only partly covers the clip, and `titles` true or false sets the choice.
10014 #[test]
10015 fn move_carries_the_titles_over_the_clip_and_says_which_stay() {
10016 fn setup() -> Server {
10017 // The 5 s take on V1 and A1: "Over" lies wholly on the picture, "Half" runs past its end.
10018 let mut srv = open();
10019 for (at, dur, text) in [("0.5s", "1s", "Over"), ("4.5s", "1s", "Half")] {
10020 let t = ed(&mut srv, json!([{ "op": "title_add", "at": at, "duration": dur, "text": text }]));
10021 assert!(!t.is_error, "{}", t.text);
10022 }
10023 srv
10024 }
10025 let starts = |srv: &Server| -> Vec<(String, u32)> {
10026 srv.session.as_ref().unwrap().titles().iter().map(|t| (t.text.clone(), t.start)).collect()
10027 };
10028 let fps = 30.0;
10029 let over = 15; // 0.5 s
10030 let half = 135; // 4.5 s
10031 let to10 = (10.0 * fps) as u32; // the clip moves from 0 to 10 s
10032
10033 let mut srv = setup();
10034 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@0", "at": "10s" }]));
10035 assert!(!r.is_error, "{}", r.text);
10036 assert!(r.text.contains("titles moved with the clip: T1"), "{}", r.text);
10037 assert!(r.text.contains("T2 (1.0s) sat over V1@0 and stays put"), "the partly covered title stays: {}", r.text);
10038 assert_eq!(starts(&srv), vec![("Half".to_string(), half), ("Over".to_string(), to10 + over)], "{}", r.text);
10039
10040 let mut srv = setup();
10041 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@0", "at": "10s", "titles": false }]));
10042 assert!(!r.is_error && !r.text.contains("titles moved"), "{}", r.text);
10043 assert_eq!(starts(&srv), vec![("Over".to_string(), over), ("Half".to_string(), half)], "titles:false carries none: {}", r.text);
10044
10045 let mut srv = setup();
10046 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@0", "at": "10s", "titles": true }]));
10047 assert!(!r.is_error, "{}", r.text);
10048 assert_eq!(starts(&srv), vec![("Over".to_string(), to10 + over), ("Half".to_string(), to10 + half)], "titles:true carries both: {}", r.text);
10049 }
10050
10051 /// A delete names the clips it moved, and no "left in place" list: the clips on other lanes
10052 /// it does not touch are not news in a plain delete (ripple_delete still lists them).
10053 #[test]
10054 fn delete_names_no_left_in_place_list() {
10055 let mut srv = open();
10056 let ops = json!([
10057 { "op": "lane_add", "kind": "video" },
10058 { "op": "place", "source": 0, "at": "0s", "in": "0s", "out": "2s", "lane": "V2", "audio": false },
10059 { "op": "place", "source": 0, "at": "4s", "in": "0s", "out": "1s", "lane": "V2", "audio": false },
10060 { "op": "delete", "clip": "V2@0", "lanes": ["V2"] }
10061 ]);
10062 let r = ed(&mut srv, ops);
10063 assert!(!r.is_error, "{}", r.text);
10064 assert!(!r.text.contains("left in place"), "{}", r.text);
10065 let clips = srv.session.as_ref().unwrap().lane_clips(Lane::new(LaneKind::Video, 1));
10066 assert_eq!(clips.last().map(|c| c.start), Some(60), "the clip after the deleted one moved back by its length: {}", r.text);
10067 }
10068
10069 /// `place` with `stretch` fits the whole source into `length` and says the speed it used; a
10070 /// stretch outside the speed range is refused by name, and the refusal names stretch.
10071 #[test]
10072 fn place_stretch_fits_the_source_into_the_length() {
10073 let mut srv = open();
10074 let added = ed(&mut srv, json!([{ "op": "lane_add", "kind": "video" }]));
10075 assert!(!added.is_error, "{}", added.text);
10076 // The 5 s asset into 3.2 s: the speed is 5 / 3.2, about 1.5625.
10077 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "20s", "in": "0s", "length": "3.2s", "stretch": true, "lane": "V2", "audio": false }]));
10078 assert!(!r.is_error, "{}", r.text);
10079 assert!(r.text.contains("stretched ×1.56") && r.text.contains("(sped up)"), "{}", r.text);
10080 let c = srv.session.as_ref().unwrap().lane_clips(Lane::new(LaneKind::Video, 1))[0].clone();
10081 assert!((c.frames() as i64 - 96).abs() <= 1, "the clip fills 3.2 s, got {} frames", c.frames());
10082 // Without stretch the same length past the source end still refuses, and names stretch.
10083 let past = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "40s", "in": "4s", "length": "2s", "lane": "V1", "audio": false }]));
10084 assert!(past.is_error && past.text.contains("stretch:true"), "{}", past.text);
10085 let fast = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "40s", "in": "0s", "length": "0.5s", "stretch": true, "lane": "V1", "audio": false }]));
10086 assert!(fast.is_error && fast.text.contains("outside 0.25–4"), "{}", fast.text);
10087 }
10088
10089 #[test]
10090 fn a_speed_factor_reads_to_three_decimals_and_names_its_direction() {
10091 assert_eq!(speed_text(5.0 / 16.2), "0.309");
10092 assert_eq!(speed_text(2.0), "2");
10093 assert_eq!(speed_note(5.0 / 16.2), " (slow motion)");
10094 assert_eq!(speed_note(1.5625), " (sped up)");
10095 assert_eq!(speed_note(1.0), "");
10096 }
10097
10098 /// The source end is shown no later than the file's real duration: 6.000 s of frames on a
10099 /// 5.968 s file reads 5.968s.
10100 #[test]
10101 fn a_source_end_past_the_real_duration_reads_the_duration() {
10102 let b = Base { src: 25_000_000, tl: 30_000_000, dur: 5.968 };
10103 assert_eq!(b.pos(150), "5.968s", "a frame rounded past the file's end is the end");
10104 assert_eq!(b.pos(100), "4.000s", "inside the file, the frame's own time");
10105 let whole = Base { src: 25_000_000, tl: 30_000_000, dur: f64::MAX };
10106 assert_eq!(whole.pos(150), "6.000s", "no duration known: the frame's own time");
10107 }
10108
10109 /// A seconds length that overlaps by a frame says why: the length rounds to whole frames and
10110 /// the clip ends a frame later than the seconds suggest, with the frame length to give instead.
10111 #[test]
10112 fn a_seconds_length_that_overlaps_explains_the_rounding() {
10113 let mut srv = open();
10114 // The V1 clip from 0 covers the first seconds; 2.0167 s is 60.5 frames at 30 fps, so it
10115 // rounds up to 61f and runs to frame 91 from timeline frame 30.
10116 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "1s", "length": "2.0167s", "audio": false }]));
10117 assert!(r.is_error && r.text.contains(" is taken: src:0"), "{}", r.text);
10118 assert!(r.text.contains("length 2.0167s rounds up to 61f (2.033s) and ends at 91f"), "{}", r.text);
10119 assert!(r.text.contains("give length in frames (e.g. \"60f\") or start 1 frame later"), "{}", r.text);
10120 // A length in frames is not explained: it has no rounding to explain.
10121 let frames = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "1s", "length": "61f", "audio": false }]));
10122 assert!(frames.is_error && !frames.text.contains("rounds"), "{}", frames.text);
10123 }
10124
10125 /// A seconds `at` or `in` that rounds to a frame is named in the overlap refusal, with the math and
10126 /// the frame to write. A refusal where every value is already a frame has no note.
10127 #[test]
10128 fn a_seconds_start_or_in_that_rounds_is_named_in_an_overlap() {
10129 let mut srv = open();
10130 // 1.0167 s is 30.501 frames at 30 fps: it rounds to 31f (1.033 s), inside the clip from 0.
10131 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "1.0167s", "length": "0.5s", "audio": false }]));
10132 assert!(r.is_error && r.text.contains(" is taken: src:0"), "{}", r.text);
10133 assert!(r.text.contains("at 1.0167s is 30.501f, which rounds to 31f (1.033s)"), "{}", r.text);
10134 assert!(r.text.contains("write at \"31f\" in frames"), "{}", r.text);
10135 // 0.5 s is exactly 15 frames, so the length is not explained.
10136 assert!(!r.text.contains("length 0.5s"), "{}", r.text);
10137 // 1.53 s is 45.9 source frames at 30 fps: the `in` rounds to 46f.
10138 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "1s", "in": "1.53s", "audio": false }]));
10139 assert!(r.is_error && r.text.contains("in 1.53s is 45.900f at 30 fps, which rounds to 46f"), "{}", r.text);
10140 assert!(r.text.contains("write in \"46f\" in frames"), "{}", r.text);
10141 // Frames all round: nothing is named.
10142 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "30f", "length": "61f", "audio": false }]));
10143 assert!(r.is_error && !r.text.contains("rounds") && !r.text.contains("in frames"), "{}", r.text);
10144 }
10145
10146 /// Holes left by several ops of one batch are one summary line per lane, not a line per op. A single
10147 /// op keeps its own line.
10148 #[test]
10149 fn holes_from_several_ops_are_one_summary_line() {
10150 let mut srv = open();
10151 let r = ed(&mut srv, json!([{ "op": "split", "at": "1s" }, { "op": "split", "at": "2s" }, { "op": "split", "at": "3s" }, { "op": "split", "at": "4s" }]));
10152 assert!(!r.is_error, "{}", r.text);
10153 // Two clips apart: each lift leaves its own gap. (Adjacent lifts would merge into one gap.)
10154 let r = ed(&mut srv, json!([{ "op": "lift", "clip": "A1@30" }, { "op": "lift", "clip": "A1@90" }]));
10155 assert!(!r.is_error, "{}", r.text);
10156 assert!(r.text.contains("holes left on A1 at 1.000s, 3.000s (close_gaps cannot close them: the A1 clip at A1@0"), "{}", r.text);
10157 assert_eq!(r.text.matches("holes left on A1").count(), 1, "{}", r.text);
10158 assert!(!r.text.contains("by lift"), "{}", r.text);
10159 // One op alone keeps its own line, named by the span it left.
10160 let mut srv = open();
10161 let r = ed(&mut srv, json!([{ "op": "split", "at": "1s" }, { "op": "split", "at": "2s" }]));
10162 assert!(!r.is_error, "{}", r.text);
10163 let r = ed(&mut srv, json!([{ "op": "lift", "clip": "A1@30" }]));
10164 assert!(r.text.contains("hole left on A1 at 1.000–2.000s by lift"), "{}", r.text);
10165 }
10166
10167 /// A caption cue a delete cuts out is named in its reply, as ripple_delete names it.
10168 #[test]
10169 fn delete_names_the_caption_cues_it_removes() {
10170 let mut srv = linked_take();
10171 let dir = TestDir::new("delete-cues");
10172 let a = dir.path().join("a.srt");
10173 std::fs::write(&a, "1\n00:00:01,000 --> 00:00:02,000\nInside cue\n").unwrap();
10174 let r = ed(
10175 &mut srv,
10176 json!([
10177 { "op": "subtitles_import", "path": a.to_string_lossy() },
10178 { "op": "captions_place", "track": 0, "lane": "S1", "at": "0f" },
10179 { "op": "delete", "clip": "V1@0" }
10180 ]),
10181 );
10182 assert!(!r.is_error, "{}", r.text);
10183 assert!(r.text.contains("caption cue(s) removed: \"Inside cue\" (1.000s–2.000s)"), "{}", r.text);
10184 assert!(srv.session.as_ref().unwrap().sub_lane_cues(Lane::S1).is_empty(), "the cue is gone");
10185 }
10186
10187 /// A stretch slower than the source reads as slow motion, with the factor at three decimals:
10188 /// 5 s into 16.2 s is ×0.309 (5 / 16.2 = 0.30864...).
10189 #[test]
10190 fn place_stretch_slower_than_the_source_says_slow_motion() {
10191 let mut srv = open();
10192 let added = ed(&mut srv, json!([{ "op": "lane_add", "kind": "video" }]));
10193 assert!(!added.is_error, "{}", added.text);
10194 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "20s", "in": "0s", "length": "16.2s", "stretch": true, "lane": "V2", "audio": false }]));
10195 assert!(!r.is_error, "{}", r.text);
10196 assert!(r.text.contains("stretched ×0.309 to ") && r.text.contains("(485f) (slow motion)"), "{}", r.text);
10197 assert!(!r.text.contains("0.30927835"), "the factor is rounded, not printed in full: {}", r.text);
10198 }
10199
10200 /// A dissolve or a fade whose clip a cut removes is named in the reply, not dropped silently.
10201 #[test]
10202 fn a_dropped_dissolve_or_fade_is_named_in_the_effects() {
10203 let mut srv = open();
10204 let r = ed(&mut srv, json!([
10205 { "op": "lane_add", "kind": "video" },
10206 { "op": "place", "source": 0, "at": "0s", "in": "0s", "out": "2s", "lane": "V2", "audio": false },
10207 { "op": "place", "source": 0, "at": "2s", "in": "0s", "out": "2s", "lane": "V2", "audio": false },
10208 { "op": "dissolve", "clip": "V2@0", "frames": 12, "linked": false },
10209 { "op": "fade", "clip": "V2@2s", "out": "5f", "linked": false },
10210 { "op": "delete", "clip": "V2@0", "lanes": ["V2"] }
10211 ]));
10212 assert!(!r.is_error, "{}", r.text);
10213 assert!(r.text.contains("dissolve dropped on V2@0"), "{}", r.text);
10214 let r = ed(&mut srv, json!([{ "op": "delete", "clip": "V2@0", "lanes": ["V2"] }]));
10215 assert!(!r.is_error && r.text.contains("fade dropped on V2 ×1"), "{}", r.text);
10216 }
10217
10218 /// A cut closes a hole it leaves under the sliver on the lanes it ripples, and says so.
10219 #[test]
10220 fn cut_regions_closes_a_sliver_hole_on_the_lanes_in_scope() {
10221 let mut srv = open();
10222 // Two picture clips with a single frame between them: a hole under CUT_SLIVER_FRAMES.
10223 let r = ed(&mut srv, json!([
10224 { "op": "lane_add", "kind": "video" },
10225 { "op": "place", "source": 0, "at": "0f", "in": "0s", "out": "2s", "lane": "V2", "audio": false },
10226 { "op": "place", "source": 0, "at": "61f", "in": "0s", "out": "2s", "lane": "V2", "audio": false },
10227 { "op": "cut_regions", "regions": [["100f", "102f"]], "lanes": ["V2"] }
10228 ]));
10229 assert!(!r.is_error, "{}", r.text);
10230 assert!(r.text.contains("closed 1 hole(s) under 4f on V2"), "{}", r.text);
10231 assert_eq!(srv.session.as_ref().unwrap().gap_count(Lane::new(LaneKind::Video, 1)), 0, "{}", r.text);
10232 }
10233
10234 /// Mean absolute difference of two composed frames, per BGRA byte.
10235 fn mean_diff(a: &engine::decode::Frame, b: &engine::decode::Frame) -> f64 {
10236 assert_eq!((a.width, a.height), (b.width, b.height));
10237 let total: u64 = a.bgra.iter().zip(&b.bgra).map(|(x, y)| u64::from(x.abs_diff(*y))).sum();
10238 total as f64 / a.bgra.len() as f64
10239 }
10240
10241 fn compose(srv: &Server, at: u32) -> engine::decode::Frame {
10242 let (proj, meta) = srv.session.as_ref().unwrap().export_snapshot();
10243 engine::export::compose_at(&proj, &meta, at, meta.width, meta.height).expect("compose")
10244 }
10245
10246 #[test]
10247 fn freeze_inserts_a_still_and_shifts_the_rest() {
10248 let dir = TestDir::new("freeze-insert");
10249 let mut srv = open();
10250 srv.path = Some(dir.join("cut.edith"));
10251 let fps = parse::session_fps(srv.session.as_ref().unwrap());
10252 let at = (1.0 * fps).round() as u32;
10253 let dur = (2.0 * fps).round() as u32;
10254 let len = first_len(&srv);
10255 let end0 = parse::session_end(srv.session.as_ref().unwrap());
10256 let pre = compose(&srv, at);
10257 let before = snapshot(&srv);
10258 let r = ed(&mut srv, json!([{ "op": "freeze", "at": "1s", "duration": "2s" }]));
10259 assert!(!r.is_error, "{}", r.text);
10260 assert!(r.text.contains(&format!("freeze/cut-{at}-")), "{}", r.text);
10261 assert_eq!(std::fs::read_dir(dir.join("freeze")).unwrap().count(), 1);
10262 let post = compose(&srv, at + (fps.round() as u32));
10263 {
10264 let s = srv.session.as_ref().unwrap();
10265 assert_eq!(parse::session_end(s), end0 + dur, "the timeline grew by the duration");
10266 let clips = s.lane_clips(Lane::V1);
10267 let still = clips.iter().find(|c| c.start == at).expect("a still starts at `at`");
10268 assert_eq!(still.frames(), dur, "the still is held for the duration");
10269 let name = s.sources()[still.source].path.file_name().unwrap().to_string_lossy().into_owned();
10270 assert!(name.starts_with(&format!("cut-{at}-")) && name.ends_with(".png"), "{name}");
10271 let rest = clips.iter().find(|c| c.start == at + dur).expect("the rest moved by the duration");
10272 assert_eq!(rest.frames(), len - at);
10273 }
10274 assert!(mean_diff(&pre, &post) < 4.0, "the still shows the frame it was taken from");
10275 let u = run_undo(&mut srv, &json!({}));
10276 assert!(!u.is_error, "{}", u.text);
10277 assert_eq!(snapshot(&srv), before);
10278 }
10279
10280 /// The source index of the still on V1 that starts at `at`.
10281 fn still_source(srv: &Server, at: u32) -> usize {
10282 let s = srv.session.as_ref().unwrap();
10283 s.lane_clips(Lane::V1).iter().find(|c| c.start == at).expect("a still at `at`").source
10284 }
10285
10286 #[test]
10287 fn freeze_same_frame_reuses_the_source_and_a_graded_clip_gets_a_new_one() {
10288 let dir = TestDir::new("freeze-reuse");
10289 let mut srv = open();
10290 srv.path = Some(dir.join("cut.edith"));
10291 let at = (1.0 * parse::session_fps(srv.session.as_ref().unwrap())).round() as u32;
10292 let freeze = json!([{ "op": "freeze", "at": "1s", "duration": "1s" }]);
10293
10294 let r = ed(&mut srv, freeze.clone());
10295 assert!(!r.is_error, "{}", r.text);
10296 let first = still_source(&srv, at);
10297 let sources0 = srv.session.as_ref().unwrap().sources().len();
10298 assert!(!run_undo(&mut srv, &json!({})).is_error);
10299
10300 // Same frame, nothing changed: the file and its source are reused.
10301 let r = ed(&mut srv, freeze.clone());
10302 assert!(!r.is_error, "{}", r.text);
10303 assert_eq!(still_source(&srv, at), first, "the same pixels reuse the same source index");
10304 assert_eq!(srv.session.as_ref().unwrap().sources().len(), sources0, "no duplicate import");
10305 assert_eq!(std::fs::read_dir(dir.join("freeze")).unwrap().count(), 1);
10306 assert!(!run_undo(&mut srv, &json!({})).is_error);
10307
10308 // A grade on the clip changes the pixels: a new file and a new source.
10309 let g = ed(&mut srv, json!([{ "op": "color", "clip": "V1#0", "brightness": 0.3 }]));
10310 assert!(!g.is_error, "{}", g.text);
10311 let r = ed(&mut srv, freeze);
10312 assert!(!r.is_error, "{}", r.text);
10313 assert_ne!(still_source(&srv, at), first, "a changed frame gets a new source");
10314 assert_eq!(std::fs::read_dir(dir.join("freeze")).unwrap().count(), 2);
10315 }
10316
10317 #[test]
10318 fn freeze_refuses_an_unsaved_project_and_changes_nothing() {
10319 let mut srv = open();
10320 let depth = srv.session.as_ref().unwrap().undo_depth();
10321 let r = ed(&mut srv, json!([{ "op": "freeze", "at": "1s", "duration": "1s" }]));
10322 assert!(r.is_error && r.text.contains("project_save"), "{}", r.text);
10323 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth);
10324 }
10325
10326 #[test]
10327 fn freeze_without_insert_overlays_a_new_top_lane() {
10328 let dir = TestDir::new("freeze-overlay");
10329 let mut srv = open();
10330 srv.path = Some(dir.join("cut.edith"));
10331 let end0 = parse::session_end(srv.session.as_ref().unwrap());
10332 let before = snapshot(&srv);
10333 let r = ed(&mut srv, json!([{ "op": "freeze", "at": "1s", "duration": "1s", "insert": false }]));
10334 assert!(!r.is_error, "{}", r.text);
10335 // The reply says why the still is on a lane the caller did not name.
10336 assert!(r.text.contains("added lane V2 for the still, since insert:false with no lane"), "{}", r.text);
10337 let s = srv.session.as_ref().unwrap();
10338 assert_eq!(parse::session_end(s), end0, "an overlay keeps the length");
10339 let top = Lane::new(LaneKind::Video, 1);
10340 let fps = parse::session_fps(s);
10341 let dur = (fps).round() as u32;
10342 let still = s.lane_clips(top).iter().find(|c| c.start == (fps).round() as u32).expect("still on V2");
10343 assert_eq!(still.frames(), dur);
10344 let after = snapshot(&srv);
10345 assert_eq!(after.iter().find(|(l, _)| *l == Lane::V1), before.iter().find(|(l, _)| *l == Lane::V1));
10346 }
10347
10348 /// The test asset opens as a linked V1+A1 take at 0.
10349 fn linked_take() -> Server {
10350 let srv = open();
10351 let s = srv.session.as_ref().unwrap();
10352 assert!(!s.lane_clips(Lane::A1).is_empty(), "the test asset has sound");
10353 assert_eq!(s.lane_clips(Lane::V1)[0].link, s.lane_clips(Lane::A1)[0].link, "one take");
10354 srv
10355 }
10356
10357 #[test]
10358 fn fade_reaches_the_linked_sound_and_says_so() {
10359 let mut srv = linked_take();
10360 let r = ed(&mut srv, json!([{ "op": "fade", "clip": "V1@0", "out": "1.0s" }]));
10361 assert!(!r.is_error, "{}", r.text);
10362 let s = srv.session.as_ref().unwrap();
10363 assert!(s.fade_out_of(Lane::V1, 0) > 0, "picture faded");
10364 assert!(s.fade_out_of(Lane::A1, 0) > 0, "sound faded with it");
10365 assert!(r.text.contains("V1@0") && r.text.contains("A1@0"), "{}", r.text);
10366 }
10367
10368 #[test]
10369 fn fade_says_when_the_engine_clamps_the_ramp() {
10370 let mut srv = linked_take();
10371 // The clip is 5.0 s; a 9.0 s ramp is kept at the clip's length, and the reply says so.
10372 let r = ed(&mut srv, json!([{ "op": "fade", "clip": "V1@0", "in": "9.0s" }]));
10373 assert!(!r.is_error, "{}", r.text);
10374 let s = srv.session.as_ref().unwrap();
10375 assert_eq!(s.fade_in_of(Lane::V1, 0), s.lane_clips(Lane::V1)[0].frames());
10376 assert!(r.text.contains("in clamped from 9.0s to the clip's 5.0s"), "{}", r.text);
10377 // A ramp that fits is named without a clamp note.
10378 let r = ed(&mut srv, json!([{ "op": "fade", "clip": "V1@0", "out": "1.0s", "linked": false }]));
10379 assert!(!r.is_error, "{}", r.text);
10380 assert!(!r.text.contains("clamped"), "{}", r.text);
10381 }
10382
10383 #[test]
10384 fn fade_with_linked_false_leaves_the_sound_alone() {
10385 let mut srv = linked_take();
10386 let r = ed(&mut srv, json!([{ "op": "fade", "clip": "V1@0", "out": "1.0s", "linked": false }]));
10387 assert!(!r.is_error, "{}", r.text);
10388 let s = srv.session.as_ref().unwrap();
10389 assert!(s.fade_out_of(Lane::V1, 0) > 0);
10390 assert_eq!(s.fade_out_of(Lane::A1, 0), 0, "sound untouched");
10391 assert!(!r.text.contains("A1@0"), "{}", r.text);
10392 }
10393
10394 #[test]
10395 fn fade_linked_must_be_a_bool() {
10396 let mut srv = linked_take();
10397 let r = ed(&mut srv, json!([{ "op": "fade", "clip": "V1@0", "out": "5f", "linked": "no" }]));
10398 assert!(r.is_error && r.text.contains("`linked` must be true or false"), "{}", r.text);
10399 }
10400
10401 /// A read tool (`clip_info`, `timeline`) called the way a model calls it.
10402 fn read(srv: &mut Server, name: &str, args: Value) -> Reply {
10403 let t = crate::server::tools().into_iter().find(|t| t.name == name).expect("tool exists");
10404 (t.run)(srv, &args)
10405 }
10406
10407 /// The link the engine holds for the clip at `at` on `lane`, against what the two reads a
10408 /// model makes say about it: `clip_info` names that id (or "link: none"), and the timeline
10409 /// shows a link on some row exactly when some clip holds one.
10410 fn assert_reads_agree(srv: &mut Server, addr: &str, lane: Lane, at: u32) {
10411 // How many placements (clips and captions, any lane) carry each id, read
10412 // off the engine in its own block so the session is not borrowed while
10413 // the reads below run.
10414 let (engine, shared, any_take, any_detached) = {
10415 let s = srv.session.as_ref().expect("session");
10416 let carried = |id: u32| {
10417 s.lanes()
10418 .into_iter()
10419 .map(|l| {
10420 s.lane_clips(l).iter().filter(|c| c.link == Some(id)).count()
10421 + s.sub_lane(l).iter().filter(|c| c.link == Some(id)).count()
10422 })
10423 .sum::<usize>()
10424 };
10425 let engine = s.lane_clips(lane).iter().find(|c| c.start == at).and_then(|c| c.link);
10426 let ids: Vec<u32> = s.lanes().into_iter().flat_map(|l| s.lane_clips(l).iter().filter_map(|c| c.link).collect::<Vec<_>>()).collect();
10427 let any_take = ids.iter().any(|&id| carried(id) >= 2);
10428 let any_detached = ids.iter().any(|&id| carried(id) == 1);
10429 (engine, engine.is_some_and(|id| carried(id) >= 2), any_take, any_detached)
10430 };
10431 let info = read(srv, "clip_info", json!({ "clip": addr }));
10432 assert!(!info.is_error, "{}", info.text);
10433 match engine {
10434 None => assert!(info.text.contains("link: none"), "{addr} holds no id: {}", info.text),
10435 Some(id) if shared => assert!(info.text.contains(&format!("link {id}")), "{addr} holds {id}: {}", info.text),
10436 Some(_) => assert!(info.text.contains("detached (ungrouped)"), "{addr} is detached: {}", info.text),
10437 }
10438 let tl = read(srv, "timeline", json!({}));
10439 assert!(!tl.is_error, "{}", tl.text);
10440 assert_eq!(tl.text.contains(" linked to "), any_take, "timeline disagrees about takes: {}", tl.text);
10441 assert_eq!(tl.text.contains("detached (ungrouped)"), any_detached, "timeline disagrees about detached clips: {}", tl.text);
10442 }
10443
10444 #[test]
10445 fn a_lifted_partner_reads_unlinked_in_timeline_and_clip_info() {
10446 let mut srv = linked_take();
10447 let r = ed(&mut srv, json!([{ "op": "lift", "clip": "V1@0" }]));
10448 assert!(!r.is_error, "{}", r.text);
10449 assert_reads_agree(&mut srv, "A1@0", Lane::A1, 0);
10450 }
10451
10452 #[test]
10453 fn a_one_lane_ripple_delete_leaves_the_partner_unlinked_in_both_reads() {
10454 let mut srv = linked_take();
10455 // A one-lane ripple of a take is refused, so the take is detached first.
10456 let r = ed(
10457 &mut srv,
10458 json!([
10459 { "op": "ungroup", "clip": "V1@0" },
10460 { "op": "ripple_delete", "clip": "V1@0", "lanes": ["V1"] }
10461 ]),
10462 );
10463 assert!(!r.is_error, "{}", r.text);
10464 assert!(srv.session.as_ref().unwrap().lane_clips(Lane::V1).is_empty(), "the picture is gone");
10465 assert_reads_agree(&mut srv, "A1@0", Lane::A1, 0);
10466 }
10467
10468 #[test]
10469 fn a_copy_of_the_same_source_elsewhere_on_its_lane_detaches_nothing() {
10470 // The copy shares the picture's identity (source and in-point) but has no sound, so a lookup
10471 // by identity alone would find it in place of the linked clip and call the take detached.
10472 let mut srv = linked_take();
10473 let r = ed(&mut srv, json!([{ "op": "place", "source": "src:0", "lane": "V1", "at": "10s", "audio": false }]));
10474 assert!(!r.is_error, "{}", r.text);
10475 assert!(!r.text.contains("detached") && !r.text.contains("linked:"), "{}", r.text);
10476 for op in [
10477 json!({ "op": "limiter", "on": true, "ceiling_db": -3 }),
10478 json!({ "op": "title_add", "at": "2s", "duration": "1s", "text": "Hi" }),
10479 ] {
10480 let r = ed(&mut srv, json!([op]));
10481 assert!(!r.is_error, "{}", r.text);
10482 assert!(!r.text.contains("detached") && !r.text.contains("linked:"), "{}", r.text);
10483 }
10484 let s = srv.session.as_ref().unwrap();
10485 let v = s.lane_clips(Lane::V1).iter().find(|c| c.start == 0).expect("the linked picture");
10486 let a = s.lane_clips(Lane::A1).iter().find(|c| c.start == 0).expect("the linked sound");
10487 assert!(v.link.is_some() && v.link == a.link, "the take is still one take");
10488 }
10489
10490 #[test]
10491 fn an_ungroup_still_names_the_detached_partners() {
10492 let mut srv = linked_take();
10493 let r = ed(&mut srv, json!([{ "op": "ungroup", "clip": "V1@0" }]));
10494 assert!(!r.is_error, "{}", r.text);
10495 assert!(r.text.contains("V1@0 is now detached") && r.text.contains("A1@0 is now detached"), "{}", r.text);
10496 }
10497
10498 #[test]
10499 fn an_ungroup_that_leaves_a_take_names_the_detached_clip_and_the_take_that_stays() {
10500 // The loose V2 clip is its own take (it starts at 3s), grouped with the V1+A1 take.
10501 let mut srv = linked_take();
10502 let r = ed(
10503 &mut srv,
10504 json!([
10505 { "op": "lane_add", "kind": "video" },
10506 { "op": "place", "source": 0, "lane": "V2", "at": "3s", "in": "0s", "out": "2s", "audio": false },
10507 { "op": "group", "clips": ["V1@0", "V2@3s"] }
10508 ]),
10509 );
10510 assert!(!r.is_error, "{}", r.text);
10511 let r = ed(&mut srv, json!([{ "op": "ungroup", "clip": "V2@3s" }]));
10512 assert!(!r.is_error, "{}", r.text);
10513 // The reply names clips by their frame address: 3s is V2@90 at 30 fps.
10514 assert!(r.text.contains("V2@90 is now detached"), "{}", r.text);
10515 assert!(r.text.contains("V1@0+A1@0 stay one take"), "{}", r.text);
10516 assert!(!r.text.contains("V1@0 is now detached") && !r.text.contains("A1@0 is now detached"), "{}", r.text);
10517 }
10518
10519 /// A 30 fps timeline with the 23.976 fps test_23976fps.mp4 (2.002 s picture, 2.0 s sound) as src:1.
10520 fn open_30_with_23976() -> Server {
10521 engine::ao::set_silent_output();
10522 let mut sess = PlaybackSession::open(asset("test_av.mp4")).expect("open 30 fps asset");
10523 sess.import(&asset("test_23976fps.mp4")).expect("import 23.976 fps asset");
10524 Server { session: Some(sess), ..Server::default() }
10525 }
10526
10527 /// The picture and sound a placement landed at `start` are one span: same frames, same source range.
10528 fn assert_take_spans_agree(srv: &Server, start: u32) {
10529 let s = srv.session.as_ref().unwrap();
10530 let v = s.lane_clips(Lane::V1).iter().find(|c| c.start == start).expect("the picture");
10531 let a = s.lane_clips(Lane::A1).iter().find(|c| c.start == start).expect("the sound");
10532 assert_eq!(v.frames(), a.frames(), "picture {}f, sound {}f", v.frames(), a.frames());
10533 assert_eq!((v.in_frame, v.out_frame), (a.in_frame, a.out_frame), "picture and sound source ranges differ");
10534 }
10535
10536 #[test]
10537 fn a_23976_take_places_picture_and_sound_over_one_span() {
10538 let mut srv = open_30_with_23976();
10539 let r = ed(&mut srv, json!([{ "op": "place", "source": "src:1", "at": "47s" }]));
10540 assert!(!r.is_error, "{}", r.text);
10541 assert_take_spans_agree(&srv, 1410);
10542 }
10543
10544 #[test]
10545 fn a_23976_take_placed_on_a_lane_places_one_span() {
10546 let mut srv = open_30_with_23976();
10547 let r = ed(&mut srv, json!([{ "op": "place", "source": "src:1", "lane": "V1", "at": "47s" }]));
10548 assert!(!r.is_error, "{}", r.text);
10549 assert_take_spans_agree(&srv, 1410);
10550 }
10551
10552 #[test]
10553 fn a_25_fps_take_places_picture_and_sound_over_one_span() {
10554 engine::ao::set_silent_output();
10555 let mut sess = PlaybackSession::open(asset("test_av.mp4")).expect("open 30 fps asset");
10556 sess.import(&asset("test_25fps.mp4")).expect("import 25 fps asset");
10557 let mut srv = Server { session: Some(sess), ..Server::default() };
10558 let r = ed(&mut srv, json!([{ "op": "place", "source": "src:1", "at": "47s" }]));
10559 assert!(!r.is_error, "{}", r.text);
10560 assert_take_spans_agree(&srv, 1410);
10561 }
10562
10563 #[test]
10564 fn an_explicit_lanes_split_unlinks_every_half_in_both_reads() {
10565 let mut srv = linked_take();
10566 let r = ed(&mut srv, json!([{ "op": "split", "at": "2s", "lanes": ["V1"] }]));
10567 assert!(!r.is_error, "{}", r.text);
10568 assert!(r.text.contains("detached at the cut"), "{}", r.text);
10569 let right = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[1].start;
10570 assert_reads_agree(&mut srv, "V1@0", Lane::V1, 0);
10571 assert_reads_agree(&mut srv, &format!("V1@{right}"), Lane::V1, right);
10572 assert_reads_agree(&mut srv, "A1@0", Lane::A1, 0);
10573 }
10574
10575 #[test]
10576 fn undoing_a_lift_puts_the_link_back_in_both_reads() {
10577 let mut srv = linked_take();
10578 let r = ed(&mut srv, json!([{ "op": "lift", "clip": "V1@0" }]));
10579 assert!(!r.is_error, "{}", r.text);
10580 let back = read(&mut srv, "undo", json!({}));
10581 assert!(!back.is_error, "{}", back.text);
10582 assert_reads_agree(&mut srv, "V1@0", Lane::V1, 0);
10583 assert_reads_agree(&mut srv, "A1@0", Lane::A1, 0);
10584 }
10585
10586 #[test]
10587 fn lane_move_takes_a_number_for_to_through_the_batch() {
10588 let mut srv = linked_take();
10589 let added = ed(&mut srv, json!([{ "op": "lane_add", "kind": "video" }]));
10590 assert!(!added.is_error, "{}", added.text);
10591 let r = ed(&mut srv, json!([{ "op": "lane_move", "lane": "V2", "to": 1 }]));
10592 assert!(!r.is_error, "{}", r.text);
10593 assert!(r.text.contains("(position 1)"), "{}", r.text);
10594 assert_eq!(srv.session.as_ref().unwrap().lanes()[0].kind, LaneKind::Video);
10595 }
10596
10597 #[test]
10598 fn lane_move_shifts_name_each_clips_new_lane_label() {
10599 let mut srv = linked_take();
10600 assert!(!ed(&mut srv, json!([{ "op": "lane_add", "kind": "video" }])).is_error);
10601 // The empty V2 moves to position 1: the picture's lane takes the label V2 (its label is its position among video lanes).
10602 let r = ed(&mut srv, json!([{ "op": "lane_move", "lane": "V2", "to": 1 }]));
10603 assert!(!r.is_error, "{}", r.text);
10604 assert!(r.text.contains("shifted: V1@0→V2@0"), "{}", r.text);
10605 assert!(!r.text.contains("split"), "a lane move splits nothing: {}", r.text);
10606 }
10607
10608 #[test]
10609 fn lane_move_refuses_a_name_for_to_and_lists_the_lanes() {
10610 let mut srv = linked_take();
10611 let r = ed(&mut srv, json!([{ "op": "lane_move", "lane": "V1", "to": "V2" }]));
10612 assert!(r.is_error, "{}", r.text);
10613 assert!(r.text.contains("1-based position of the lane in the lane list"), "{}", r.text);
10614 assert!(r.text.contains("V1 (1), A1 (2)"), "the lane list is named: {}", r.text);
10615 }
10616
10617 /// A take of three lanes: V2 picture with sound on A2 and A3, all 2 s from 0.
10618 fn three_lane_take() -> Server {
10619 let mut srv = open();
10620 let r = ed(
10621 &mut srv,
10622 json!([
10623 { "op": "lane_add", "kind": "video" },
10624 { "op": "lane_add", "kind": "audio" },
10625 { "op": "lane_add", "kind": "audio" },
10626 { "op": "place", "source": 0, "at": "0s", "in": "0s", "out": "2s", "lane": "V2", "audio": false },
10627 { "op": "place", "source": 0, "at": "0s", "in": "0s", "out": "2s", "lane": "A2" },
10628 { "op": "place", "source": 0, "at": "0s", "in": "0s", "out": "2s", "lane": "A3" },
10629 { "op": "group", "clips": ["V2@0", "A2@0", "A3@0"] }
10630 ]),
10631 );
10632 assert!(!r.is_error, "{}", r.text);
10633 srv
10634 }
10635
10636 #[test]
10637 fn scope_clip_trim_leaves_the_partners_linked_to_each_other() {
10638 let mut srv = three_lane_take();
10639 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "V2@0", "edge": "out", "to": "1s", "scope": "clip" }]));
10640 assert!(!r.is_error, "{}", r.text);
10641 assert!(r.text.contains("2 partners stay linked to each other"), "{}", r.text);
10642 let s = srv.session.as_ref().unwrap();
10643 let (v, a2, a3) = (s.lane_clips(Lane::new(LaneKind::Video, 1))[0].link, s.lane_clips(Lane::new(LaneKind::Audio, 1))[0].link, s.lane_clips(Lane::new(LaneKind::Audio, 2))[0].link);
10644 assert!(v.is_some() && v != a2, "V2 left the take");
10645 assert!(a2.is_some() && a2 == a3, "A2 and A3 stay one take");
10646 assert_eq!(s.lane_clips(Lane::new(LaneKind::Audio, 1))[0].frames(), s.lane_clips(Lane::new(LaneKind::Audio, 2))[0].frames(), "the partners were not trimmed");
10647 }
10648
10649 #[test]
10650 fn scope_clip_trim_with_a_locked_partner_refuses_and_names_the_way_out() {
10651 let mut srv = three_lane_take();
10652 assert!(!ed(&mut srv, json!([{ "op": "lane_flags", "lane": "A3", "locked": true }])).is_error);
10653 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "V2@0", "edge": "out", "to": "1s", "scope": "clip" }]));
10654 assert!(r.is_error, "{}", r.text);
10655 assert!(r.text.contains("alone unlinks it from A3, which is locked; unlock A3 or use scope:\"group\""), "{}", r.text);
10656 let s = srv.session.as_ref().unwrap();
10657 assert_eq!(s.lane_clips(Lane::new(LaneKind::Video, 1))[0].frames(), (2.0 * parse::session_fps(s)).round() as u32, "nothing moved (the batch rolled back)");
10658 }
10659
10660 #[test]
10661 fn close_gaps_on_a_lane_with_no_gap_says_so() {
10662 let mut srv = linked_take();
10663 let r = ed(&mut srv, json!([{ "op": "close_gaps", "lane": "V1" }]));
10664 assert!(!r.is_error, "{}", r.text);
10665 assert!(r.text.contains("V1 has no gaps"), "{}", r.text);
10666 assert!(!r.text.contains("not a gap"), "{}", r.text);
10667 }
10668
10669 #[test]
10670 fn a_move_to_another_lane_is_not_reported_as_a_split() {
10671 let mut srv = open();
10672 let r = ed(
10673 &mut srv,
10674 json!([
10675 { "op": "lane_add", "kind": "video" },
10676 { "op": "place", "source": 0, "at": "0s", "in": "0s", "out": "2s", "lane": "V2", "audio": false },
10677 { "op": "lane_add", "kind": "video" },
10678 { "op": "move", "clip": "V2@0", "at": "5s", "to_lane": "V3" }
10679 ]),
10680 );
10681 assert!(!r.is_error, "{}", r.text);
10682 assert!(!r.text.contains("split"), "nothing was split: {}", r.text);
10683 }
10684
10685 #[test]
10686 fn ripple_delete_names_the_caption_cues_it_removes() {
10687 let mut srv = linked_take();
10688 let dir = TestDir::new("ripple-cues");
10689 let a = dir.path().join("a.srt");
10690 std::fs::write(&a, "1\n00:00:01,000 --> 00:00:02,000\nInside cue\n").unwrap();
10691 let r = ed(
10692 &mut srv,
10693 json!([
10694 { "op": "subtitles_import", "path": a.to_string_lossy() },
10695 { "op": "captions_place", "track": 0, "lane": "S1", "at": "0f" },
10696 { "op": "ripple_delete", "clip": "V1@0" }
10697 ]),
10698 );
10699 assert!(!r.is_error, "{}", r.text);
10700 assert!(r.text.contains("caption cue(s) removed: \"Inside cue\" (1.000s–2.000s)"), "{}", r.text);
10701 assert!(!r.text.contains("trimmed"), "a cue wholly inside the span is not trimmed: {}", r.text);
10702 assert!(srv.session.as_ref().unwrap().sub_lane_cues(Lane::S1).is_empty(), "the cue is gone");
10703 }
10704
10705 #[test]
10706 fn a_cut_that_only_trims_a_cue_says_trimmed_with_old_and_new_times() {
10707 let mut srv = linked_take();
10708 let dir = TestDir::new("cut-trims-cue");
10709 let a = dir.path().join("a.srt");
10710 std::fs::write(&a, "1\n00:00:01,000 --> 00:00:02,000\nStraddle\nline two\n").unwrap();
10711 let r = ed(
10712 &mut srv,
10713 json!([
10714 { "op": "subtitles_import", "path": a.to_string_lossy() },
10715 { "op": "captions_place", "track": 0, "lane": "S1", "at": "0f" },
10716 { "op": "remove_time", "at": "1.5s", "duration": "0.5s" }
10717 ]),
10718 );
10719 assert!(!r.is_error, "{}", r.text);
10720 assert!(!r.text.contains("removed"), "the cue keeps its first half, so nothing is removed: {}", r.text);
10721 assert!(
10722 r.text.contains("caption cue(s) trimmed: S1 cue 1 'Straddle / line two' → 'Straddle / line' (was 1.000s–2.000s, now 1.000s–1.500s)"),
10723 "{}",
10724 r.text
10725 );
10726 }
10727
10728 #[test]
10729 fn an_unknown_lane_is_not_a_lane_and_an_empty_one_has_no_clips() {
10730 let mut srv = linked_take();
10731 let r = ed(&mut srv, json!([{ "op": "delete", "clip": "V9@0" }]));
10732 assert!(r.is_error, "{}", r.text);
10733 assert!(r.text.contains("V9 is not a lane in this project; the lanes are V1, A1"), "{}", r.text);
10734 assert!(!r.text.contains("has no clips"), "{}", r.text);
10735 let r = ed(&mut srv, json!([{ "op": "lane_add", "kind": "video" }, { "op": "delete", "clip": "V2@0" }]));
10736 assert!(r.is_error, "{}", r.text);
10737 assert!(r.text.contains("V2 has no clips"), "{}", r.text);
10738 }
10739
10740 #[test]
10741 fn lane_move_names_every_lane_it_renamed_and_what_holds_it() {
10742 let mut srv = linked_take();
10743 // A locked lane does not move, so the batch is refused and nothing changes.
10744 let r = ed(
10745 &mut srv,
10746 json!([{ "op": "lane_add", "kind": "audio" }, { "op": "lane_flags", "lane": "A2", "locked": true }, { "op": "lane_move", "lane": "A2", "to": 2 }]),
10747 );
10748 assert!(r.is_error && r.text.contains("lane_move A2: lane A2 is locked"), "{}", r.text);
10749 assert_eq!(srv.session.as_ref().unwrap().lanes().len(), 2, "the refused batch added no lane");
10750 // The unlocked lane moves past the locked one: the locked lane is renamed by position, and says so.
10751 let r = ed(
10752 &mut srv,
10753 json!([{ "op": "lane_add", "kind": "audio" }, { "op": "lane_flags", "lane": "A2", "locked": true }, { "op": "lane_move", "lane": "A1", "to": 3 }]),
10754 );
10755 assert!(!r.is_error, "{}", r.text);
10756 assert!(
10757 r.text.contains("lanes renamed by position: A1 → A2 (test_av.mp4), A2 → A1 (locked)"),
10758 "{}",
10759 r.text
10760 );
10761 assert!(r.text.contains("use the new names from now on"), "{}", r.text);
10762 }
10763
10764 #[test]
10765 fn a_copy_look_onto_a_target_that_already_has_it_says_nothing_to_copy() {
10766 let mut srv = linked_take();
10767 let r = ed(
10768 &mut srv,
10769 json!([
10770 { "op": "lane_add", "kind": "video" },
10771 { "op": "place", "source": 0, "lane": "V2", "at": "300f", "in": "0s", "out": "2s", "audio": false },
10772 { "op": "color", "clip": "V1@0", "brightness": 0.2 }
10773 ]),
10774 );
10775 assert!(!r.is_error, "{}", r.text);
10776 let r = ed(&mut srv, json!([{ "op": "copy_look", "from": "V1@0", "to": ["V2@300"] }]));
10777 assert!(!r.is_error && !r.text.contains("no change"), "a real copy is not a no-change: {}", r.text);
10778 let r = ed(&mut srv, json!([{ "op": "copy_look", "from": "V1@0", "to": ["V2@300"] }]));
10779 assert!(r.text.starts_with("no change: V2@300 already has V1@0's color: nothing to copy"), "{}", r.text);
10780 assert!(!r.text.contains("copied"), "{}", r.text);
10781 }
10782
10783 #[test]
10784 fn keep_names_the_frame_snapped_span_it_placed() {
10785 let mut srv = open();
10786 let r = ed(
10787 &mut srv,
10788 json!([
10789 { "op": "lane_add", "kind": "video" },
10790 { "op": "keep", "source": 0, "ranges": [["1.2345s", "2.5"]], "lane": "V2", "at": "0s", "audio": false }
10791 ]),
10792 );
10793 assert!(!r.is_error, "{}", r.text);
10794 assert!(r.text.contains("src 1.233s–2.500s"), "{}", r.text);
10795 }
10796
10797 #[test]
10798 fn a_dip_past_one_clip_names_the_clips_that_cover_the_span() {
10799 let mut srv = open();
10800 let r = ed(
10801 &mut srv,
10802 json!([
10803 { "op": "lane_add", "kind": "audio" },
10804 { "op": "place", "source": 0, "lane": "A2", "at": "0s", "in": "0s", "out": "1s" },
10805 { "op": "place", "source": 0, "lane": "A2", "at": "1s", "in": "2s", "out": "3s" },
10806 { "op": "gain_dip", "clip": "A2@0", "from": "0.5s", "to": "2.5s", "db": -6 }
10807 ]),
10808 );
10809 assert!(r.is_error, "{}", r.text);
10810 assert!(r.text.contains("the span 0.5s–2.5s covers A2@0…A2@30: dip each, or use lane gain keys"), "{}", r.text);
10811 }
10812
10813 #[test]
10814 fn a_dip_at_the_clip_start_says_there_is_no_ramp_in() {
10815 let mut srv = open();
10816 let r = ed(
10817 &mut srv,
10818 json!([
10819 { "op": "lane_add", "kind": "audio" },
10820 { "op": "place", "source": 0, "lane": "A2", "at": "0s", "in": "0s", "out": "2s" },
10821 { "op": "gain_dip", "clip": "A2@0", "from": "0s", "to": "1s", "db": -6, "ramp": "0.5s" }
10822 ]),
10823 );
10824 assert!(!r.is_error, "{}", r.text);
10825 assert!(
10826 r.text.contains("no ramp in: the dip starts at the clip's start, so there is no fade down into it; start it later than "),
10827 "{}",
10828 r.text
10829 );
10830 assert!(r.text.contains("for a ramp"), "{}", r.text);
10831 assert!(!r.text.contains("shortened from"), "{}", r.text);
10832 }
10833
10834 #[test]
10835 fn lane_remove_names_the_clips_it_refuses_by_address_and_file() {
10836 let mut srv = linked_take();
10837 let r = ed(&mut srv, json!([{ "op": "lane_remove", "lane": "A1" }]));
10838 assert!(r.is_error, "{}", r.text);
10839 assert!(r.text.contains("A1 still holds 1 clip(s): A1@0 (test_av.mp4)"), "{}", r.text);
10840 assert!(!r.text.contains("/home/"), "paths are shortened to file names: {}", r.text);
10841 }
10842
10843 #[test]
10844 fn undo_and_redo_with_nothing_to_take_say_nothing_to_undo() {
10845 let mut srv = open();
10846 let r = run_undo(&mut srv, &json!({}));
10847 assert!(r.is_error && r.text.starts_with("nothing to undo yet; checkpoints survive"), "{}", r.text);
10848 assert!(!r.text.contains("project_open"), "a new project never opened from a file: {}", r.text);
10849 // A project opened from a file with no edits lost no history, so no reopen is blamed for it.
10850 srv.saved_depth = Some(0);
10851 let r = run_undo(&mut srv, &json!({}));
10852 assert!(r.is_error && r.text.starts_with("nothing to undo yet; checkpoints survive"), "{}", r.text);
10853 assert!(!r.text.contains("project_open"), "{}", r.text);
10854 let r = run_redo(&mut srv, &json!({}));
10855 assert!(r.is_error && r.text.starts_with("nothing to redo ("), "{}", r.text);
10856 }
10857
10858 #[test]
10859 fn swap_trades_two_clips_on_one_lane_and_lists_the_moves() {
10860 let mut srv = open();
10861 let fps = parse::session_fps(srv.session.as_ref().unwrap());
10862 // Two picture-only clips on V1, 2 s at 20 s and 3 s at 25 s, with a gap between.
10863 let p1 = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "20s", "in": "0s", "out": "2s", "lane": "V1", "audio": false }]));
10864 assert!(!p1.is_error, "{}", p1.text);
10865 let p2 = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "25s", "in": "0s", "out": "3s", "lane": "V1", "audio": false }]));
10866 assert!(!p2.is_error, "{}", p2.text);
10867 let (a, b) = ((20.0 * fps).round() as u32, (25.0 * fps).round() as u32);
10868 let r = ed(&mut srv, json!([{ "op": "swap", "a": format!("V1@{a}f"), "b": format!("V1@{b}f") }]));
10869 assert!(!r.is_error, "{}", r.text);
10870 assert!(r.text.contains("now at"), "{}", r.text);
10871 assert!(r.text.contains("moved"), "the moves are listed: {}", r.text);
10872 let v1 = srv.session.as_ref().unwrap().lane_clips(Lane::V1).to_vec();
10873 let mine: Vec<(u32, u32)> = v1.iter().filter(|c| c.start >= a).map(|c| (c.start, c.frames())).collect();
10874 // The 3 s clip now starts at 20 s; the 2 s clip lands where the 3 s one ended less 2 s.
10875 assert_eq!(mine, vec![(a, (3.0 * fps).round() as u32), (b + (fps).round() as u32, (2.0 * fps).round() as u32)]);
10876 // One undo puts both back.
10877 assert!(srv.session.as_mut().unwrap().undo());
10878 let back: Vec<u32> = srv.session.as_ref().unwrap().lane_clips(Lane::V1).iter().filter(|c| c.start >= a).map(|c| c.start).collect();
10879 assert_eq!(back, vec![a, b]);
10880 // A clip in a take is not swapped apart (V1@0 is linked to A1).
10881 let refused = ed(&mut srv, json!([{ "op": "swap", "a": "V1@0", "b": format!("V1@{a}f") }]));
10882 assert!(refused.is_error && refused.text.contains("refused"), "{}", refused.text);
10883 }
10884
10885 /// A placement on one lane names only the clips on that lane: a clip on another lane that the
10886 /// span merely overlaps stays intact and is not in the reply.
10887 #[test]
10888 fn overwrite_reply_names_only_the_lane_the_placement_landed_on() {
10889 let mut srv = open_asset("test_25fps.mp4");
10890 srv.session.as_mut().unwrap().import(&asset("test_tone.wav")).expect("import tone");
10891 // The opened asset is already on V1 and A1 at 0 (a take), so only A2 is added to.
10892 let r = ed(&mut srv, json!([{ "op": "lane_add", "kind": "audio" }]));
10893 assert!(!r.is_error, "{}", r.text);
10894 let r = ed(&mut srv, json!([{ "op": "place", "source": 1, "lane": "A2", "at": "0s" }]));
10895 assert!(!r.is_error, "{}", r.text);
10896 assert!(!r.text.contains("V1@") && !r.text.contains("A1@"), "other lanes are not named: {}", r.text);
10897 assert!(!r.text.contains("overwrote") && !r.text.contains("removed"), "nothing was overwritten: {}", r.text);
10898 // A second tone on A2 at the same start does overwrite what A2 holds, and A2 is what is named.
10899 let r = ed(&mut srv, json!([{ "op": "place", "source": 1, "lane": "A2", "at": "0s", "overwrite": true }]));
10900 assert!(!r.is_error, "{}", r.text);
10901 assert!(r.text.contains("overwrote A2@0"), "{}", r.text);
10902 assert!(!r.text.contains("V1@") && !r.text.contains("A1@"), "{}", r.text);
10903 assert!(srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].frames() > 0, "V1 is intact");
10904 }
10905
10906 /// An audio-only mp4 has no picture, whatever its extension says: a laneless place puts its
10907 /// sound on A1 alone, and a video lane request is refused as having no picture.
10908 #[test]
10909 fn audio_only_mp4_places_sound_alone_and_refuses_a_video_lane() {
10910 let mut srv = open_asset("test_av.mp4");
10911 srv.session.as_mut().unwrap().import(&asset("test_audio_only.mp4")).expect("import audio-only");
10912 let r = ed(&mut srv, json!([{ "op": "place", "source": 1, "at": "end" }]));
10913 assert!(!r.is_error, "{}", r.text);
10914 assert!(r.text.contains("A1@"), "the sound lands on A1: {}", r.text);
10915 assert!(!r.text.contains("V1@"), "no picture clip is made: {}", r.text);
10916 let s = srv.session.as_ref().unwrap();
10917 assert!(s.lane_clips(Lane::V1).iter().all(|c| c.source != 1), "no video clip for the audio-only source");
10918 let r = ed(&mut srv, json!([{ "op": "place", "source": 1, "lane": "V1", "at": "end" }]));
10919 assert!(r.is_error && r.text.contains("has no picture"), "{}", r.text);
10920 }
10921
10922 /// A clip whose link no other clip shares (what ungroup leaves) is not in a take, so it swaps.
10923 #[test]
10924 fn a_detached_clip_swaps_after_ungroup() {
10925 let mut srv = open_asset("test_av.mp4");
10926 let r = ed(&mut srv, json!([{ "op": "ungroup", "clip": "V1@0" }]));
10927 assert!(!r.is_error, "{}", r.text);
10928 let fps = parse::session_fps(srv.session.as_ref().unwrap());
10929 let at = (20.0 * fps).round() as u32;
10930 let p = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "20s", "in": "0s", "out": "2s", "lane": "V1", "audio": false }]));
10931 assert!(!p.is_error, "{}", p.text);
10932 let r = ed(&mut srv, json!([{ "op": "swap", "a": "V1@0", "b": format!("V1@{at}f") }]));
10933 assert!(!r.is_error, "a detached clip is not in a take: {}", r.text);
10934 assert!(!r.text.contains("in a take"), "{}", r.text);
10935 }
10936
10937 /// `swap ripple:false` between a 4 s clip and a 1 s clip with a 1 s clip between them: the
10938 /// long clip's new slot is where the short one stood, so it fits only once the short one has
10939 /// left. The swap succeeds, moves nothing else, and one undo restores both.
10940 #[test]
10941 fn swap_without_ripple_fits_when_checked_on_the_final_positions() {
10942 let mut srv = open();
10943 let fps = parse::session_fps(srv.session.as_ref().unwrap());
10944 let f = |sec: f64| (sec * fps).round() as u32;
10945 // Past the asset's own clip at 0s, so only these three are on the lane from 20s on.
10946 let place = |srv: &mut Server, at: &str, len: &str| {
10947 let p = ed(srv, json!([{ "op": "place", "source": 0, "at": at, "in": "0s", "length": len, "lane": "V1", "audio": false }]));
10948 assert!(!p.is_error, "{}", p.text);
10949 };
10950 place(&mut srv, "20s", "4s");
10951 place(&mut srv, "24s", "1s");
10952 place(&mut srv, "25s", "1s");
10953 let lane_from = |srv: &Server| -> Vec<(u32, u32)> {
10954 srv.session.as_ref().unwrap().lane_clips(Lane::V1).iter().filter(|c| c.start >= f(20.0)).map(|c| (c.start, c.frames())).collect()
10955 };
10956 let before = lane_from(&srv);
10957 // The 4 s clip would land on 25..29 s, where the 1 s clip stands until it has moved.
10958 let r = ed(&mut srv, json!([{ "op": "swap", "a": format!("V1@{}f", f(20.0)), "b": format!("V1@{}f", f(25.0)), "ripple": false }]));
10959 assert!(!r.is_error, "{}", r.text);
10960 assert!(r.text.contains("first now at 25.0s, second now at 20.0s"), "{}", r.text);
10961 // The 4 s clip now sits at 25 s, the 1 s clip at 20 s, and the middle clip has not moved.
10962 assert_eq!(lane_from(&srv), vec![(f(20.0), f(1.0)), (f(24.0), f(1.0)), (f(25.0), f(4.0))]);
10963 assert_ne!(before, lane_from(&srv));
10964 assert!(srv.session.as_mut().unwrap().undo());
10965 assert_eq!(lane_from(&srv), before, "one undo restores the lane");
10966 }
10967
10968 #[test]
10969 fn place_length_sets_the_out_point_from_in() {
10970 let mut srv = open();
10971 let fps = parse::session_fps(srv.session.as_ref().unwrap());
10972 // 1 s into the 5 s asset, 2 s long, placed well past the existing clip.
10973 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "20s", "in": "1s", "length": "2s" }]));
10974 assert!(!r.is_error, "{}", r.text);
10975 let last = srv.session.as_ref().unwrap().lane_clips(Lane::V1).last().unwrap().clone();
10976 assert_eq!(last.frames(), (2.0 * fps).round() as u32, "two seconds on the timeline");
10977 assert_eq!(last.in_frame, (1.0 * fps).round() as u32, "the in point is kept");
10978 }
10979
10980 #[test]
10981 fn append_length_lays_one_copy_of_that_length() {
10982 let mut srv = open();
10983 let fps = parse::session_fps(srv.session.as_ref().unwrap());
10984 let before = srv.session.as_ref().unwrap().lane_clips(Lane::V1).len();
10985 let r = ed(&mut srv, json!([{ "op": "append", "source": 0, "length": "1s" }]));
10986 assert!(!r.is_error, "{}", r.text);
10987 let v1 = srv.session.as_ref().unwrap().lane_clips(Lane::V1);
10988 assert_eq!(v1.len(), before + 1, "{}", r.text);
10989 assert_eq!(v1.last().unwrap().frames(), (1.0 * fps).round() as u32);
10990 }
10991
10992 #[test]
10993 fn place_length_refuses_past_the_source_end_and_with_out() {
10994 let mut srv = open();
10995 // The 5 s asset: 4 s in plus 2 s runs past its end.
10996 let past = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "20s", "in": "4s", "length": "2s" }]));
10997 assert!(past.is_error, "{}", past.text);
10998 assert!(past.text.contains("runs past the source end"), "{}", past.text);
10999 let both = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "20s", "out": "2s", "length": "1s" }]));
11000 assert!(both.is_error && both.text.contains("give out or length, not both"), "{}", both.text);
11001 let loop_len = ed(&mut srv, json!([{ "op": "append", "source": 0, "until": "9s", "length": "1s" }]));
11002 assert!(loop_len.is_error && loop_len.text.contains("do not combine"), "{}", loop_len.text);
11003 }
11004
11005 #[test]
11006 fn dissolve_crossfades_the_linked_sound() {
11007 let mut srv = linked_take();
11008 let len = first_len(&srv);
11009 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": format!("{len}f") }]));
11010 assert!(!r.is_error, "{}", r.text);
11011 let d = ed(&mut srv, json!([{ "op": "dissolve", "clip": "V1@0", "frames": 12 }]));
11012 assert!(!d.is_error, "{}", d.text);
11013 assert!(d.text.contains("sound crossfaded A1@0 12f"), "{}", d.text);
11014 assert!(srv.session.as_ref().unwrap().fade_out_of(Lane::A1, 0) > 0);
11015 }
11016
11017 #[test]
11018 fn dissolve_reply_says_the_overlap_and_the_length() {
11019 let mut srv = open();
11020 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s", "audio": false, "overwrite": true }]));
11021 assert!(!r.is_error, "{}", r.text);
11022 let len = first_len(&srv);
11023 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": format!("{len}f"), "audio": false, "overwrite": true }]));
11024 assert!(!r.is_error, "{}", r.text);
11025 let d = ed(&mut srv, json!([{ "op": "dissolve", "clip": "V1@0", "frames": 12 }]));
11026 assert!(!d.is_error, "{}", d.text);
11027 assert!(d.text.contains(&format!("V1@{len} blends in over the tail of V1@0")), "{}", d.text);
11028 assert!(d.text.contains("timeline length unchanged"), "{}", d.text);
11029 }
11030
11031 #[test]
11032 fn transition_sets_a_kind_with_a_direction_and_undoes() {
11033 let mut srv = open();
11034 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s", "audio": false, "overwrite": true }]));
11035 assert!(!r.is_error, "{}", r.text);
11036 let len = first_len(&srv);
11037 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": format!("{len}f"), "audio": false, "overwrite": true }]));
11038 assert!(!r.is_error, "{}", r.text);
11039 let t = ed(&mut srv, json!([{ "op": "transition", "clip": "V1@0", "kind": "push", "direction": "up", "length": "1s" }]));
11040 assert!(!t.is_error, "{}", t.text);
11041 assert!(t.text.contains("push-up V1@0→V1@"), "{}", t.text);
11042 let k = |srv: &Server| srv.session.as_ref().unwrap().transition_kind_of(Lane::V1, 0);
11043 assert_eq!(k(&srv), TransitionKind::Push(Dir::Up));
11044 let frames = srv.session.as_ref().unwrap().transition_out_of(Lane::V1, 0);
11045 assert_eq!(frames, 30, "1s at 30 fps");
11046 // Omitted length keeps the overlap; the full name is a kind too; a dissolve op resets the look.
11047 let t = ed(&mut srv, json!([{ "op": "transition", "clip": "V1@0", "kind": "wipe-right" }]));
11048 assert!(!t.is_error, "{}", t.text);
11049 assert_eq!(k(&srv), TransitionKind::Wipe(Dir::Right));
11050 assert_eq!(srv.session.as_ref().unwrap().transition_out_of(Lane::V1, 0), frames);
11051 let t = ed(&mut srv, json!([{ "op": "transition", "clip": "V1@0", "kind": "dip-black" }]));
11052 assert!(!t.is_error, "{}", t.text);
11053 assert_eq!(k(&srv), TransitionKind::DipBlack);
11054 for bad in [
11055 json!({ "op": "transition", "clip": "V1@0", "kind": "zoom", "direction": "left" }),
11056 json!({ "op": "transition", "clip": "V1@0", "kind": "spin" }),
11057 json!({ "op": "transition", "clip": "V1@0", "kind": "wipe", "direction": "sideways" }),
11058 ] {
11059 let r = ed(&mut srv, json!([bad]));
11060 assert!(r.is_error, "{}", r.text);
11061 }
11062 assert_eq!(k(&srv), TransitionKind::DipBlack, "refusals change nothing");
11063 let d = ed(&mut srv, json!([{ "op": "dissolve", "clip": "V1@0", "frames": 12 }]));
11064 assert!(!d.is_error, "{}", d.text);
11065 assert_eq!(k(&srv), TransitionKind::Dissolve);
11066 assert!(srv.session.as_mut().unwrap().undo());
11067 assert_eq!(k(&srv), TransitionKind::DipBlack);
11068 }
11069
11070 #[test]
11071 fn dissolve_names_a_gap_and_a_missing_next_clip() {
11072 let mut srv = open();
11073 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s", "audio": false, "overwrite": true }]));
11074 assert!(!r.is_error, "{}", r.text);
11075 let len = first_len(&srv);
11076 let last = ed(&mut srv, json!([{ "op": "dissolve", "clip": "V1@0", "frames": 12 }]));
11077 assert!(last.is_error && last.text.contains("last clip on V1"), "{}", last.text);
11078 let far = len + 30;
11079 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": format!("{far}f"), "audio": false }]));
11080 assert!(!r.is_error, "{}", r.text);
11081 let gap = ed(&mut srv, json!([{ "op": "dissolve", "clip": "V1@0", "frames": 12 }]));
11082 assert!(gap.is_error && gap.text.contains("a gap of 30f lies between V1@0"), "{}", gap.text);
11083 assert!(srv.session.as_ref().unwrap().transition_out_of(Lane::V1, 0) == 0, "refusal changes nothing");
11084 }
11085
11086 #[test]
11087 fn dissolve_on_an_audio_lane_points_at_crossfade() {
11088 let mut srv = linked_take();
11089 let d = ed(&mut srv, json!([{ "op": "dissolve", "clip": "A1@0", "frames": 12 }]));
11090 assert!(d.is_error && d.text.contains("use crossfade"), "{}", d.text);
11091 }
11092
11093 #[test]
11094 fn append_audio_false_is_picture_only() {
11095 let mut srv = open();
11096 let (v, a) = (clip_count(&srv, Lane::V1), clip_count(&srv, Lane::A1));
11097 let r = ed(&mut srv, json!([{ "op": "append", "source": 0, "audio": false }]));
11098 assert!(!r.is_error, "{}", r.text);
11099 assert_eq!(clip_count(&srv, Lane::V1), v + 1, "picture appended on V1");
11100 assert_eq!(clip_count(&srv, Lane::A1), a, "no sound appended");
11101 }
11102
11103 #[test]
11104 fn append_pairs_sound_by_default_and_audio_true_is_the_same() {
11105 let mut srv = open();
11106 let (v, a) = (clip_count(&srv, Lane::V1), clip_count(&srv, Lane::A1));
11107 let r = ed(&mut srv, json!([{ "op": "append", "source": 0, "audio": true }]));
11108 assert!(!r.is_error, "{}", r.text);
11109 assert_eq!(clip_count(&srv, Lane::V1), v + 1);
11110 assert_eq!(clip_count(&srv, Lane::A1), a + 1, "sound paired");
11111 }
11112
11113 fn clip_count(srv: &Server, lane: Lane) -> usize {
11114 srv.session.as_ref().unwrap().lane_clips(lane).len()
11115 }
11116
11117 #[test]
11118 fn move_with_to_names_the_right_argument() {
11119 let mut srv = linked_take();
11120 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@0", "to": "-10s" }]));
11121 assert!(r.is_error && r.text.contains("missing `at` (move takes `at`, not `to`)"), "{}", r.text);
11122 }
11123
11124 #[test]
11125 fn undo_steps_must_be_a_whole_number_in_words() {
11126 let mut srv = open();
11127 let u = run_undo(&mut srv, &json!({ "steps": 1.5 }));
11128 assert!(u.is_error && u.text.contains("a whole number of at least 1, not 1.5"), "{}", u.text);
11129 }
11130
11131 #[test]
11132 fn undo_steps_fraction_is_refused_by_the_argument_check() {
11133 let t = tools().into_iter().find(|t| t.name == "undo").expect("undo tool");
11134 let err = crate::rpc::check_args(&t, &json!({ "steps": 1.5 })).expect_err("refused");
11135 assert_eq!(err, "argument `steps` for undo must be an integer, got 1.5; for example 1: Batches to take back or redo (default 1).");
11136 }
11137
11138 #[test]
11139 fn speed_out_of_range_echoes_a_short_number() {
11140 let mut srv = linked_take();
11141 let r = ed(&mut srv, json!([{ "op": "speed", "clip": "V1@0", "x": 1e300 }]));
11142 assert!(r.is_error && r.text.contains("speed 1e300 is outside"), "{}", r.text);
11143 }
11144
11145 #[test]
11146 fn every_op_in_the_dispatcher_has_a_key_list() {
11147 for name in OWN_OPS.iter().chain(FX_OPS).chain(SUB_OPS) {
11148 assert!(accepted_keys(name).is_some(), "{name} has no accepted-key list");
11149 }
11150 }
11151
11152 #[test]
11153 fn an_unknown_key_is_refused_by_name_with_the_keys_the_op_takes() {
11154 let mut srv = empty_with_av();
11155 let depth = srv.session.as_ref().unwrap().undo_depth();
11156 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "0s", "clipp": "x" }]));
11157 assert!(r.is_error, "{}", r.text);
11158 assert!(
11159 r.text.contains("unknown key `clipp`; place takes source, lane, at, in, out, length, stretch, audio, audio_lane, overwrite"),
11160 "{}",
11161 r.text
11162 );
11163 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth, "a refused batch changes nothing");
11164 }
11165
11166 #[test]
11167 fn an_unknown_key_suggests_the_close_name() {
11168 let mut srv = linked_take();
11169 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "V1@0", "edge": "out", "tos": "1s" }]));
11170 assert!(r.is_error && r.text.contains("(did you mean `to`?)"), "{}", r.text);
11171 }
11172
11173 #[test]
11174 fn a_guessed_key_still_gets_the_missing_argument_hint() {
11175 let mut srv = linked_take();
11176 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@0", "to": "-10s" }]));
11177 assert!(r.is_error && r.text.contains("missing `at` (move takes `at`, not `to`)"), "{}", r.text);
11178 }
11179
11180 #[test]
11181 fn an_occupied_explicit_video_lane_refuses_and_overwrite_lists_what_it_replaced() {
11182 let mut srv = open();
11183 let before = snapshot(&srv);
11184 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s", "audio": false }]));
11185 assert!(r.is_error, "{}", r.text);
11186 assert!(r.text.contains("would overwrite V1@0") && r.text.contains("overwrite:true"), "{}", r.text);
11187 assert_eq!(snapshot(&srv), before, "a refused placement changes nothing");
11188 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s", "audio": false, "overwrite": true }]));
11189 assert!(!r.is_error, "{}", r.text);
11190 assert!(r.text.contains("overwrote V1@0"), "{}", r.text);
11191 }
11192
11193 #[test]
11194 fn an_occupied_explicit_audio_lane_refuses_and_names_the_clip() {
11195 let mut srv = open();
11196 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "A1", "at": "0s" }]));
11197 assert!(r.is_error && r.text.contains("would overwrite A1@0"), "{}", r.text);
11198 }
11199
11200 #[test]
11201 fn append_with_no_at_starts_at_the_end_of_v1_not_the_timeline() {
11202 let mut srv = empty_with_av();
11203 assert!(!ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "A1", "at": "0s" }])).is_error);
11204 // V1 is empty, A1 runs to the end: the picture alone starts at 0 on V1.
11205 let r = ed(&mut srv, json!([{ "op": "append", "source": 0, "audio": false }]));
11206 assert!(!r.is_error, "{}", r.text);
11207 assert_eq!(srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].start, 0, "{}", r.text);
11208 }
11209
11210 #[test]
11211 fn append_refuses_a_busy_sound_lane_and_suggests_audio_false() {
11212 let mut srv = empty_with_av();
11213 assert!(!ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "A1", "at": "0s" }])).is_error);
11214 let r = ed(&mut srv, json!([{ "op": "append", "source": 0 }]));
11215 assert!(r.is_error && r.text.contains("would overlap A1@0"), "{}", r.text);
11216 assert!(r.text.contains("audio:false"), "{}", r.text);
11217 assert!(srv.session.as_ref().unwrap().lane_clips(Lane::V1).is_empty(), "a refused append changes nothing");
11218 }
11219
11220 #[test]
11221 fn ripple_delete_lists_the_shifted_clips_old_to_new() {
11222 let mut srv = open();
11223 let half = first_len(&srv) / 2;
11224 assert!(!ed(&mut srv, json!([{ "op": "split", "at": format!("{half}f") }])).is_error);
11225 let r = ed(&mut srv, json!([{ "op": "ripple_delete", "clip": "V1@0" }]));
11226 assert!(!r.is_error, "{}", r.text);
11227 let want = format!("shifted: V1@{half}→V1@0, A1@{half}→A1@0");
11228 assert!(r.text.contains(&want), "{}", r.text);
11229 }
11230
11231 #[test]
11232 fn delete_of_a_detached_sound_refuses_when_the_ripple_would_take_the_picture_under_it() {
11233 // Two takes cut from the same source range. The first sound is detached, so its picture
11234 // V1@0 belongs to no take; the later take's picture V1@len would move onto it. The cut
11235 // would remove V1@0, so the delete refuses and changes nothing.
11236 let mut srv = empty_with_av();
11237 assert!(!ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s" }, { "op": "append", "source": 0 }])).is_error);
11238 assert!(!ed(&mut srv, json!([{ "op": "ungroup", "clip": "A1@0" }])).is_error);
11239 let before = snapshot(&srv);
11240 let len = first_len(&srv);
11241 let r = ed(&mut srv, json!([{ "op": "delete", "clip": "A1@0" }]));
11242 assert!(r.is_error, "{}", r.text);
11243 assert!(r.text.contains("refused"), "{}", r.text);
11244 assert!(r.text.contains("V1@0"), "{}", r.text);
11245 assert!(r.text.contains("lift A1@0"), "{}", r.text);
11246 assert!(r.text.contains("close_gaps {lane:\"V1\"}"), "{}", r.text);
11247 assert_eq!(snapshot(&srv), before, "a refused delete changes nothing");
11248 assert_eq!(srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].start, 0);
11249 assert_eq!(srv.session.as_ref().unwrap().lane_clips(Lane::V1)[1].start, len);
11250 }
11251
11252 #[test]
11253 fn ripple_delete_of_a_detached_sound_refuses_the_same_overwrite() {
11254 let mut srv = empty_with_av();
11255 assert!(!ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s" }, { "op": "append", "source": 0 }])).is_error);
11256 assert!(!ed(&mut srv, json!([{ "op": "ungroup", "clip": "A1@0" }])).is_error);
11257 let before = snapshot(&srv);
11258 let r = ed(&mut srv, json!([{ "op": "ripple_delete", "clip": "A1@0" }]));
11259 assert!(r.is_error, "{}", r.text);
11260 assert!(r.text.contains("ripple_delete A1@0 refused"), "{}", r.text);
11261 assert_eq!(snapshot(&srv), before);
11262 }
11263
11264 #[test]
11265 fn lift_both_then_close_gaps_is_the_way_out_of_the_refusal() {
11266 // The refusal's own recipe: lift the sound and the picture in its way, then close the gap.
11267 // The later take rides along when its lane is empty over the stretch, so the take stays whole.
11268 let mut srv = empty_with_av();
11269 assert!(!ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s" }, { "op": "append", "source": 0 }])).is_error);
11270 assert!(!ed(&mut srv, json!([{ "op": "ungroup", "clip": "A1@0" }])).is_error);
11271 let len = first_len(&srv);
11272 let r = ed(
11273 &mut srv,
11274 json!([
11275 { "op": "lift", "clip": "A1@0" },
11276 { "op": "lift", "clip": "V1@0" },
11277 { "op": "close_gaps", "lane": "V1" },
11278 { "op": "close_gaps", "lane": "A1" }
11279 ]),
11280 );
11281 assert!(!r.is_error, "{}", r.text);
11282 let s = srv.session.as_ref().unwrap();
11283 assert_eq!(s.lane_clips(Lane::V1).len(), 1, "{}", r.text);
11284 assert_eq!(s.lane_clips(Lane::V1)[0].start, 0, "{}", r.text);
11285 assert_eq!(s.lane_clips(Lane::A1)[0].start, 0, "{}", r.text);
11286 assert_eq!(s.lane_clips(Lane::V1)[0].frames(), len);
11287 }
11288
11289 /// Two takes cut from the same source, the first one's sound detached: V1@0 is a picture that
11290 /// belongs to no take, A1@0 the sound beside it; the later take V1@len + A1@len stays whole.
11291 fn detached_pair_then_take() -> (Server, u32) {
11292 let mut srv = empty_with_av();
11293 assert!(!ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s" }, { "op": "append", "source": 0 }])).is_error);
11294 assert!(!ed(&mut srv, json!([{ "op": "ungroup", "clip": "A1@0" }])).is_error);
11295 let len = first_len(&srv);
11296 (srv, len)
11297 }
11298
11299 #[test]
11300 fn move_insert_of_a_detached_sound_refuses_when_its_slot_would_take_the_picture_under_it() {
11301 // The insert moves the later take up into the slot the sound leaves, and the slot cut would
11302 // take V1@0 with it: refuse before anything moves.
11303 let (mut srv, len) = detached_pair_then_take();
11304 let before = snapshot(&srv);
11305 let r = ed(&mut srv, json!([{ "op": "move", "clip": "A1@0", "at": format!("{len}f"), "to_lane": "A1", "insert": true }]));
11306 assert!(r.is_error, "{}", r.text);
11307 assert!(r.text.contains("move A1@0 insert to A1@"), "{}", r.text);
11308 assert!(r.text.contains("refused: the ripple would close over V1@0"), "{}", r.text);
11309 assert!(r.text.contains("move A1@0 without insert to leave the gap instead"), "{}", r.text);
11310 assert!(r.text.contains("close_gaps {lane:\"V1\"}"), "{}", r.text);
11311 assert_eq!(snapshot(&srv), before, "a refused move changes nothing");
11312 }
11313
11314 #[test]
11315 fn move_insert_of_a_detached_picture_refuses_when_its_slot_would_take_the_sound_under_it() {
11316 // The mirror: the picture leaves its slot, and the cut would take A1@0 under it.
11317 let (mut srv, len) = detached_pair_then_take();
11318 let before = snapshot(&srv);
11319 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@0", "at": format!("{len}f"), "insert": true }]));
11320 assert!(r.is_error, "{}", r.text);
11321 assert!(r.text.contains("refused: the ripple would close over A1@0"), "{}", r.text);
11322 assert!(r.text.contains("close_gaps {lane:\"A1\"}"), "{}", r.text);
11323 assert_eq!(snapshot(&srv), before, "a refused move changes nothing");
11324 }
11325
11326 #[test]
11327 fn move_without_insert_moves_the_detached_sound_the_refusal_names() {
11328 // The refusal's first way out: the slide leaves the gap and ripples nothing, so the picture stays.
11329 let (mut srv, len) = detached_pair_then_take();
11330 let r = ed(&mut srv, json!([{ "op": "move", "clip": "A1@0", "at": format!("{}f", 2 * len) }]));
11331 assert!(!r.is_error, "{}", r.text);
11332 let s = srv.session.as_ref().unwrap();
11333 assert_eq!(s.lane_clips(Lane::V1)[0].start, 0, "{}", r.text);
11334 assert_eq!(s.lane_clips(Lane::V1).len(), 2, "{}", r.text);
11335 }
11336
11337 #[test]
11338 fn ripple_delete_of_the_later_take_shifts_nothing() {
11339 // The later of two identical takes goes: the earlier one stays where it is, so nothing moves.
11340 let mut srv = empty_with_av();
11341 assert!(!ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s" }, { "op": "append", "source": 0 }])).is_error);
11342 let len = first_len(&srv);
11343 let r = ed(&mut srv, json!([{ "op": "ripple_delete", "clip": format!("V1@{len}") }]));
11344 assert!(!r.is_error, "{}", r.text);
11345 assert!(!r.text.contains("shifted:"), "{}", r.text);
11346 assert_eq!(srv.session.as_ref().unwrap().lane_clips(Lane::V1).len(), 1, "{}", r.text);
11347 }
11348
11349 #[test]
11350 fn remove_time_lists_both_lanes_when_takes_share_a_source_range() {
11351 let mut srv = empty_with_av();
11352 assert!(!ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s" }, { "op": "append", "source": 0 }])).is_error);
11353 let len = first_len(&srv);
11354 let r = ed(&mut srv, json!([{ "op": "remove_time", "at": "0f", "duration": format!("{len}f") }]));
11355 assert!(!r.is_error, "{}", r.text);
11356 let want = format!("shifted: V1@{len}→V1@0, A1@{len}→A1@0");
11357 assert!(r.text.contains(&want), "{}", r.text);
11358 }
11359
11360 #[test]
11361 fn shifted_lists_cap_at_twenty_and_count_the_rest() {
11362 let mut srv = open();
11363 let len = first_len(&srv);
11364 let cuts: Vec<Value> = (1..=12).map(|i| i * 10).filter(|&f| f < len).map(|f| json!({ "op": "split", "at": format!("{f}f") })).collect();
11365 assert!(!ed(&mut srv, Value::Array(cuts.clone())).is_error);
11366 let r = ed(&mut srv, json!([{ "op": "ripple_delete", "clip": "V1@0" }]));
11367 assert!(!r.is_error, "{}", r.text);
11368 // Every cut piece after the first shifts on V1 and on A1.
11369 let total = 2 * cuts.len();
11370 let shown = r.text.lines().find(|l| l.starts_with(" shifted: ")).expect("shifted line");
11371 assert_eq!(shown.matches('→').count(), total.min(SHIFT_CAP), "{shown}");
11372 if total > SHIFT_CAP {
11373 assert!(shown.ends_with(&format!("+{} more", total - SHIFT_CAP)), "{shown}");
11374 }
11375 }
11376
11377 #[test]
11378 fn freeze_at_a_clips_last_frame_goes_after_it_with_no_sliver() {
11379 let dir = TestDir::new("freeze-last-frame");
11380 let mut srv = open();
11381 srv.path = Some(dir.join("cut.edith"));
11382 let len = first_len(&srv);
11383 let r = ed(&mut srv, json!([{ "op": "freeze", "at": format!("{}f", len - 1), "duration": "1s" }]));
11384 assert!(!r.is_error, "{}", r.text);
11385 assert!(r.text.contains("holding frame"), "{}", r.text);
11386 let s = srv.session.as_ref().unwrap();
11387 let v1 = s.lane_clips(Lane::V1);
11388 assert_eq!(v1.len(), 2, "{}", r.text);
11389 assert_eq!(v1[0].frames(), len, "the clip is not cut: {}", r.text);
11390 assert_eq!(v1[1].start, len, "the still starts where the clip ends");
11391 }
11392
11393 #[test]
11394 fn a_still_with_in_out_names_its_length_and_how_to_change_it() {
11395 let mut srv = open();
11396 let still = asset("test_still.png");
11397 srv.session.as_mut().unwrap().import(&still).expect("import still");
11398 let n = srv.session.as_ref().unwrap().sources().len() - 1;
11399 let r = ed(&mut srv, json!([{ "op": "place", "source": n, "lane": "V1", "at": "0s", "in": "0s", "out": "1s" }]));
11400 assert!(r.is_error, "{}", r.text);
11401 assert!(r.text.contains("default 5.0 s") && r.text.contains("length"), "{}", r.text);
11402 }
11403
11404 /// Two copies of the test asset back to back on V1 and A1: V1@0 and V1@(first_len).
11405 fn two_takes() -> Server {
11406 let mut srv = open();
11407 let r = ed(&mut srv, json!([{ "op": "append", "source": 0 }]));
11408 assert!(!r.is_error, "{}", r.text);
11409 srv
11410 }
11411
11412 #[test]
11413 fn speed_without_ripple_refuses_and_names_ripple() {
11414 let mut srv = two_takes();
11415 let r = ed(&mut srv, json!([{ "op": "speed", "clip": "V1@0", "x": 0.5 }]));
11416 assert!(r.is_error, "{}", r.text);
11417 assert!(r.text.contains("ripple:true"), "{}", r.text);
11418 }
11419
11420 #[test]
11421 fn speed_ripple_slower_pushes_the_later_takes_and_is_one_undo_step() {
11422 let mut srv = two_takes();
11423 let fps = parse::session_fps(srv.session.as_ref().unwrap());
11424 let s0 = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].clone();
11425 let next_before = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[1].start;
11426 assert_eq!(next_before, s0.end());
11427 let steps = srv.ledger.len();
11428 let r = ed(&mut srv, json!([{ "op": "speed", "clip": "V1@0", "x": 0.5, "ripple": true }]));
11429 assert!(!r.is_error, "{}", r.text);
11430 assert_eq!(srv.ledger.len(), steps + 1, "one undo step for the batch");
11431 let s = srv.session.as_ref().unwrap();
11432 let slow = s.lane_clips(Lane::V1)[0].clone();
11433 assert_eq!(slow.frames(), 2 * s0.frames(), "half speed doubles the length");
11434 assert_eq!(s.lane_clips(Lane::V1)[1].start, slow.end(), "the next V1 take moved to the new end");
11435 assert_eq!(s.lane_clips(Lane::A1)[1].start, slow.end(), "its sound partner moved with it");
11436 assert!(fps > 0.0);
11437 let u = run_undo(&mut srv, &json!({}));
11438 assert!(!u.is_error, "{}", u.text);
11439 let s = srv.session.as_ref().unwrap();
11440 assert_eq!(s.lane_clips(Lane::V1)[0].frames(), s0.frames(), "undo restores the speed");
11441 assert_eq!(s.lane_clips(Lane::V1)[1].start, next_before, "and the later take");
11442 }
11443
11444 #[test]
11445 fn speed_ramp_sets_the_length_from_the_ramp_and_clearing_restores_the_constant() {
11446 let mut srv = two_takes();
11447 let s0 = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].clone();
11448 let len = s0.len();
11449 let keys = [engine::project::SpeedKey { at: 0, speed: Speed::NORMAL }, engine::project::SpeedKey { at: 60, speed: Speed::from_permille(2000) }];
11450 let want = engine::project::ramp_frames(&keys, len);
11451 assert!(want < len, "a speeding-up ramp shortens a {len}-frame clip, to {want}");
11452 let steps = srv.ledger.len();
11453 let r = ed(
11454 &mut srv,
11455 json!([{ "op": "speed_ramp", "clip": "V1@0", "keys": [
11456 {"at": "0f", "speed": 1.0}, {"at": "2s", "speed": 2.0}
11457 ], "ripple": true }]),
11458 );
11459 assert!(!r.is_error, "{}", r.text);
11460 assert!(r.text.contains("speed ramp V1@0 (5.000s → 3.000s)"), "{}", r.text);
11461 assert!(r.text.contains("→"), "the reply names the length change: {}", r.text);
11462 assert_eq!(srv.ledger.len(), steps + 1, "one undo step for the batch");
11463 let s = srv.session.as_ref().unwrap();
11464 let ramped = s.lane_clips(Lane::V1)[0].clone();
11465 assert_eq!(ramped.speed_keys, keys.to_vec(), "the keys are on the clip");
11466 assert_eq!(ramped.frames(), want, "the length is the ramp's footprint");
11467 assert_eq!(s.lane_clips(Lane::V1)[1].start, ramped.end(), "the later take closed up to the new end");
11468 // Clearing: the constant speed comes back, which was real time.
11469 let r = ed(&mut srv, json!([{ "op": "speed_ramp", "clip": "V1@0", "keys": [], "ripple": true }]));
11470 assert!(!r.is_error, "{}", r.text);
11471 let s = srv.session.as_ref().unwrap();
11472 let cleared = s.lane_clips(Lane::V1)[0].clone();
11473 assert!(cleared.speed_keys.is_empty());
11474 assert_eq!(cleared.frames(), s0.frames(), "a cleared ramp is the constant speed again");
11475 }
11476
11477 #[test]
11478 fn speed_ramp_refuses_bad_keys_and_changes_nothing() {
11479 let mut srv = two_takes();
11480 let before = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].clone();
11481 for (keys, want) in [
11482 (json!([{"at": "0s", "speed": 9.0}]), "outside 0.25–4"),
11483 (json!([{"at": "2s", "speed": 1.0}, {"at": "1s", "speed": 2.0}]), "increasing order"),
11484 (json!([{"at": "0s"}]), "needs `speed`"),
11485 (json!("fast"), "must be a list"),
11486 ] {
11487 let r = ed(&mut srv, json!([{ "op": "speed_ramp", "clip": "V1@0", "keys": keys, "ripple": true }]));
11488 assert!(r.is_error, "{keys} should be refused");
11489 assert!(r.text.contains(want), "{keys}: {}", r.text);
11490 }
11491 assert_eq!(srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0], before);
11492 }
11493
11494 #[test]
11495 fn speed_ripple_faster_closes_the_gap() {
11496 let mut srv = two_takes();
11497 let s0 = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].clone();
11498 let r = ed(&mut srv, json!([{ "op": "speed", "clip": "V1@0", "x": 2, "ripple": true }]));
11499 assert!(!r.is_error, "{}", r.text);
11500 let s = srv.session.as_ref().unwrap();
11501 let fast = s.lane_clips(Lane::V1)[0].clone();
11502 assert_eq!(fast.end(), s0.frames() / 2 + u32::from(s0.frames() % 2 == 1), "2x halves the length");
11503 assert_eq!(s.lane_clips(Lane::V1)[1].start, fast.end(), "the gap closed");
11504 assert_eq!(s.lane_clips(Lane::A1)[1].start, fast.end(), "the sound closed it too");
11505 }
11506
11507 #[test]
11508 fn ripple_delete_moves_titles_after_the_cut_with_the_picture() {
11509 let mut srv = two_takes();
11510 let fps = parse::session_fps(srv.session.as_ref().unwrap());
11511 let r = ed(&mut srv, json!([{ "op": "title_add", "at": "6s", "duration": "1s", "text": "Porto" }]));
11512 assert!(!r.is_error, "{}", r.text);
11513 let before = srv.session.as_ref().unwrap().titles()[0].start;
11514 let cut = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].clone();
11515 let r = ed(&mut srv, json!([{ "op": "ripple_delete", "clip": "V1@0" }]));
11516 assert!(!r.is_error, "{}", r.text);
11517 let s = srv.session.as_ref().unwrap();
11518 assert_eq!(s.titles()[0].start, before - cut.frames(), "the title moved with the picture");
11519 assert_eq!(s.titles()[0].start, (1.0 * fps).round() as u32);
11520 assert!(r.text.contains("titles moved"), "{}", r.text);
11521 }
11522
11523 #[test]
11524 fn delete_moves_a_title_after_the_removed_clip() {
11525 let mut srv = two_takes();
11526 let r = ed(&mut srv, json!([{ "op": "title_add", "at": "6s", "duration": "1s", "text": "Porto" }]));
11527 assert!(!r.is_error, "{}", r.text);
11528 let before = srv.session.as_ref().unwrap().titles()[0].start;
11529 let len = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].frames();
11530 let r = ed(&mut srv, json!([{ "op": "delete", "clip": "V1@0" }]));
11531 assert!(!r.is_error, "{}", r.text);
11532 assert_eq!(srv.session.as_ref().unwrap().titles()[0].start, before - len);
11533 }
11534
11535 fn s1() -> Lane {
11536 Lane::new(LaneKind::Subtitle, 0)
11537 }
11538
11539 /// The text of each cue S1 shows, in timeline order.
11540 fn shown(srv: &Server, lane: Lane) -> Vec<String> {
11541 srv.session.as_ref().unwrap().sub_lane_cues(lane).into_iter().map(|c| c.text).collect()
11542 }
11543
11544 /// One four-second sentence, "alpha beta gamma delta", placed on S1 at 0.
11545 fn sentence(tag: &str) -> (Server, TestDir) {
11546 let mut srv = open();
11547 let dir = TestDir::new(&format!("cues-{tag}"));
11548 let a = dir.path().join("a.srt");
11549 std::fs::write(&a, "1\n00:00:00,000 --> 00:00:04,000\nalpha beta gamma delta\n").unwrap();
11550 let r = ed(
11551 &mut srv,
11552 json!([
11553 { "op": "subtitles_import", "path": a.to_string_lossy() },
11554 { "op": "captions_place", "track": 0, "lane": "S1", "at": "0f" }
11555 ]),
11556 );
11557 assert!(!r.is_error, "{}", r.text);
11558 (srv, dir)
11559 }
11560
11561 /// Cutting a span out of a sentence keeps the words either side and drops
11562 /// the ones inside: "beta" lies in 1 s to 2 s, so "alpha" and "gamma delta"
11563 /// are what is left. Undo brings the sentence back whole.
11564 #[test]
11565 fn remove_time_through_a_sentence_keeps_the_words_outside_the_span() {
11566 let (mut srv, _dir) = sentence("remove");
11567 let r = ed(&mut srv, json!([{ "op": "remove_time", "at": "1s", "duration": "1s" }]));
11568 assert!(!r.is_error, "{}", r.text);
11569 assert_eq!(shown(&srv, s1()), ["alpha", "gamma delta"], "{}", r.text);
11570
11571 let u = run_undo(&mut srv, &json!({}));
11572 assert!(!u.is_error, "{}", u.text);
11573 assert_eq!(shown(&srv, s1()), ["alpha beta gamma delta"], "undo restores the sentence");
11574 }
11575
11576 /// Opening room inside a sentence divides its words once, with no "(part n/2)"
11577 /// copies of the whole sentence: "alpha" stays where it was and the rest moves on.
11578 #[test]
11579 fn insert_time_through_a_sentence_divides_its_words() {
11580 let (mut srv, _dir) = sentence("insert");
11581 let r = ed(&mut srv, json!([{ "op": "insert_time", "at": "1s", "duration": "2s" }]));
11582 assert!(!r.is_error, "{}", r.text);
11583 assert_eq!(shown(&srv, s1()), ["alpha", "beta gamma delta"], "{}", r.text);
11584 assert!(shown(&srv, s1()).iter().all(|t| !t.contains("alpha beta")), "no copy of the whole sentence");
11585 }
11586
11587 /// A cue that runs past its placement's window is named by the part the
11588 /// placement shows, not by times before it starts or after it ends: the
11589 /// sentence over a window trimmed to 0 s to 2 s is "0.000s–2.000s".
11590 #[test]
11591 fn a_cue_past_its_window_is_named_by_the_part_shown() {
11592 let (mut srv, _dir) = sentence("clamp");
11593 let r = ed(&mut srv, json!([{ "op": "sub_trim", "clip": "S1@0", "edge": "out", "to": "2s" }]));
11594 assert!(!r.is_error, "{}", r.text);
11595 let r = ed(&mut srv, json!([{ "op": "remove_time", "at": "1s", "duration": "1s" }]));
11596 assert!(!r.is_error, "{}", r.text);
11597 assert!(r.text.contains("trimmed: S1 cue 1 'alpha beta gamma delta' → 'alpha' (was 0.000s–2.000s, now 0.000s–1.000s)"), "{}", r.text);
11598 assert!(!r.text.contains("-"), "no negative time in the reply: {}", r.text);
11599 }
11600
11601 /// A cue shown by two placements of one track is listed once in the reply.
11602 #[test]
11603 fn a_cue_shown_twice_is_listed_once() {
11604 let (mut srv, _dir) = sentence("twice");
11605 let r = ed(&mut srv, json!([{ "op": "captions_place", "track": 0, "lane": "S2", "at": "0f" }]));
11606 assert!(!r.is_error, "{}", r.text);
11607 let r = ed(&mut srv, json!([{ "op": "remove_time", "at": "1s", "duration": "1s" }]));
11608 assert!(!r.is_error, "{}", r.text);
11609 assert_eq!(r.text.matches("'alpha beta gamma delta'").count(), 1, "{}", r.text);
11610 }
11611
11612 /// A ripple that moves the captions but leaves the narration under them
11613 /// warns; the same ripple with the narration's lane in its scope does not.
11614 #[test]
11615 fn a_ripple_that_leaves_the_sound_under_moved_captions_warns() {
11616 let (mut srv, _dir) = sentence("drift");
11617 // Split at 2 s, then take the narration off its picture (both halves): a take can only move whole.
11618 let r = ed(
11619 &mut srv,
11620 json!([{ "op": "split", "at": "2s" }, { "op": "ungroup", "clip": "V1@0" }, { "op": "ungroup", "clip": "V1@60" }]),
11621 );
11622 assert!(!r.is_error, "{}", r.text);
11623 let r = ed(&mut srv, json!([{ "op": "ripple_delete", "clip": "V1@0", "lanes": ["V1", "S1"] }]));
11624 assert!(!r.is_error, "{}", r.text);
11625 assert!(r.text.contains("left in place"), "{}", r.text);
11626 assert!(
11627 r.text.contains("captions on S1 moved −2.000s but A1 (sound under them) stayed"),
11628 "{}",
11629 r.text
11630 );
11631 assert!(r.text.contains("add lanes:[…A1] or undo"), "{}", r.text);
11632
11633 let (mut srv, _dir) = sentence("linked");
11634 let r = ed(&mut srv, json!([{ "op": "split", "at": "2s" }, { "op": "ripple_delete", "clip": "V1@0" }]));
11635 assert!(!r.is_error, "{}", r.text);
11636 assert!(!r.text.contains("may no longer match"), "the linked narration moves with the picture: {}", r.text);
11637 }
11638
11639 /// Captions placed on S1 from one SRT cue, `start` to `end` seconds, as `srt`'s text.
11640 fn captions_from(tag: &str, srt: &str) -> (Server, TestDir) {
11641 let mut srv = open();
11642 let dir = TestDir::new(&format!("cues-{tag}"));
11643 let a = dir.path().join("a.srt");
11644 std::fs::write(&a, srt).unwrap();
11645 let r = ed(
11646 &mut srv,
11647 json!([
11648 { "op": "subtitles_import", "path": a.to_string_lossy() },
11649 { "op": "captions_place", "track": 0, "lane": "S1", "at": "0f" }
11650 ]),
11651 );
11652 assert!(!r.is_error, "{}", r.text);
11653 (srv, dir)
11654 }
11655
11656 /// Adds an audio lane A2 with the asset's sound looped back to back to six seconds: a clip at 0
11657 /// that runs to 5 s and one at 5 s to 6 s.
11658 fn sound_bed_on_a2(srv: &mut Server) {
11659 let r = ed(srv, json!([{ "op": "lane_add", "kind": "audio" }]));
11660 assert!(!r.is_error, "{}", r.text);
11661 let r = ed(srv, json!([{ "op": "append", "source": 0, "lane": "A2", "until": "6s" }]));
11662 assert!(!r.is_error, "{}", r.text);
11663 }
11664
11665 /// A one-word cue that a cut at 3 s runs through (0 s to 4 s) is shown once, on the longer side
11666 /// (the head, 3 s), and an insert at 3 s leaves no copy on the far side.
11667 #[test]
11668 fn insert_time_through_a_one_word_caption_shows_the_word_once() {
11669 let (mut srv, _dir) = captions_from("one-word", "1\n00:00:00,000 --> 00:00:04,000\nOnewordcue\n");
11670 let r = ed(&mut srv, json!([{ "op": "insert_time", "at": "3s", "duration": "2s" }]));
11671 assert!(!r.is_error, "{}", r.text);
11672 assert_eq!(shown(&srv, s1()), ["Onewordcue"], "{}", r.text);
11673 }
11674
11675 /// (a) V1 in two clips with A1 linked to them, an unlinked sound bed on A2 under captions over 2 s to 6 s.
11676 /// Rippling V1's first clip moves the captions 2 s and leaves A2 where it was: the warning names A2.
11677 #[test]
11678 fn a_ripple_warns_when_an_unlinked_sound_bed_under_moved_captions_stays() {
11679 let (mut srv, _dir) = captions_from("drift-a", "1\n00:00:02,000 --> 00:00:06,000\nalpha beta gamma delta\n");
11680 let r = ed(&mut srv, json!([{ "op": "split", "at": "2s" }]));
11681 assert!(!r.is_error, "{}", r.text);
11682 sound_bed_on_a2(&mut srv);
11683 let r = ed(&mut srv, json!([{ "op": "ripple_delete", "clip": "V1@0" }]));
11684 assert!(!r.is_error, "{}", r.text);
11685 assert!(
11686 r.text.contains("captions on S1 moved −2.000s but A2 (sound under them) stayed"),
11687 "{}",
11688 r.text
11689 );
11690 assert!(!r.text.contains("A1 (sound under them)"), "the linked A1 moved with the picture: {}", r.text);
11691 }
11692
11693 /// (b) The sound is A1 under V1's clips, and the take is detached (a take cannot move one track
11694 /// alone): the ripple names its lanes as V1 and S1, so A1 is left out, the captions move and the
11695 /// speech under them stays. The warning names A1.
11696 #[test]
11697 fn a_ripple_with_explicit_lanes_warns_when_the_sound_is_left_out() {
11698 let (mut srv, _dir) = captions_from("drift-b", "1\n00:00:02,000 --> 00:00:06,000\nalpha beta gamma delta\n");
11699 let r = ed(
11700 &mut srv,
11701 json!([{ "op": "split", "at": "2s" }, { "op": "ungroup", "clip": "V1@0" }, { "op": "ungroup", "clip": "V1@60" }]),
11702 );
11703 assert!(!r.is_error, "{}", r.text);
11704 let r = ed(&mut srv, json!([{ "op": "ripple_delete", "clip": "V1@0", "lanes": ["V1", "S1"] }]));
11705 assert!(!r.is_error, "{}", r.text);
11706 assert!(
11707 r.text.contains("captions on S1 moved −2.000s but A1 (sound under them) stayed"),
11708 "{}",
11709 r.text
11710 );
11711 }
11712
11713 /// (c) A locked sound bed on A2 (a clip from 0 to 5 s, starting before the cut) under captions the
11714 /// remove moves: the warning names A2 even though its clip begins before the edit.
11715 #[test]
11716 fn a_remove_warns_when_a_locked_sound_bed_that_starts_before_the_cut_stays() {
11717 let (mut srv, _dir) = captions_from("drift-c", "1\n00:00:02,000 --> 00:00:06,000\nalpha beta gamma delta\n");
11718 sound_bed_on_a2(&mut srv);
11719 let r = ed(&mut srv, json!([{ "op": "lane_flags", "lane": "A2", "locked": true }]));
11720 assert!(!r.is_error, "{}", r.text);
11721 let r = ed(&mut srv, json!([{ "op": "remove_time", "at": "1s", "duration": "1s" }]));
11722 assert!(r.is_error && r.text.contains("lane A2 is locked") && r.text.contains("pass lanes without it"), "{}", r.text);
11723 }
11724
11725 /// Captions that end before the cut do not move, so the sound under them is not drift.
11726 #[test]
11727 fn a_ripple_over_captions_that_do_not_move_does_not_warn() {
11728 let (mut srv, _dir) = captions_from("drift-none", "1\n00:00:00,000 --> 00:00:01,000\nalpha\n");
11729 let r = ed(&mut srv, json!([{ "op": "split", "at": "2s" }]));
11730 assert!(!r.is_error, "{}", r.text);
11731 sound_bed_on_a2(&mut srv);
11732 let r = ed(&mut srv, json!([{ "op": "ripple_delete", "clip": "V1@60" }]));
11733 assert!(!r.is_error, "{}", r.text);
11734 assert!(!r.text.contains("captions on"), "{}", r.text);
11735 }
11736
11737 #[test]
11738 fn fade_clamp_is_reported_for_a_short_clip() {
11739 let mut srv = open();
11740 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "10s", "audio": false, "in": "0s", "out": "0.88s" }]));
11741 assert!(!r.is_error, "{}", r.text);
11742 let r = ed(&mut srv, json!([{ "op": "fade", "clip": "V1@10s", "out": "1s" }]));
11743 assert!(!r.is_error, "{}", r.text);
11744 assert!(r.text.contains("out clamped from 1.0s to the clip's 0.87s"), "{}", r.text);
11745 }
11746
11747 #[test]
11748 fn dry_run_leaves_a_clean_project_clean() {
11749 let mut srv = open();
11750 let s = srv.session.as_ref().unwrap();
11751 srv.saved_depth = Some(s.undo_depth());
11752 srv.saved_pushes = Some(s.history_pushes());
11753 srv.saved_sources = Some(s.sources().len());
11754 assert!(!crate::tools::project::dirty(&srv));
11755 let r = run_edit(&mut srv, &json!({ "ops": [{ "op": "split", "at": "1s" }], "dry_run": true }));
11756 assert!(!r.is_error, "{}", r.text);
11757 assert!(r.text.contains("dry run"), "{}", r.text);
11758 assert!(!crate::tools::project::dirty(&srv), "a dry run leaves the project clean");
11759 assert!(srv.ledger.is_empty(), "and keeps no ledger entry");
11760 }
11761
11762 #[test]
11763 fn append_until_loops_the_source_and_trims_the_last_copy() {
11764 let mut srv = open();
11765 let r = ed(&mut srv, json!([{ "op": "lane_add", "kind": "audio" }]));
11766 assert!(!r.is_error, "{}", r.text);
11767 let fps = parse::session_fps(srv.session.as_ref().unwrap());
11768 let until = (12.0 * fps).round() as u32;
11769 let r = ed(&mut srv, json!([{ "op": "append", "source": 0, "lane": "A2", "until": "12s" }]));
11770 assert!(!r.is_error, "{}", r.text);
11771 assert!(r.text.contains("loop src:0"), "{}", r.text);
11772 let s = srv.session.as_ref().unwrap();
11773 let a2 = s.lane_clips(Lane::new(LaneKind::Audio, 1)).to_vec();
11774 assert!(a2.len() >= 2, "the copy repeats: {}", r.text);
11775 assert_eq!(a2[0].start, 0);
11776 for w in a2.windows(2) {
11777 assert_eq!(w[1].start, w[0].end(), "back to back");
11778 }
11779 assert_eq!(a2.last().unwrap().end(), until, "the last copy ends at the time asked");
11780 assert!(a2.last().unwrap().frames() <= a2[0].frames(), "the last copy is trimmed");
11781 assert!(r.text.contains("last copy trimmed"), "{}", r.text);
11782 }
11783
11784 /// The flags of the waveform picture a visualizer on a sound clip placed (the first picture
11785 /// clip on a video lane above V1 that carries any).
11786 fn picture_flags(s: &PlaybackSession) -> u8 {
11787 s.lanes()
11788 .into_iter()
11789 .filter(|l| l.kind == LaneKind::Video && l.ord > 0)
11790 .flat_map(|l| s.lane_clips(l).iter().map(|c| c.visualizer).collect::<Vec<_>>())
11791 .find(|&v| v != 0)
11792 .unwrap_or(0)
11793 }
11794
11795 #[test]
11796 fn visualizer_sets_on_style_and_fast_in_one_step() {
11797 // The visualizer is set on the sound clip; its waveform picture carries the flags.
11798 let mut srv = open();
11799 let steps = srv.ledger.len();
11800 let r = ed(&mut srv, json!([{ "op": "visualizer", "clip": "A1@0", "on": true, "style": "ring", "fast": true }]));
11801 assert!(!r.is_error, "{}", r.text);
11802 assert!(r.text.contains("style ring, fast"), "{}", r.text);
11803 let v = picture_flags(srv.session.as_ref().unwrap());
11804 assert_eq!(v & 1, 1, "bit 0 on");
11805 assert_eq!(engine::decode::viz_style(v), 2, "ring");
11806 assert_eq!(v & engine::decode::VIZ_FAST, engine::decode::VIZ_FAST, "fast");
11807 assert_eq!(srv.ledger.len(), steps + 1, "one undo step");
11808 let r = ed(&mut srv, json!([{ "op": "visualizer", "clip": "A1@0", "on": true, "style": "wave" }]));
11809 assert!(!r.is_error, "{}", r.text);
11810 let v = picture_flags(srv.session.as_ref().unwrap());
11811 assert_eq!(engine::decode::viz_style(v), 3, "style changed, fast kept");
11812 assert_ne!(v & engine::decode::VIZ_FAST, 0);
11813 }
11814
11815 #[test]
11816 fn visualizer_refuses_unknown_style_and_strays() {
11817 let mut srv = open();
11818 let r = ed(&mut srv, json!([{ "op": "visualizer", "clip": "A1@0", "on": true, "style": "spiral" }]));
11819 assert!(r.is_error && r.text.contains("fill, ribbon, ring, wave"), "{}", r.text);
11820 let r = ed(&mut srv, json!([{ "op": "visualizer", "clip": "A1@0", "style": "ring" }]));
11821 assert!(r.is_error && r.text.contains("on:true"), "{}", r.text);
11822 let r = ed(&mut srv, json!([{ "op": "visualizer", "clip": "A1@0", "on": true, "colour": "red" }]));
11823 assert!(r.is_error && r.text.contains("unknown key"), "{}", r.text);
11824 }
11825
11826 fn lane_clips_of(srv: &Server, l: Lane) -> Vec<(u32, u32, Option<u32>)> {
11827 srv.session.as_ref().unwrap().lane_clips(l).iter().map(|c| (c.start, c.frames(), c.link)).collect()
11828 }
11829
11830 #[test]
11831 fn music_delete_leaves_picture_and_sound_alone() {
11832 let mut srv = open();
11833 let built = ed(
11834 &mut srv,
11835 json!([
11836 { "op": "lane_add", "kind": "audio" },
11837 { "op": "append", "source": 0, "lane": "A2" },
11838 { "op": "append", "source": 0, "lane": "A2" }
11839 ]),
11840 );
11841 assert!(!built.is_error, "{}", built.text);
11842 let a2 = parse::lane("A2").unwrap();
11843 let picture = lane_clips_of(&srv, Lane::V1);
11844 let sound = lane_clips_of(&srv, Lane::A1);
11845 let music = lane_clips_of(&srv, a2);
11846 assert!(music.len() >= 2, "{:?}", music);
11847 let r = ed(&mut srv, json!([{ "op": "delete", "clip": "A2@0" }]));
11848 assert!(!r.is_error, "{}", r.text);
11849 assert_eq!(lane_clips_of(&srv, Lane::V1), picture, "V1 moved: {}", r.text);
11850 assert_eq!(lane_clips_of(&srv, Lane::A1), sound, "A1 moved: {}", r.text);
11851 assert_eq!(lane_clips_of(&srv, a2).len(), music.len() - 1, "{}", r.text);
11852 }
11853
11854 #[test]
11855 fn broll_speed_ripple_does_not_touch_sound() {
11856 let mut srv = open();
11857 let built = ed(
11858 &mut srv,
11859 json!([
11860 { "op": "lane_add", "kind": "audio" },
11861 { "op": "append", "source": 0, "lane": "A2" },
11862 { "op": "lane_add", "kind": "video" },
11863 { "op": "place", "source": 0, "lane": "V2", "at": "0s", "audio": false }
11864 ]),
11865 );
11866 assert!(!built.is_error, "{}", built.text);
11867 let picture = lane_clips_of(&srv, Lane::V1);
11868 let sound = lane_clips_of(&srv, Lane::A1);
11869 let music = lane_clips_of(&srv, parse::lane("A2").unwrap());
11870 let r = ed(&mut srv, json!([{ "op": "speed", "clip": "V2@0", "x": 0.5, "ripple": true }]));
11871 assert!(!r.is_error, "{}", r.text);
11872 assert_eq!(lane_clips_of(&srv, Lane::V1), picture, "{}", r.text);
11873 assert_eq!(lane_clips_of(&srv, Lane::A1), sound, "{}", r.text);
11874 assert_eq!(lane_clips_of(&srv, parse::lane("A2").unwrap()), music, "{}", r.text);
11875 }
11876
11877 #[test]
11878 fn ripple_delete_of_a_picture_clip_keeps_the_take_linked() {
11879 let mut srv = open();
11880 let built = ed(
11881 &mut srv,
11882 json!([
11883 { "op": "lane_add", "kind": "video" },
11884 { "op": "place", "source": 0, "lane": "V2", "at": "0s", "audio": false }
11885 ]),
11886 );
11887 assert!(!built.is_error, "{}", built.text);
11888 let picture = lane_clips_of(&srv, Lane::V1);
11889 let sound = lane_clips_of(&srv, Lane::A1);
11890 let link = sound[0].2;
11891 assert!(link.is_some(), "the fixture's V1/A1 take is linked");
11892 let r = ed(&mut srv, json!([{ "op": "ripple_delete", "clip": "V2@0" }]));
11893 assert!(!r.is_error, "{}", r.text);
11894 assert!(!r.text.contains("detached"), "{}", r.text);
11895 assert_eq!(lane_clips_of(&srv, Lane::V1), picture, "{}", r.text);
11896 assert_eq!(lane_clips_of(&srv, Lane::A1), sound, "{}", r.text);
11897 }
11898
11899 #[test]
11900 fn linked_trim_moves_both_halves_to_one_time() {
11901 let mut srv = open();
11902 let len = first_len(&srv);
11903 let half = len / 2;
11904 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "A1@0", "edge": "out", "to": format!("{half}f") }]));
11905 assert!(!r.is_error, "{}", r.text);
11906 assert!(r.text.contains("(with V1@0)"), "{}", r.text);
11907 assert!(!r.text.contains("shifted: V1@0→A1@0"), "{}", r.text);
11908 let s = srv.session.as_ref().unwrap();
11909 let v = s.lane_clips(Lane::V1)[0].end();
11910 let a = s.lane_clips(Lane::A1)[0].end();
11911 assert_eq!(v, a, "picture and sound ends agree: {}", r.text);
11912 assert_eq!(v, half, "{}", r.text);
11913 }
11914
11915 #[test]
11916 fn split_on_named_lanes_cuts_only_them() {
11917 let mut srv = open();
11918 let len = first_len(&srv);
11919 let half = len / 2;
11920 let built = ed(&mut srv, json!([{ "op": "lane_add", "kind": "audio" }, { "op": "append", "source": 0, "lane": "A2" }]));
11921 assert!(!built.is_error, "{}", built.text);
11922 let music = lane_clips_of(&srv, parse::lane("A2").unwrap());
11923 let r = ed(&mut srv, json!([{ "op": "split", "at": format!("{half}f"), "lanes": ["V1"] }]));
11924 assert!(!r.is_error, "{}", r.text);
11925 // Explicit lanes are honoured exactly: A1 (linked to V1) stays whole, and the take is unlinked at the cut.
11926 assert!(r.text.contains("kept whole: A1, A2"), "{}", r.text);
11927 assert!(r.text.contains("detached at the cut"), "{}", r.text);
11928 assert_eq!(srv.session.as_ref().unwrap().lane_clips(Lane::V1).len(), 2);
11929 assert_eq!(srv.session.as_ref().unwrap().lane_clips(Lane::A1).len(), 1);
11930 assert_eq!(lane_clips_of(&srv, parse::lane("A2").unwrap()), music, "{}", r.text);
11931 }
11932
11933 #[test]
11934 fn dissolve_fades_sound_to_silence_when_no_sound_meets_it() {
11935 let mut srv = open();
11936 let built = ed(&mut srv, json!([{ "op": "append", "source": 0, "lane": "V1", "audio": false }]));
11937 assert!(!built.is_error, "{}", built.text);
11938 let r = ed(&mut srv, json!([{ "op": "dissolve", "clip": "V1@0", "frames": 12 }]));
11939 assert!(!r.is_error, "{}", r.text);
11940 assert!(r.text.contains("faded out 12f to silence"), "{}", r.text);
11941 assert!(!r.text.contains("was not crossfaded"), "{}", r.text);
11942 }
11943
11944 #[test]
11945 fn crossfade_to_silence_is_applied_not_refused() {
11946 let mut srv = open();
11947 let built = ed(&mut srv, json!([{ "op": "append", "source": 0, "lane": "V1", "audio": false }]));
11948 assert!(!built.is_error, "{}", built.text);
11949 let r = ed(&mut srv, json!([{ "op": "crossfade", "clip": "A1@0", "frames": 12 }]));
11950 assert!(!r.is_error, "{}", r.text);
11951 assert!(r.text.contains("faded out 12f to silence"), "{}", r.text);
11952 }
11953}
11954
11955/// Unit tests for the ripple rule, the lock closure, no-op batches, explicit split lanes,
11956/// lane-kind refusals and the left-behind list. Each opens the test asset (V1 and A1 linked).
11957#[cfg(test)]
11958mod ripple_rule_tests {
11959 use super::*;
11960 use std::path::Path;
11961
11962 fn open() -> Server {
11963 engine::ao::set_silent_output();
11964 let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
11965 let sess = PlaybackSession::open(p).expect("open test asset");
11966 Server { session: Some(sess), ..Server::default() }
11967 }
11968
11969 fn ed(srv: &mut Server, ops: Value) -> Reply {
11970 run_edit(srv, &json!({ "ops": ops }))
11971 }
11972
11973 fn clip_count(srv: &Server, lane: Lane) -> usize {
11974 srv.session.as_ref().unwrap().lane_clips(lane).len()
11975 }
11976
11977 fn len_of(srv: &Server) -> u32 {
11978 srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].frames()
11979 }
11980
11981 fn ledger(srv: &Server) -> usize {
11982 srv.ledger.len()
11983 }
11984
11985 #[test]
11986 fn locked_partner_refuses_a_ripple_and_moves_nothing() {
11987 // A1 is linked to V1, so a ripple from V1 reaches it: locked, the op refuses (finding 1).
11988 let mut srv = open();
11989 let half = len_of(&srv) / 2;
11990 assert!(!ed(&mut srv, json!([{ "op": "split", "at": format!("{half}f") }])).is_error);
11991 let before = ledger(&srv);
11992 let r = ed(&mut srv, json!([
11993 { "op": "lane_flags", "lane": "A1", "locked": true },
11994 { "op": "insert_time", "at": "0.1s", "duration": "1s" }
11995 ]));
11996 assert!(r.is_error, "{}", r.text);
11997 assert!(r.text.contains("A1 is locked") || r.text.contains("lane A1 is locked"), "{}", r.text);
11998 assert_eq!(ledger(&srv), before);
11999 }
12000
12001 #[test]
12002 fn locked_partner_refuses_a_cut_regions_default() {
12003 let mut srv = open();
12004 let r = ed(&mut srv, json!([
12005 { "op": "lane_flags", "lane": "A1", "locked": true },
12006 { "op": "cut_regions", "regions": [["0.2s", "0.4s"]] }
12007 ]));
12008 assert!(r.is_error, "{}", r.text);
12009 assert!(r.text.contains("locked"), "{}", r.text);
12010 }
12011
12012 #[test]
12013 fn deleting_a_whole_take_reports_no_unlink() {
12014 // Finding 2: the deleted pair is gone; the reply must not say its link was broken.
12015 let mut srv = open();
12016 let half = len_of(&srv) / 2;
12017 let r = ed(&mut srv, json!([
12018 { "op": "split", "at": format!("{half}f") },
12019 { "op": "delete", "clip": format!("V1@{half}") }
12020 ]));
12021 assert!(!r.is_error, "{}", r.text);
12022 assert!(!r.text.contains("detached"), "{}", r.text);
12023 }
12024
12025 #[test]
12026 fn past_the_end_remove_time_is_no_change_and_no_undo_step() {
12027 // Finding 3: the no-op batch is rolled back and the reply says why.
12028 let mut srv = open();
12029 let before = ledger(&srv);
12030 let r = ed(&mut srv, json!([{ "op": "remove_time", "at": "1000s", "duration": "1s" }]));
12031 assert!(!r.is_error, "{}", r.text);
12032 assert!(r.text.starts_with("no change:"), "{}", r.text);
12033 assert_eq!(ledger(&srv), before);
12034 }
12035
12036 #[test]
12037 fn empty_lanes_is_named_and_explicit_lanes_keep_partners_whole() {
12038 // Finding 8.
12039 let mut srv = open();
12040 let half = len_of(&srv) / 2;
12041 let r = ed(&mut srv, json!([{ "op": "split", "at": format!("{half}f"), "lanes": [] }]));
12042 assert!(r.is_error && r.text.contains("`lanes` is empty"), "{}", r.text);
12043
12044 let r = ed(&mut srv, json!([{ "op": "split", "at": format!("{half}f"), "lanes": ["V1"] }]));
12045 assert!(!r.is_error, "{}", r.text);
12046 assert!(r.text.contains("kept whole: A1"), "{}", r.text);
12047 assert!(r.text.contains("detached at the cut"), "{}", r.text);
12048 assert_eq!(clip_count(&srv, Lane::V1), 2, "{}", r.text);
12049 assert_eq!(clip_count(&srv, Lane::A1), 1, "{}", r.text);
12050 }
12051
12052 #[test]
12053 fn kind_mismatches_are_refused() {
12054 // Finding 9.
12055 let mut srv = open();
12056 let r = ed(&mut srv, json!([{ "op": "color", "clip": "A1@0", "brightness": 0.1 }]));
12057 assert!(r.is_error && r.text.contains("audio lane"), "{}", r.text);
12058 let r = ed(&mut srv, json!([{ "op": "eq", "clip": "V1@0", "bands": [{ "f": 1000, "db": 3, "q": 1, "kind": "peak" }] }]));
12059 assert!(r.is_error && r.text.contains("video lane"), "{}", r.text);
12060 let r = ed(&mut srv, json!([{ "op": "visualizer", "clip": "A1@0", "on": false }]));
12061 assert!(!r.is_error && r.text.contains("off already"), "{}", r.text);
12062 let r = ed(&mut srv, json!([{ "op": "lane_gain", "lane": "V1", "db": -3 }]));
12063 assert!(r.is_error && r.text.contains("video lane"), "{}", r.text);
12064 }
12065
12066 #[test]
12067 fn ripple_lists_clips_left_in_place_outside_the_scope() {
12068 // Finding 15: a V2 clip after the edit point stays put and is named.
12069 let mut srv = open();
12070 let far = len_of(&srv) + 30;
12071 let r = ed(&mut srv, json!([
12072 { "op": "lane_add", "kind": "video" },
12073 { "op": "place", "source": 0, "at": format!("{far}f"), "lane": "V2", "audio": false },
12074 { "op": "ripple_delete", "clip": "V1@0" }
12075 ]));
12076 assert!(!r.is_error, "{}", r.text);
12077 assert!(r.text.contains("left in place") && r.text.contains("V2@"), "{}", r.text);
12078 }
12079}
12080
12081/// Round 9 fixes: the no-op check, place length, audio-lane length, the no-op notes, cut slivers,
12082/// swap slots, take links through a cut and the half-open remove_time span.
12083#[cfg(test)]
12084mod round9_tests {
12085 use super::*;
12086
12087 fn open() -> Server {
12088 engine::ao::set_silent_output();
12089 let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
12090 Server { session: Some(PlaybackSession::open(p).expect("open test asset")), ..Server::default() }
12091 }
12092
12093 fn asset(name: &str) -> PathBuf {
12094 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
12095 }
12096
12097 fn open_asset(name: &str) -> Server {
12098 engine::ao::set_silent_output();
12099 let sess = PlaybackSession::open(asset(name)).expect("open test asset");
12100 Server { session: Some(sess), ..Server::default() }
12101 }
12102
12103 fn ed(srv: &mut Server, ops: Value) -> Reply {
12104 run_edit(srv, &json!({ "ops": ops }))
12105 }
12106
12107 /// Runs one op, checks it applied and the project changed, then undoes it and checks the
12108 /// project is back where it was.
12109 fn sticks_and_undoes(ops: Value) {
12110 let mut srv = open_asset("test_av.mp4");
12111 let before = state_of(srv.session.as_ref().unwrap());
12112 let r = ed(&mut srv, ops.clone());
12113 assert!(!r.is_error && !r.text.starts_with("no change"), "{ops}: {}", r.text);
12114 let after = state_of(srv.session.as_ref().unwrap());
12115 assert_ne!(before, after, "{ops} changed nothing the no-op check can see");
12116 // One ledger step, which may be several engine steps (a placed picture is one of them). The link
12117 // counter is not rolled back by an undo: a link id once handed out is simply not reused.
12118 assert!(!run_undo(&mut srv, &json!({})).is_error, "{ops}: an undo step was taken");
12119 let without_counter = |t: String| t.split("next_link: ").enumerate().map(|(i, p)| if i == 0 { p.to_string() } else { p.trim_start_matches(|c: char| c.is_ascii_digit()).to_string() }).collect::<String>();
12120 assert_eq!(without_counter(state_of(srv.session.as_ref().unwrap())), without_counter(before), "{ops}: undo restores it");
12121 }
12122
12123 #[test]
12124 fn lane_settings_are_kept_by_the_no_op_check_and_undoable() {
12125 sticks_and_undoes(json!([{ "op": "lane_gain", "lane": "A1", "db": -6 }]));
12126 sticks_and_undoes(json!([{ "op": "limiter", "on": true, "ceiling_db": -3 }]));
12127 sticks_and_undoes(json!([{ "op": "lane_flags", "lane": "A1", "muted": true }]));
12128 sticks_and_undoes(json!([{ "op": "color", "clip": "V1@0", "brightness": 0.2 }]));
12129 sticks_and_undoes(json!([{ "op": "eq", "clip": "A1@0", "bands": [{ "f": 1000, "db": 3, "q": 1, "kind": "peak" }] }]));
12130 sticks_and_undoes(json!([{ "op": "visualizer", "clip": "A1@0", "on": true, "style": "wave" }]));
12131 }
12132
12133 #[test]
12134 fn duck_sticks_and_is_undoable() {
12135 let mut srv = open_asset("test_av.mp4");
12136 let r = ed(&mut srv, json!([{ "op": "lane_add", "kind": "audio" }]));
12137 assert!(!r.is_error, "{}", r.text);
12138 let before = state_of(srv.session.as_ref().unwrap());
12139 let r = ed(&mut srv, json!([{ "op": "duck", "lane": "A1", "under": "A2" }]));
12140 assert!(!r.is_error && !r.text.starts_with("no change"), "{}", r.text);
12141 assert_ne!(before, state_of(srv.session.as_ref().unwrap()));
12142 assert!(srv.session.as_mut().unwrap().undo());
12143 assert_eq!(state_of(srv.session.as_ref().unwrap()), before);
12144 }
12145
12146 #[test]
12147 fn place_takes_length_and_append_does_too() {
12148 let mut srv = open_asset("test_av.mp4");
12149 let fps = parse::session_fps(srv.session.as_ref().unwrap());
12150 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "20s", "length": "1s" }]));
12151 assert!(!r.is_error, "{}", r.text);
12152 let r = ed(&mut srv, json!([{ "op": "append", "source": 0, "length": "1s" }]));
12153 assert!(!r.is_error, "{}", r.text);
12154 let last = srv.session.as_ref().unwrap().lane_clips(Lane::V1).last().unwrap().clone();
12155 assert_eq!(last.frames(), (1.0 * fps).round() as u32);
12156 // The schema and the tool text both name length.
12157 assert!(EDIT_DOC.contains("place {source, at, lane?, in?, out?, length?"), "the place signature names length");
12158 assert!(EDIT_DOC.contains("append {source, in?, out?, length?"), "the append signature names length");
12159 }
12160
12161 #[test]
12162 fn audio_lane_takes_the_sound_length_of_a_source_with_a_short_picture() {
12163 let mut srv = open_asset("test_short_video_long_audio.mp4");
12164 let fps = parse::session_fps(srv.session.as_ref().unwrap());
12165 let r = ed(&mut srv, json!([{ "op": "lane_add", "kind": "audio" }]));
12166 assert!(!r.is_error, "{}", r.text);
12167 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "A2", "at": "0s" }]));
12168 assert!(!r.is_error, "{}", r.text);
12169 let a2 = srv.session.as_ref().unwrap().lanes().into_iter().filter(|l| l.kind == LaneKind::Audio).nth(1).expect("the added audio lane");
12170 let placed = srv.session.as_ref().unwrap().lane_clips(a2)[0].frames();
12171 assert!(placed > (3.0 * fps) as u32, "the sound's length, not the 2 s picture: {placed}f");
12172 }
12173
12174 #[test]
12175 fn insert_time_at_the_end_says_why_nothing_moved() {
12176 let mut srv = open_asset("test_av.mp4");
12177 let end = parse::session_end(srv.session.as_ref().unwrap());
12178 let r = ed(&mut srv, json!([{ "op": "insert_time", "at": format!("{end}f"), "duration": "1s" }]));
12179 assert!(!r.is_error, "{}", r.text);
12180 assert!(r.text.contains("nothing after the end to push"), "{}", r.text);
12181 assert!(r.text.contains("no change"), "{}", r.text);
12182 }
12183
12184 /// On an empty timeline insert_time moves nothing and the reply says so, and names the way a lead-in comes about.
12185 #[test]
12186 fn insert_time_on_an_empty_timeline_says_nothing_changed() {
12187 let mut srv = Server { session: Some(PlaybackSession::empty(1920, 1080, 30.0).unwrap()), ..Server::default() };
12188 let depth = srv.session.as_ref().unwrap().undo_depth();
12189 let r = ed(&mut srv, json!([{ "op": "insert_time", "at": "0s", "duration": "3s" }]));
12190 assert!(!r.is_error, "{}", r.text);
12191 assert!(r.text.contains("the timeline is empty, so no clip moved and nothing changed"), "{}", r.text);
12192 assert!(r.text.contains("a 3.000s lead-in appears once a clip is placed after it"), "{}", r.text);
12193 assert!(!r.text.contains("nothing after the end"), "{}", r.text);
12194 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth, "no snapshot was pushed");
12195 }
12196
12197 /// A 30 fps timeline with the 25 fps test_25fps.mp4 imported as src:1.
12198 fn open_30_with_25() -> Server {
12199 engine::ao::set_silent_output();
12200 let mut sess = PlaybackSession::open(asset("test_av.mp4")).expect("open 30 fps asset");
12201 sess.import(&asset("test_25fps.mp4")).expect("import 25 fps asset");
12202 Server { session: Some(sess), ..Server::default() }
12203 }
12204
12205 /// The in-point is snapped once to the nearest source frame, ties up: 0.5s of the 25 fps
12206 /// source is 12.5, so frame 13 (0.520s), stored as the first timeline frame showing it (16f).
12207 /// The reply and the stored clip both read back 0.520s.
12208 #[test]
12209 fn place_in_on_a_tie_rounds_up_to_the_source_frame_once() {
12210 let mut srv = open_30_with_25();
12211 let end = parse::session_end(srv.session.as_ref().unwrap());
12212 let r = ed(&mut srv, json!([{ "op": "place", "source": 1, "lane": "V1", "at": format!("{end}f"), "in": "0.5s", "length": "1.0s", "audio": false }]));
12213 assert!(!r.is_error, "{}", r.text);
12214 assert!(r.text.contains("src 0.520s–1.520s"), "{}", r.text);
12215 assert!(r.text.contains("(0.5s → src 13f 0.520s)"), "{}", r.text);
12216 let c = srv.session.as_ref().unwrap().lane_clips(Lane::V1).iter().find(|c| c.start == end).expect("placed").clone();
12217 assert_eq!((c.in_frame, c.out_frame), (16, 46), "0.5s stored as 16f (shows 13), one second long, no second snap");
12218 }
12219
12220 /// An out-point at 1.5s of the 25 fps source is 37.5, so frame 38 (1.520s): stored as 46f.
12221 #[test]
12222 fn place_out_on_a_tie_rounds_up_to_the_source_frame() {
12223 let mut srv = open_30_with_25();
12224 let end = parse::session_end(srv.session.as_ref().unwrap());
12225 let r = ed(&mut srv, json!([{ "op": "place", "source": 1, "lane": "V1", "at": format!("{end}f"), "in": "0.5s", "out": "1.5s", "audio": false }]));
12226 assert!(!r.is_error, "{}", r.text);
12227 assert!(r.text.contains("src 0.520s–1.520s"), "{}", r.text);
12228 let c = srv.session.as_ref().unwrap().lane_clips(Lane::V1).iter().find(|c| c.start == end).expect("placed").clone();
12229 assert_eq!(c.out_frame, 46, "1.5s is source frame 38, first shown at timeline 46");
12230 let back = (f64::from(c.out_frame) * 25.0 / 30.0).floor() as u32;
12231 assert_eq!(back, 38, "the stored out reads back as the source frame the reply names");
12232 }
12233
12234 /// An in-point rounds once to the nearest source frame: 0.52s is
12235 /// source frame 13, stored as the first timeline frame that shows it (16f), and the reply,
12236 /// the clip and frame reading all say 0.520s, with no note because 0.52s is exact on the source.
12237 #[test]
12238 fn place_in_off_the_timeline_grid_rounds_to_the_source_frame_once() {
12239 let mut srv = open_30_with_25();
12240 let end = parse::session_end(srv.session.as_ref().unwrap());
12241 let r = ed(&mut srv, json!([{ "op": "place", "source": 1, "lane": "V1", "at": format!("{end}f"), "in": "0.52s", "length": "1.0s", "audio": false }]));
12242 assert!(!r.is_error, "{}", r.text);
12243 assert!(r.text.contains("src 0.520s–1.520s"), "{}", r.text);
12244 assert!(!r.text.contains("→ src"), "exact on the source, no note: {}", r.text);
12245 let c = srv.session.as_ref().unwrap().lane_clips(Lane::V1).iter().find(|c| c.start == end).expect("placed").clone();
12246 assert_eq!(c.in_frame, 16, "the first timeline frame showing source frame 13");
12247 assert_eq!(c.out_frame, 46);
12248 let back = (f64::from(c.in_frame) * 25.0 / 30.0).floor() as u32;
12249 assert_eq!(back, 13, "the stored frame reads back as the source frame the reply names");
12250 }
12251
12252 /// `keep` ranges go through the same snap: 0.5s to 2.0s of the 25 fps source, each once.
12253 #[test]
12254 fn keep_range_on_the_timeline_grid_names_the_frame_it_stores() {
12255 let mut srv = open_30_with_25();
12256 let r = ed(&mut srv, json!([{ "op": "keep", "source": 1, "ranges": [["0.5s", "2.0s"]] }]));
12257 assert!(!r.is_error, "{}", r.text);
12258 assert!(r.text.contains("src 0.520s–2.000s"), "{}", r.text);
12259 let s = srv.session.as_ref().unwrap();
12260 let c = s.lane_clips(Lane::V1).last().expect("the keep placed a clip");
12261 assert_eq!((c.in_frame, c.out_frame), (16, 60), "0.5s stores as 16f (frame 13); 2.0s is on the grid");
12262 }
12263
12264 #[test]
12265 fn a_trim_already_at_its_edge_is_a_note_not_a_failed_batch() {
12266 let mut srv = open_asset("test_av.mp4");
12267 let out = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].end();
12268 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "V1@0", "edge": "out", "to": format!("{out}f") }]));
12269 assert!(!r.is_error, "{}", r.text);
12270 assert!(r.text.contains("already at"), "{}", r.text);
12271 }
12272
12273 #[test]
12274 fn join_slivers_merges_a_gap_under_the_sliver_and_leaves_a_wide_one() {
12275 let (merged, joined) = join_slivers(&[(100, 50), (153, 47)]);
12276 assert_eq!((merged.clone(), joined), (vec![(100, 100)], 1), "a 3-frame gap is joined");
12277 let (kept, joined) = join_slivers(&[(0, 10), (20, 5)]);
12278 assert_eq!((kept, joined), (vec![(0, 10), (20, 5)], 0), "a 10-frame gap stays");
12279 let (touching, joined) = join_slivers(&[(0, 10), (10, 5)]);
12280 assert_eq!((touching, joined), (vec![(0, 15)], 0), "touching cuts merge without a count");
12281 }
12282
12283 #[test]
12284 fn a_linked_take_cut_across_its_lanes_stays_linked_on_both_sides() {
12285 let mut srv = open_asset("test_av.mp4");
12286 let r = ed(&mut srv, json!([{ "op": "remove_time", "at": "1s", "duration": "0.4s" }]));
12287 assert!(!r.is_error, "{}", r.text);
12288 assert!(!r.text.contains("detached"), "{}", r.text);
12289 let s = srv.session.as_ref().unwrap();
12290 let v = s.lane_clips(Lane::V1);
12291 let a = s.lane_clips(Lane::A1);
12292 // The take's piece after the cut is linked to its sound piece, and the piece before it to its own.
12293 let after_v = v.iter().find(|c| c.start >= 30).expect("picture after the cut");
12294 let after_a = a.iter().find(|c| c.start >= 30).expect("sound after the cut");
12295 assert!(after_v.link.is_some() && after_v.link == after_a.link, "tail pieces linked");
12296 let before_v = v.iter().find(|c| c.start < 30).expect("picture before the cut");
12297 let before_a = a.iter().find(|c| c.start < 30).expect("sound before the cut");
12298 assert!(before_v.link.is_some() && before_v.link == before_a.link, "head pieces linked");
12299 assert_ne!(before_v.link, after_v.link, "the two sides are separate takes");
12300 }
12301
12302 #[test]
12303 fn remove_time_ends_its_span_half_open() {
12304 let mut srv = open_asset("test_av.mp4");
12305 let fps = parse::session_fps(srv.session.as_ref().unwrap());
12306 let at = (1.0 * fps).round() as u32;
12307 let to = (2.0 * fps).round() as u32;
12308 let r = ed(&mut srv, json!([{ "op": "title_add", "at": format!("{to}f"), "duration": "1s", "text": "T" }]));
12309 assert!(!r.is_error, "{}", r.text);
12310 let r = ed(&mut srv, json!([{ "op": "remove_time", "at": format!("{at}f"), "duration": format!("{}f", to - at) }]));
12311 assert!(!r.is_error, "a title starting at the span's end is outside it: {}", r.text);
12312 }
12313
12314 /// Splits the 5 s take at 2 s, so V1 and A1 each hold the clips 0–2 s (A) and 2–5 s (B).
12315 fn two_takes() -> Server {
12316 let mut srv = open();
12317 let r = ed(&mut srv, json!([{ "op": "split", "at": "2s" }]));
12318 assert!(!r.is_error, "{}", r.text);
12319 srv
12320 }
12321
12322 /// `move {insert:true}` ripples the clip into place: the clip before it is pushed later to
12323 /// make room, the slot the clip left closes, and the timeline keeps its length. Its sound
12324 /// on A1 moves with it.
12325 #[test]
12326 fn move_insert_ripples_a_clip_earlier_and_keeps_the_length() {
12327 let mut srv = two_takes();
12328 let before = srv.session.as_ref().unwrap();
12329 let total = parse::session_end(before);
12330 let (a_in, b_in) = (before.lane_clips(Lane::V1)[0].in_frame, before.lane_clips(Lane::V1)[1].in_frame);
12331 let b_len = before.lane_clips(Lane::V1)[1].frames();
12332 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@60f", "at": "0s", "insert": true }]));
12333 assert!(!r.is_error, "{}", r.text);
12334 assert!(r.text.contains("insert to V1@"), "{}", r.text);
12335 let s = srv.session.as_ref().unwrap();
12336 let v = s.lane_clips(Lane::V1);
12337 assert_eq!(v.len(), 2, "{}", r.text);
12338 assert_eq!((v[0].start, v[0].frames(), v[0].in_frame), (0, b_len, b_in), "the moved clip leads: {}", r.text);
12339 assert_eq!((v[1].start, v[1].in_frame), (b_len, a_in), "the first clip follows: {}", r.text);
12340 assert_eq!(parse::session_end(s), total, "one clip out, one in: the length holds");
12341 let a1 = s.lane_clips(Lane::A1);
12342 assert_eq!(a1[0].start, 0, "the sound moved with its picture: {}", r.text);
12343 assert_eq!(srv.ledger.len(), 2, "split and move are one step each");
12344 }
12345
12346 /// A plain move into occupied space still refuses, and names insert:true as the way in.
12347 #[test]
12348 fn move_into_occupied_space_refuses_and_suggests_insert() {
12349 let mut srv = two_takes();
12350 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@60f", "at": "0s" }]));
12351 assert!(r.is_error && r.text.contains("insert:true"), "{}", r.text);
12352 assert_eq!(srv.session.as_ref().unwrap().lane_clips(Lane::V1)[1].start, 60, "a refusal changes nothing");
12353 }
12354
12355 /// An insert later than the timeline's end once the slot closes would leave a gap: it refuses.
12356 #[test]
12357 fn move_insert_later_past_the_end_refuses() {
12358 let mut srv = two_takes();
12359 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@0f", "at": "5s", "insert": true }]));
12360 assert!(r.is_error && r.text.contains("past the timeline end"), "{}", r.text);
12361 }
12362
12363 /// A title that runs past the last picture frame is named in the reply, with where the picture ends.
12364 #[test]
12365 fn a_title_past_the_picture_end_is_named_in_the_reply() {
12366 let mut srv = open();
12367 let r = ed(&mut srv, json!([{ "op": "title_add", "at": "4.5s", "duration": "2s", "text": "Late" }]));
12368 assert!(!r.is_error, "{}", r.text);
12369 assert!(r.text.contains("T1 runs") && r.text.contains("past the picture's end at"), "{}", r.text);
12370 }
12371
12372 /// insert_time reports each clip it split and the silence its time leaves on that lane.
12373 #[test]
12374 fn insert_time_names_the_clips_it_splits_and_the_silence_it_leaves() {
12375 let mut srv = open();
12376 let r = ed(&mut srv, json!([{ "op": "insert_time", "at": "1s", "duration": "2s" }]));
12377 assert!(!r.is_error, "{}", r.text);
12378 assert!(r.text.contains("A1 split"), "{}", r.text);
12379 // The same span the effects line names as the hole (3 decimals, one set of times).
12380 assert!(r.text.contains("2.000s of silence at 1.000–3.000s"), "{}", r.text);
12381 assert!(r.text.contains("hole left on A1 at 1.000–3.000s"), "{}", r.text);
12382 }
12383
12384 /// A lane shorter than the timeline is not a gap: close_gaps says so and names the lane that ends it.
12385 #[test]
12386 fn close_gaps_says_when_a_lane_is_short_of_the_timeline() {
12387 let mut srv = two_takes();
12388 let r = ed(&mut srv, json!([{ "op": "lift", "clip": "V1@60f" }]));
12389 assert!(!r.is_error, "{}", r.text);
12390 let r = ed(&mut srv, json!([{ "op": "close_gaps", "lane": "V1" }]));
12391 assert!(!r.is_error, "{}", r.text);
12392 assert!(r.text.contains("V1 has no gaps"), "{}", r.text);
12393 assert!(r.text.contains("V1 ends at 2.0s, 3.0s before the timeline end (A1)"), "{}", r.text);
12394 assert!(r.text.contains("trim A1 or extend V1 to reach it"), "{}", r.text);
12395 }
12396
12397 /// A swap that moves later clips names how far, and says how to keep them still.
12398 #[test]
12399 fn a_default_swap_says_how_to_keep_the_others_still() {
12400 // Two picture-only clips (a take refuses a swap): 2 s at 10 s and 3 s at 15 s, after the test take.
12401 let mut srv = open();
12402 let p1 = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "10s", "in": "0s", "out": "2s", "lane": "V1", "audio": false }]));
12403 assert!(!p1.is_error, "{}", p1.text);
12404 let p2 = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "15s", "in": "0s", "out": "3s", "lane": "V1", "audio": false }]));
12405 assert!(!p2.is_error, "{}", p2.text);
12406 let r = ed(&mut srv, json!([{ "op": "swap", "a": "V1@300f", "b": "V1@450f" }]));
12407 assert!(!r.is_error, "{}", r.text);
12408 assert!(r.text.contains("later clips moved by 30f") && r.text.contains("use ripple:false to keep everyone else in place"), "{}", r.text);
12409 assert!(!r.text.contains("ripple:false keeps"), "{}", r.text);
12410 }
12411
12412 /// `append until` on a source shorter than the gap says how many times it looped.
12413 #[test]
12414 fn append_until_says_how_many_times_it_looped() {
12415 let mut srv = open();
12416 let r = ed(&mut srv, json!([{ "op": "append", "source": 0, "until": "12s" }]));
12417 assert!(!r.is_error, "{}", r.text);
12418 assert!(r.text.contains("looped 2 times"), "{}", r.text);
12419 }
12420
12421 /// A 16:9 picture placed on a 9:16 canvas says it is letterboxed, and how to crop; a matching
12422 /// aspect says nothing.
12423 #[test]
12424 fn a_placement_on_another_aspect_names_the_fit() {
12425 let mut srv = open();
12426 srv.session.as_mut().unwrap().set_resolution(1080, 1920);
12427 let r = ed(&mut srv, json!([{ "op": "append", "source": 0 }]));
12428 assert!(!r.is_error, "{}", r.text);
12429 assert!(r.text.contains("fitted with letterbox") && r.text.contains("policy:\"fill\""), "{}", r.text);
12430 let mut same = open();
12431 let r = ed(&mut same, json!([{ "op": "append", "source": 0 }]));
12432 assert!(!r.text.contains("fitted with"), "{}", r.text);
12433 }
12434}
12435
12436#[cfg(test)]
12437mod round12_tests {
12438 use super::*;
12439 use crate::testutil::TestDir;
12440 use std::path::Path;
12441
12442 fn open() -> Server {
12443 engine::ao::set_silent_output();
12444 let p = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
12445 Server { session: Some(PlaybackSession::open(p).expect("open test asset")), ..Server::default() }
12446 }
12447
12448 fn ed(srv: &mut Server, ops: Value) -> Reply {
12449 run_edit(srv, &json!({ "ops": ops }))
12450 }
12451
12452 /// The cues a caption lane shows: (text, start, end) in seconds, in start order.
12453 fn cues(srv: &Server, lane: Lane) -> Vec<(String, f64, f64)> {
12454 srv.session
12455 .as_ref()
12456 .unwrap()
12457 .sub_lane_cues(lane)
12458 .into_iter()
12459 .map(|c| (c.text, c.start_us as f64 / 1e6, c.end_us as f64 / 1e6))
12460 .collect()
12461 }
12462
12463 /// A 5 s timeline of five 1 s clips on V1, and two caption lanes: S1 shows track 0 (four cues)
12464 /// and S2 shows track 1 (two cues), both placed at 0.
12465 fn two_caption_lanes(tag: &str) -> Server {
12466 let mut srv = open();
12467 let dir = TestDir::new(&format!("r12-two-lanes-{tag}"));
12468 let a = dir.path().join("a.srt");
12469 std::fs::write(
12470 &a,
12471 "1\n00:00:00,200 --> 00:00:00,800\na1\n\n2\n00:00:01,200 --> 00:00:01,800\na2\n\n\
12472 3\n00:00:02,500 --> 00:00:03,500\na3\n\n4\n00:00:04,200 --> 00:00:04,800\na4\n",
12473 )
12474 .unwrap();
12475 let b = dir.path().join("b.srt");
12476 std::fs::write(
12477 &b,
12478 "1\n00:00:01,300 --> 00:00:01,700\nb1\n\n2\n00:00:03,200 --> 00:00:03,600\nb2\n",
12479 )
12480 .unwrap();
12481 let r = ed(
12482 &mut srv,
12483 json!([
12484 { "op": "split", "at": "30f" },
12485 { "op": "split", "at": "60f" },
12486 { "op": "split", "at": "90f" },
12487 { "op": "split", "at": "120f" },
12488 { "op": "subtitles_import", "path": a.to_string_lossy() },
12489 { "op": "subtitles_import", "path": b.to_string_lossy() },
12490 { "op": "captions_place", "track": 0, "lane": "S1" },
12491 { "op": "captions_place", "track": 1, "lane": "S2" }
12492 ]),
12493 );
12494 assert!(!r.is_error, "{}", r.text);
12495 srv
12496 }
12497
12498 fn s1() -> Lane {
12499 Lane::new(LaneKind::Subtitle, 0)
12500 }
12501
12502 fn s2() -> Lane {
12503 Lane::new(LaneKind::Subtitle, 1)
12504 }
12505
12506 fn expect(list: &[(&str, f64, f64)]) -> Vec<(String, f64, f64)> {
12507 list.iter().map(|&(t, a, b)| (t.to_string(), a, b)).collect()
12508 }
12509
12510 /// A ripple move later (3 s) lifts the clip at 1 s: the captions over it travel with it, the
12511 /// others ripple with the slot, and undo restores every cue exactly.
12512 #[test]
12513 fn insert_move_later_carries_captions_over_the_picture_and_ripples_the_rest() {
12514 let mut srv = two_caption_lanes("later");
12515 let (before1, before2) = (cues(&srv, s1()), cues(&srv, s2()));
12516 assert_eq!(
12517 before1,
12518 expect(&[("a1", 0.2, 0.8), ("a2", 1.2, 1.8), ("a3", 2.5, 3.5), ("a4", 4.2, 4.8)])
12519 );
12520 assert_eq!(before2, expect(&[("b1", 1.3, 1.7), ("b2", 3.2, 3.6)]));
12521 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@30", "at": "3s", "insert": true, "split_captions": true }]));
12522 assert!(!r.is_error, "{}", r.text);
12523 assert!(r.text.contains("2 caption(s) moved with the clip"), "{}", r.text);
12524 assert_eq!(
12525 cues(&srv, s1()),
12526 expect(&[("a1", 0.2, 0.8), ("a3", 1.5, 2.5), ("a2", 3.2, 3.8), ("a4", 4.2, 4.8)])
12527 );
12528 assert_eq!(cues(&srv, s2()), expect(&[("b2", 2.2, 2.6), ("b1", 3.3, 3.7)]));
12529 let r = run_undo(&mut srv, &json!({}));
12530 assert!(!r.is_error, "{}", r.text);
12531 assert_eq!(cues(&srv, s1()), before1);
12532 assert_eq!(cues(&srv, s2()), before2);
12533 }
12534
12535 /// A ripple move earlier (to 1 s) lifts the last clip: its caption travels, the captions from
12536 /// 1 s up ripple later, and nothing is cut, duplicated or lost.
12537 #[test]
12538 fn insert_move_earlier_carries_captions_over_the_picture_and_ripples_the_rest() {
12539 let mut srv = two_caption_lanes("earlier");
12540 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@120", "at": "1s", "insert": true, "split_captions": true }]));
12541 assert!(!r.is_error, "{}", r.text);
12542 assert!(r.text.contains("1 caption(s) moved with the clip"), "{}", r.text);
12543 assert_eq!(
12544 cues(&srv, s1()),
12545 expect(&[("a1", 0.2, 0.8), ("a4", 1.2, 1.8), ("a2", 2.2, 2.8), ("a3", 3.5, 4.5)])
12546 );
12547 assert_eq!(cues(&srv, s2()), expect(&[("b1", 2.3, 2.7), ("b2", 4.2, 4.6)]));
12548 }
12549
12550 /// Two-second V1 clip at 0 with its take, and a narration on A2 over 0–4 s (spanning the change).
12551 fn speed_setup(narration_out: &str) -> Server {
12552 let mut srv = open();
12553 let r = ed(
12554 &mut srv,
12555 json!([
12556 { "op": "split", "at": "60f" },
12557 { "op": "lane_add", "kind": "audio" },
12558 { "op": "place", "source": 0, "at": "0s", "in": "0s", "out": narration_out, "lane": "A2" }
12559 ]),
12560 );
12561 assert!(!r.is_error, "{}", r.text);
12562 srv
12563 }
12564
12565 /// Speed (bug 2): a shorter clip with ripple leaves a narration on an out-of-scope lane alone and
12566 /// says so; an explicit scope naming that lane refuses, naming it, and changes nothing.
12567 #[test]
12568 fn speed_ripple_leaves_a_spanning_clip_on_another_lane_and_says_so() {
12569 let mut srv = speed_setup("2s");
12570 let a2 = Lane::new(LaneKind::Audio, 1);
12571 let before = srv.session.as_ref().unwrap().lane_clips(a2).to_vec();
12572 let r = ed(&mut srv, json!([{ "op": "speed", "clip": "V1@0", "x": 2, "ripple": true }]));
12573 assert!(!r.is_error, "{}", r.text);
12574 assert!(r.text.contains("A2@0 spans the change and was left in place"), "{}", r.text);
12575 assert!(r.text.contains("(2.000s → 1.000s)"), "the length change is named: {}", r.text);
12576 assert!(r.text.contains("later items moved 30f (1.000s) earlier"), "{}", r.text);
12577 let after = srv.session.as_ref().unwrap().lane_clips(a2).to_vec();
12578 assert_eq!(
12579 after.iter().map(|c| (c.start, c.in_frame, c.out_frame)).collect::<Vec<_>>(),
12580 before.iter().map(|c| (c.start, c.in_frame, c.out_frame)).collect::<Vec<_>>(),
12581 "the narration is not truncated"
12582 );
12583 // The later V1 clip moved up by the 30f the change closed.
12584 assert_eq!(srv.session.as_ref().unwrap().lane_clips(Lane::V1)[1].start, 30);
12585 }
12586
12587 #[test]
12588 fn speed_ripple_refuses_a_spanning_clip_on_a_named_lane_and_changes_nothing() {
12589 let mut srv = speed_setup("2s");
12590 let depth = srv.ledger.len();
12591 let r = ed(
12592 &mut srv,
12593 json!([{ "op": "speed", "clip": "V1@0", "x": 2, "ripple": true, "lanes": ["V1", "A1", "A2"] }]),
12594 );
12595 assert!(r.is_error, "{}", r.text);
12596 assert!(r.text.contains("A2@0 spans the change"), "{}", r.text);
12597 assert_eq!(srv.ledger.len(), depth);
12598 assert_eq!(srv.session.as_ref().unwrap().lane_clips(Lane::new(LaneKind::Audio, 1))[0].frames(), 60);
12599 }
12600
12601 /// Lengthening (bug 2, same rule): a narration over the point the room opens is left in place
12602 /// by default, and an explicit scope naming its lane refuses.
12603 #[test]
12604 fn speed_ripple_lengthening_follows_the_same_spanning_rule() {
12605 let mut srv = speed_setup("4s");
12606 let r = ed(&mut srv, json!([{ "op": "speed", "clip": "V1@0", "x": 0.5, "ripple": true }]));
12607 assert!(!r.is_error, "{}", r.text);
12608 assert!(r.text.contains("A2@0 spans the change and was left in place"), "{}", r.text);
12609 let mut srv = speed_setup("4s");
12610 let r = ed(
12611 &mut srv,
12612 json!([{ "op": "speed", "clip": "V1@0", "x": 0.5, "ripple": true, "lanes": ["V1", "A1", "A2"] }]),
12613 );
12614 assert!(r.is_error && r.text.contains("A2@0 spans the change"), "{}", r.text);
12615 }
12616
12617 /// Locked lanes (bug 5): the default scope skips a locked caption lane with a note; an explicit
12618 /// `lanes` naming it refuses.
12619 #[test]
12620 fn default_scope_skips_a_locked_caption_lane_with_a_note() {
12621 let mut srv = two_caption_lanes("locked");
12622 srv.session.as_mut().unwrap().set_lane_locked(s1(), true);
12623 let before = cues(&srv, s1());
12624 let r = ed(&mut srv, json!([{ "op": "insert_time", "at": "1.5s", "duration": "1s" }]));
12625 assert!(!r.is_error, "{}", r.text);
12626 assert!(r.text.contains("skipped locked S1"), "{}", r.text);
12627 assert_eq!(cues(&srv, s1()), before, "the locked lane's cues stay put");
12628 let r = ed(&mut srv, json!([{ "op": "cut_regions", "regions": [["1.5s", "2.5s"]] }]));
12629 assert!(!r.is_error, "{}", r.text);
12630 assert!(r.text.contains("skipped locked S1"), "{}", r.text);
12631 let r = ed(&mut srv, json!([{ "op": "insert_time", "at": "1.5s", "duration": "1s", "lanes": ["V1", "S1"] }]));
12632 assert!(r.is_error && r.text.contains("S1 is locked"), "{}", r.text);
12633 }
12634
12635 /// Dirty state (bug 4): a failed batch leaves a clean project clean.
12636 #[test]
12637 fn a_failed_batch_leaves_a_clean_project_clean() {
12638 let mut srv = open();
12639 let s = srv.session.as_ref().unwrap();
12640 srv.saved_depth = Some(s.undo_depth());
12641 srv.saved_pushes = Some(s.history_pushes());
12642 srv.saved_sources = Some(s.sources().len());
12643 let r = ed(
12644 &mut srv,
12645 json!([
12646 { "op": "split", "at": "1s" },
12647 { "op": "trim", "clip": "V1@999999f", "edge": "out", "to": "1f" }
12648 ]),
12649 );
12650 assert!(r.is_error, "{}", r.text);
12651 assert!(!crate::tools::project::dirty(&srv), "a rolled-back batch is not a change");
12652 }
12653
12654 /// Freeze (bug 3): a dry run writes no still and adds no source; a failed batch that froze takes
12655 /// the still's source back.
12656 #[test]
12657 fn freeze_dry_run_writes_nothing_and_a_failed_batch_takes_its_source_back() {
12658 let dir = TestDir::new("r12-freeze");
12659 let mut srv = open();
12660 srv.path = Some(dir.join("cut.edith"));
12661 let s = srv.session.as_ref().unwrap();
12662 srv.saved_depth = Some(s.undo_depth());
12663 srv.saved_pushes = Some(s.history_pushes());
12664 srv.saved_sources = Some(s.sources().len());
12665 let sources = s.sources().len();
12666 let r = run_edit(
12667 &mut srv,
12668 &json!({ "ops": [{ "op": "freeze", "at": "1s", "duration": "1s" }], "dry_run": true }),
12669 );
12670 assert!(!r.is_error, "{}", r.text);
12671 assert_eq!(srv.session.as_ref().unwrap().sources().len(), sources, "a dry run adds no source");
12672 assert!(!dir.join("freeze").exists(), "a dry run writes no still");
12673 assert!(!crate::tools::project::dirty(&srv));
12674 let r = ed(
12675 &mut srv,
12676 json!([
12677 { "op": "freeze", "at": "1s", "duration": "1s" },
12678 { "op": "trim", "clip": "V1@999999f", "edge": "out", "to": "1f" }
12679 ]),
12680 );
12681 assert!(r.is_error, "{}", r.text);
12682 assert_eq!(srv.session.as_ref().unwrap().sources().len(), sources, "the failed batch took its still back");
12683 assert!(!crate::tools::project::dirty(&srv));
12684 }
12685
12686 /// Trim (bug 7): a source end that meets the next clip exactly is named for that clip.
12687 #[test]
12688 fn trim_names_the_neighbour_a_source_end_meets() {
12689 let mut srv = open();
12690 let r = ed(&mut srv, json!([{ "op": "append", "source": 0 }]));
12691 assert!(!r.is_error, "{}", r.text);
12692 // The first clip's source ends at 150f, where the appended clip starts.
12693 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "V1@0", "edge": "out", "to": "200f", "scope": "clip" }]));
12694 assert!(!r.is_error, "{}", r.text);
12695 assert!(r.text.contains("clamped where it meets V1@150"), "{}", r.text);
12696 assert!(!r.text.contains("source's end"), "{}", r.text);
12697 }
12698
12699 /// Placed source ranges are source time and timeline positions are timeline frames (bug 6).
12700 #[test]
12701 fn place_labels_source_time_and_timeline_frames() {
12702 let mut srv = open();
12703 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "in": "0s", "out": "2s", "at": "5s", "lane": "V1" }]));
12704 assert!(!r.is_error, "{}", r.text);
12705 assert!(r.text.contains("src 0.000s–2.000s at timeline 150f"), "{}", r.text);
12706 }
12707
12708 /// A sliver hole closed by a cut names the clip that moved back (bug 6, find_words path).
12709 #[test]
12710 fn closing_a_sliver_hole_names_the_clip_that_moved() {
12711 let mut srv = open();
12712 let r = ed(
12713 &mut srv,
12714 json!([
12715 { "op": "split", "at": "60f" },
12716 { "op": "trim", "clip": "V1@0", "edge": "out", "to": "58f", "scope": "clip" }
12717 ]),
12718 );
12719 assert!(!r.is_error, "{}", r.text);
12720 let r = ed(&mut srv, json!([{ "op": "cut_regions", "regions": [["100f", "110f"]] }]));
12721 assert!(!r.is_error, "{}", r.text);
12722 assert!(r.text.contains("closed 1 hole(s)"), "{}", r.text);
12723 assert!(r.text.contains("by trimming the clip beside each"), "{}", r.text);
12724 assert!(!r.text.contains("moving V1@60"), "{}", r.text);
12725 }
12726}
12727
12728#[cfg(test)]
12729mod round13_tests {
12730 use super::*;
12731 use crate::testutil::TestDir;
12732 use std::path::Path;
12733
12734 fn asset(name: &str) -> PathBuf {
12735 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
12736 }
12737
12738 /// The 5 s test_av.mp4 on a timeline of its own: V1 holds one 5 s clip, A1 its sound.
12739 fn open() -> Server {
12740 engine::ao::set_silent_output();
12741 Server { session: Some(PlaybackSession::open(asset("test_av.mp4")).expect("open test asset")), ..Server::default() }
12742 }
12743
12744 /// An empty timeline with test_av.mp4 imported as src:0 (nothing placed yet).
12745 fn empty_av() -> Server {
12746 engine::ao::set_silent_output();
12747 let mut sess = PlaybackSession::empty(1280, 720, 30.0).expect("empty session");
12748 sess.import(&asset("test_av.mp4")).expect("import test asset");
12749 Server { session: Some(sess), ..Server::default() }
12750 }
12751
12752 fn ed(srv: &mut Server, ops: Value) -> Reply {
12753 run_edit(srv, &json!({ "ops": ops }))
12754 }
12755
12756 fn s1() -> Lane {
12757 Lane::new(LaneKind::Subtitle, 0)
12758 }
12759
12760 fn s2() -> Lane {
12761 Lane::new(LaneKind::Subtitle, 1)
12762 }
12763
12764 /// The V1 clips as (start, frames), for asserting placements.
12765 fn v1_spans(srv: &Server, lane: Lane) -> Vec<(u32, u32)> {
12766 srv.session.as_ref().unwrap().lane_clips(lane).iter().map(|c| (c.start, c.frames())).collect()
12767 }
12768
12769 /// Two tracks: track 0 is a cue 0.5–2.5 s ("x spans a b") and track 1 a cue 1.0–2.2 s ("b one").
12770 fn write_srts(dir: &TestDir) -> (PathBuf, PathBuf) {
12771 let a = dir.path().join("a.srt");
12772 std::fs::write(&a, "1\n00:00:00,500 --> 00:00:02,500\nx spans a b\n").unwrap();
12773 let b = dir.path().join("b.srt");
12774 std::fs::write(&b, "1\n00:00:01,000 --> 00:00:02,200\nb one\n").unwrap();
12775 (a, b)
12776 }
12777
12778 /// Two 2 s clips on V1 (split at 2 s, 60f), the 5 s picture's second part 3 s long, and a cue
12779 /// over the 2 s edge on S1 (track 0), placed at 0.
12780 fn captioned(dir: &TestDir, two_lanes: bool) -> Server {
12781 let mut srv = open();
12782 let (a, b) = write_srts(dir);
12783 let mut ops = vec![
12784 json!({ "op": "split", "at": "60f" }),
12785 json!({ "op": "subtitles_import", "path": a.to_string_lossy() }),
12786 json!({ "op": "captions_place", "track": 0, "lane": "S1", "at": "0f" }),
12787 ];
12788 if two_lanes {
12789 ops.push(json!({ "op": "subtitles_import", "path": b.to_string_lossy() }));
12790 ops.push(json!({ "op": "captions_place", "track": 1, "lane": "S2", "at": "0f" }));
12791 }
12792 let r = ed(&mut srv, Value::Array(ops));
12793 assert!(!r.is_error, "{}", r.text);
12794 srv
12795 }
12796
12797 fn sub_count(srv: &Server, lane: Lane) -> usize {
12798 srv.session.as_ref().unwrap().sub_lane(lane).len()
12799 }
12800
12801 #[test]
12802 fn insert_move_refuses_a_caption_spanning_the_edge_by_name() {
12803 let dir = TestDir::new("r13-cap-refuse");
12804 let mut srv = captioned(&dir, false);
12805 let before = (v1_spans(&srv, Lane::V1), sub_count(&srv, s1()));
12806 // Moving the later clip earlier: its old edges are 2 s and 5 s, and the caption crosses 2 s.
12807 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@60", "at": "0f", "insert": true }]));
12808 assert!(r.is_error, "{}", r.text);
12809 assert!(r.text.contains("cue 'x spans a b' (S1 0.5s–2.5s) crosses the edge of the moved clip"), "{}", r.text);
12810 assert!(r.text.contains("pass split_captions:true to split it"), "{}", r.text);
12811 // A refusal changes nothing, captions included.
12812 assert_eq!((v1_spans(&srv, Lane::V1), sub_count(&srv, s1())), before);
12813 }
12814
12815 #[test]
12816 fn insert_move_split_captions_splits_and_reports_both_halves_then_undoes_exactly() {
12817 let dir = TestDir::new("r13-cap-split");
12818 let mut srv = captioned(&dir, false);
12819 let before = (v1_spans(&srv, Lane::V1), sub_count(&srv, s1()));
12820 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@60", "at": "0f", "insert": true, "split_captions": true }]));
12821 assert!(!r.is_error, "{}", r.text);
12822 assert!(r.text.contains("captions split:"), "{}", r.text);
12823 assert!(r.text.contains("split at 2.0s into S1 0.0s–2.0s and S1 2.0s–2.5s"), "{}", r.text);
12824 // The cue is in two placements now, not three: one split at the edge.
12825 assert_eq!(sub_count(&srv, s1()), 2);
12826 assert_eq!(v1_spans(&srv, Lane::V1), vec![(0, 90), (90, 60)]);
12827 // Undo returns the clips and the single caption exactly.
12828 let u = run_undo(&mut srv, &json!({}));
12829 assert!(!u.is_error, "{}", u.text);
12830 assert_eq!((v1_spans(&srv, Lane::V1), sub_count(&srv, s1())), before);
12831 }
12832
12833 #[test]
12834 fn insert_move_later_refuses_then_splits_the_other_direction() {
12835 let dir = TestDir::new("r13-cap-later");
12836 let mut srv = captioned(&dir, false);
12837 // The first clip moved later: its old edge at 2 s is where the caption spans.
12838 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@0", "at": "3s", "insert": true }]));
12839 assert!(r.is_error && r.text.contains("crosses the edge of the moved clip"), "{}", r.text);
12840 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@0", "at": "3s", "insert": true, "split_captions": true }]));
12841 assert!(!r.is_error, "{}", r.text);
12842 assert!(r.text.contains("captions split:"), "{}", r.text);
12843 assert!(sub_count(&srv, s1()) >= 2);
12844 }
12845
12846 #[test]
12847 fn insert_move_split_names_each_caption_lane_it_splits() {
12848 let dir = TestDir::new("r13-cap-two-lanes");
12849 let mut srv = captioned(&dir, true);
12850 let before = (v1_spans(&srv, Lane::V1), sub_count(&srv, s1()), sub_count(&srv, s2()));
12851 // Two caption lanes: refused by the first straddling placement, S1 here.
12852 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@60", "at": "0f", "insert": true }]));
12853 assert!(r.is_error && r.text.contains("(S1 "), "{}", r.text);
12854 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@60", "at": "0f", "insert": true, "split_captions": true }]));
12855 assert!(!r.is_error, "{}", r.text);
12856 assert!(r.text.contains("'b one' (S2 "), "{}", r.text);
12857 assert!(r.text.contains("'x spans a b' (S1 "), "{}", r.text);
12858 let u = run_undo(&mut srv, &json!({}));
12859 assert!(!u.is_error, "{}", u.text);
12860 assert_eq!((v1_spans(&srv, Lane::V1), sub_count(&srv, s1()), sub_count(&srv, s2())), before);
12861 }
12862
12863 /// Clips of 1 s, 1 s and 2 s on V1 (audio off), with the middle one lifted: a 1 s hole at 1 s.
12864 fn holed() -> Server {
12865 let mut srv = empty_av();
12866 let r = ed(
12867 &mut srv,
12868 json!([
12869 { "op": "append", "source": "src:0", "in": "0s", "out": "1s", "lane": "V1", "audio": false },
12870 { "op": "append", "source": "src:0", "in": "1s", "out": "2s", "lane": "V1", "audio": false },
12871 { "op": "append", "source": "src:0", "in": "2s", "out": "4s", "lane": "V1", "audio": false },
12872 { "op": "lift", "clip": "V1@30" }
12873 ]),
12874 );
12875 assert!(!r.is_error, "{}", r.text);
12876 srv
12877 }
12878
12879 #[test]
12880 fn stretched_place_into_a_hole_checks_the_stretched_span() {
12881 let mut srv = holed();
12882 // A 2 s source fitted into 30f: it fills the 1 s hole and does not overlap the clip after it.
12883 let r = ed(
12884 &mut srv,
12885 json!([{ "op": "place", "source": "src:0", "lane": "V1", "at": "1s", "in": "0s", "out": "2s", "length": "30f", "stretch": true, "audio": false }]),
12886 );
12887 assert!(!r.is_error, "{}", r.text);
12888 assert!(r.text.contains("stretched ×2"), "{}", r.text);
12889 assert_eq!(v1_spans(&srv, Lane::V1), vec![(0, 30), (30, 30), (60, 60)]);
12890 }
12891
12892 #[test]
12893 fn unstretched_place_into_the_same_hole_still_overlaps() {
12894 let mut srv = holed();
12895 let r = ed(
12896 &mut srv,
12897 json!([{ "op": "place", "source": "src:0", "lane": "V1", "at": "1s", "in": "0s", "out": "2s", "audio": false }]),
12898 );
12899 assert!(r.is_error && r.text.contains("would overwrite V1@60"), "{}", r.text);
12900 }
12901
12902 #[test]
12903 fn a_still_takes_length_as_its_duration_and_a_missing_source_is_named() {
12904 let mut sess = PlaybackSession::empty(1280, 720, 30.0).expect("empty session");
12905 sess.import(&asset("test_av.mp4")).expect("import");
12906 sess.import(&asset("test_still.png")).expect("import still");
12907 let mut srv = Server { session: Some(sess), ..Server::default() };
12908 let r = ed(&mut srv, json!([{ "op": "place", "source": "src:1", "lane": "V1", "at": "0s", "length": "5.267s" }]));
12909 assert!(!r.is_error, "{}", r.text);
12910 assert_eq!(v1_spans(&srv, Lane::V1), vec![(0, 158)]);
12911 let r = ed(&mut srv, json!([{ "op": "place", "source": "src:4", "at": "0s" }]));
12912 assert!(r.is_error && r.text.contains("there is no src:4 (media_list shows src:0–1)"), "{}", r.text);
12913 }
12914
12915 #[test]
12916 fn trim_clamp_names_the_real_neighbour_not_the_linked_partner() {
12917 let mut srv = empty_av();
12918 let r = ed(
12919 &mut srv,
12920 json!([
12921 { "op": "append", "source": "src:0", "in": "0s", "out": "1.5s", "lane": "V1", "audio": false },
12922 // A pair at 1.5 s: V1@45 with A1@45 as its linked sound, its source reaching back 1 s.
12923 { "op": "place", "source": "src:0", "lane": "V1", "at": "1.5s", "in": "1s", "out": "3s" }
12924 ]),
12925 );
12926 assert!(!r.is_error, "{}", r.text);
12927 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "V1@45", "edge": "in", "to": "0.5s" }]));
12928 assert!(r.text.contains("clamped where it meets V1@0"), "{}", r.text);
12929 assert!(!r.text.contains("A1@45") && !r.text.contains("meets V1@45"), "{}", r.text);
12930 }
12931
12932 /// An in edge trimmed later leaves a hole before the clip: the reply offers the close in one line.
12933 /// An out edge trimmed shorter leaves none, so it gets no offer.
12934 #[test]
12935 fn an_in_edge_that_moves_later_offers_the_close_in_one_line() {
12936 let mut srv = empty_av();
12937 let r = ed(
12938 &mut srv,
12939 json!([{ "op": "append", "source": "src:0", "in": "0s", "out": "3s", "lane": "V1", "audio": false }]),
12940 );
12941 assert!(!r.is_error, "{}", r.text);
12942 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "V1@0", "edge": "in", "to": "1s" }]));
12943 assert!(!r.is_error, "{}", r.text);
12944 assert!(r.text.contains("the in edge leaves a hole before the clip"), "{}", r.text);
12945 assert!(r.text.contains("close_gaps {lane:\"V1\"}"), "{}", r.text);
12946
12947 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "V1@30", "edge": "out", "to": "1.5s" }]));
12948 assert!(!r.is_error, "{}", r.text);
12949 assert!(!r.text.contains("leaves a hole") && !r.text.contains("close_gaps"), "{}", r.text);
12950 }
12951
12952 /// The hint is named only for an in edge that moved later, and names the lane it trims.
12953 #[test]
12954 fn the_in_edge_hint_needs_a_later_move() {
12955 let v1 = vec!["V1".to_string()];
12956 let both = vec!["V1".to_string(), "A1".to_string()];
12957 assert_eq!(
12958 in_edge_hole_hint(Edge::Start, Some(0), Some(30), &v1).as_deref(),
12959 Some("the in edge leaves a hole before the clip; to pull later clips left over it, close_gaps {lane:\"V1\"} (each closes every gap on its lane)")
12960 );
12961 // A take trimmed together names each of its lanes.
12962 let took = in_edge_hole_hint(Edge::Start, Some(0), Some(30), &both).unwrap_or_default();
12963 assert!(took.ends_with("close_gaps {lane:\"V1\"} and close_gaps {lane:\"A1\"} (each closes every gap on its lane)"), "{took}");
12964 assert_eq!(in_edge_hole_hint(Edge::Start, Some(30), Some(0), &v1), None);
12965 assert_eq!(in_edge_hole_hint(Edge::End, Some(30), Some(60), &v1), None);
12966 assert_eq!(in_edge_hole_hint(Edge::Start, None, Some(30), &v1), None);
12967 }
12968
12969 #[test]
12970 fn a_failed_batch_with_a_freeze_leaves_no_still_behind() {
12971 let dir = TestDir::new("r13-freeze-rollback");
12972 let mut srv = open();
12973 srv.path = Some(dir.join("cut.edith"));
12974 // A still already on disk from an earlier batch is never removed by a refused one.
12975 std::fs::create_dir_all(dir.join("freeze")).unwrap();
12976 std::fs::write(dir.join("freeze").join("keep.png"), b"old").unwrap();
12977 let r = ed(
12978 &mut srv,
12979 json!([
12980 { "op": "freeze", "at": "1s", "duration": "1s" },
12981 { "op": "trim", "clip": "V1@999999f", "edge": "out", "to": "1f" }
12982 ]),
12983 );
12984 assert!(r.is_error, "{}", r.text);
12985 let names: Vec<String> = std::fs::read_dir(dir.join("freeze")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
12986 assert_eq!(names, vec!["keep.png".to_string()], "only the file that was there stays");
12987 }
12988
12989 #[test]
12990 fn a_refused_freeze_in_a_fresh_folder_removes_the_folder_it_made() {
12991 let dir = TestDir::new("r13-freeze-fresh");
12992 let mut srv = open();
12993 srv.path = Some(dir.join("cut.edith"));
12994 let r = ed(
12995 &mut srv,
12996 json!([
12997 { "op": "freeze", "at": "1s", "duration": "1s" },
12998 { "op": "trim", "clip": "V1@999999f", "edge": "out", "to": "1f" }
12999 ]),
13000 );
13001 assert!(r.is_error, "{}", r.text);
13002 assert!(!dir.join("freeze").exists(), "a refused batch leaves no freeze folder it made");
13003 }
13004
13005 #[test]
13006 fn a_picture_lane_past_the_picture_end_is_named_after_a_ripple() {
13007 let mut srv = open();
13008 let r = ed(
13009 &mut srv,
13010 json!([
13011 { "op": "split", "at": "30f" },
13012 { "op": "lane_add", "kind": "video" },
13013 { "op": "place", "source": "src:0", "lane": "V2", "at": "0s", "in": "0s", "out": "5s", "audio": false },
13014 { "op": "ripple_delete", "clip": "V1@0" }
13015 ]),
13016 );
13017 assert!(!r.is_error, "{}", r.text);
13018 assert!(r.text.contains("V2 runs 1.0s past the picture's end at 4.0s"), "{}", r.text);
13019 }
13020
13021 #[test]
13022 fn copy_look_copies_colour_to_the_targets_as_one_undo_step() {
13023 let mut srv = open();
13024 let r = ed(
13025 &mut srv,
13026 json!([
13027 { "op": "lane_add", "kind": "video" },
13028 { "op": "place", "source": "src:0", "lane": "V2", "at": "0s", "in": "0s", "out": "5s", "audio": false },
13029 { "op": "color", "clip": "V1@0", "brightness": 0.3 }
13030 ]),
13031 );
13032 assert!(!r.is_error, "{}", r.text);
13033 let v2 = Lane::new(LaneKind::Video, 1);
13034 assert!(srv.session.as_ref().unwrap().color_of(v2, 0).is_none());
13035 let r = ed(&mut srv, json!([{ "op": "copy_look", "from": "V1@0", "to": ["V2@0"] }]));
13036 assert!(!r.is_error, "{}", r.text);
13037 assert!(r.text.contains("copy_look V1@0 → V2@0: color copied"), "{}", r.text);
13038 let s = srv.session.as_ref().unwrap();
13039 assert_eq!(s.color_of(v2, 0).copied(), s.color_of(Lane::V1, 0).copied());
13040 assert!(s.color_of(v2, 0).is_some());
13041 let u = run_undo(&mut srv, &json!({}));
13042 assert!(!u.is_error, "{}", u.text);
13043 assert!(srv.session.as_ref().unwrap().color_of(v2, 0).is_none(), "one undo takes the whole copy back");
13044 }
13045
13046 #[test]
13047 fn copy_look_what_and_targets_are_checked() {
13048 let mut srv = open();
13049 let r = ed(&mut srv, json!([{ "op": "lane_add", "kind": "video" }, { "op": "place", "source": "src:0", "lane": "V2", "at": "0s", "in": "0s", "out": "5s", "audio": false }]));
13050 assert!(!r.is_error, "{}", r.text);
13051 // Eq comes from a sound clip: a picture clip as the source is refused by name.
13052 let r = ed(&mut srv, json!([{ "op": "copy_look", "from": "V1@0", "to": ["V2@0"], "what": ["eq"] }]));
13053 assert!(r.is_error && r.text.contains("eq comes from a sound clip"), "{}", r.text);
13054 // A bad part is named; so is a missing target.
13055 let r = ed(&mut srv, json!([{ "op": "copy_look", "from": "V1@0", "to": ["V2@0"], "what": ["sparkle"] }]));
13056 assert!(r.is_error && r.text.contains("sparkle"), "{}", r.text);
13057 let r = ed(&mut srv, json!([{ "op": "copy_look", "from": "V1@0" }]));
13058 assert!(r.is_error && r.text.contains("to_lane"), "{}", r.text);
13059 // Transform and to_lane: the source's placement goes to every clip on the lane but itself.
13060 let r = ed(&mut srv, json!([{ "op": "transform", "clip": "V1@0", "scale": 0.5 }]));
13061 assert!(!r.is_error, "{}", r.text);
13062 let r = ed(&mut srv, json!([{ "op": "copy_look", "from": "V1@0", "to_lane": "V2", "what": ["transform"] }]));
13063 assert!(!r.is_error, "{}", r.text);
13064 assert!(r.text.contains("V2@0"), "{}", r.text);
13065 let s = srv.session.as_ref().unwrap();
13066 assert_eq!(s.transform_of(Lane::new(LaneKind::Video, 1), 0).copied(), s.transform_of(Lane::V1, 0).copied());
13067 }
13068
13069 #[test]
13070 fn copy_look_carries_effects_speed_and_gain() {
13071 let mut srv = open();
13072 let r = ed(
13073 &mut srv,
13074 json!([
13075 { "op": "lane_add", "kind": "video" },
13076 { "op": "place", "source": "src:0", "lane": "V2", "at": "0s", "in": "0s", "out": "2s", "audio": false },
13077 { "op": "lane_add", "kind": "audio" },
13078 { "op": "place", "source": "src:0", "lane": "A2", "at": "0s", "in": "0s", "out": "2s" },
13079 { "op": "speed", "clip": "V1@0", "x": 2, "ripple": false },
13080 { "op": "gain", "clip": "A1@0", "db": -6 }
13081 ]),
13082 );
13083 assert!(!r.is_error, "{}", r.text);
13084 let fx = engine::effects::Effect::new(engine::effects::EffectKind::Vignette);
13085 assert!(srv.session.as_mut().unwrap().set_effects(Lane::V1, 0, vec![fx]));
13086 let v2 = Lane::new(LaneKind::Video, 1);
13087 let a2 = Lane::new(LaneKind::Audio, 1);
13088 let r = ed(&mut srv, json!([{ "op": "copy_look", "from": "V1@0", "to": ["V2@0"], "what": ["effects", "speed"] }]));
13089 assert!(!r.is_error && r.text.contains("effects, speed copied"), "{}", r.text);
13090 let s = srv.session.as_ref().unwrap();
13091 assert_eq!(s.effects_of(v2, 0), s.effects_of(Lane::V1, 0));
13092 assert_eq!(s.speed_of(v2, 0), s.speed_of(Lane::V1, 0));
13093 let r = ed(&mut srv, json!([{ "op": "copy_look", "from": "A1@0", "to": ["A2@0"], "what": ["gain"] }]));
13094 assert!(!r.is_error && r.text.contains("gain copied"), "{}", r.text);
13095 let s = srv.session.as_ref().unwrap();
13096 assert_eq!(s.clip_gain_of(a2, 0), s.clip_gain_of(Lane::A1, 0));
13097 assert_ne!(s.clip_gain_of(a2, 0), Some(0.));
13098 // The same copy again changes nothing; gain from a picture clip is refused by name.
13099 let r = ed(&mut srv, json!([{ "op": "copy_look", "from": "A1@0", "to": ["A2@0"], "what": ["gain"] }]));
13100 assert!(r.text.contains("nothing to copy"), "{}", r.text);
13101 let r = ed(&mut srv, json!([{ "op": "copy_look", "from": "V1@0", "to": ["V2@0"], "what": ["gain"] }]));
13102 assert!(r.is_error && r.text.contains("gain"), "{}", r.text);
13103 }
13104
13105 #[test]
13106 fn replace_overwrites_the_clip_and_its_sound_keeping_place_and_length() {
13107 let mut srv = open();
13108 let r = ed(&mut srv, json!([{ "op": "split", "at": "2s" }]));
13109 assert!(!r.is_error, "{}", r.text);
13110 let (len, in_before) = {
13111 let c = &srv.session.as_ref().unwrap().lane_clips(Lane::V1)[1];
13112 (c.frames(), c.in_frame)
13113 };
13114 let r = ed(&mut srv, json!([{ "op": "replace", "clip": "V1@60", "source": "src:0", "in": "0s" }]));
13115 assert!(!r.is_error, "{}", r.text);
13116 assert!(r.text.contains("replace V1@60 with src:0") && r.text.contains("V1@60 + A1@60"), "{}", r.text);
13117 let s = srv.session.as_ref().unwrap();
13118 for lane in [Lane::V1, Lane::A1] {
13119 let c = &s.lane_clips(lane)[1];
13120 assert_eq!((c.start, c.frames(), c.in_frame), (60, len, 0), "{lane:?}");
13121 }
13122 assert_ne!(in_before, 0);
13123 assert_eq!(s.lane_clips(Lane::V1).len(), 2);
13124 let u = run_undo(&mut srv, &json!({}));
13125 assert!(!u.is_error, "{}", u.text);
13126 assert_eq!(srv.session.as_ref().unwrap().lane_clips(Lane::V1)[1].in_frame, in_before);
13127 // A range that runs out of source is refused by name.
13128 let r = ed(&mut srv, json!([{ "op": "replace", "clip": "V1@0", "source": "src:0", "in": "4s" }]));
13129 assert!(r.is_error && r.text.contains("frames after its start"), "{}", r.text);
13130 }
13131
13132 #[test]
13133 fn nudge_moves_a_take_whole_and_refuses_when_a_neighbour_is_in_the_way() {
13134 let mut srv = open();
13135 let r = ed(&mut srv, json!([{ "op": "split", "at": "2s" }]));
13136 assert!(!r.is_error, "{}", r.text);
13137 let r = ed(&mut srv, json!([{ "op": "nudge", "clips": ["V1@60"], "by": "+10f" }]));
13138 assert!(!r.is_error && r.text.contains("now V1@70"), "{}", r.text);
13139 let s = srv.session.as_ref().unwrap();
13140 assert_eq!(s.lane_clips(Lane::V1)[1].start, 70);
13141 assert_eq!(s.lane_clips(Lane::A1)[1].start, 70, "the linked sound moves with it");
13142 let r = ed(&mut srv, json!([{ "op": "nudge", "clips": ["V1@0"], "by": "+20f" }]));
13143 assert!(!r.is_error && r.text.contains("by +10f") && r.text.contains("stopped short of +20f"), "{}", r.text);
13144 let r = ed(&mut srv, json!([{ "op": "nudge", "clips": ["V1@10"], "by": "+5f" }]));
13145 assert!(r.is_error && r.text.contains("refused"), "{}", r.text);
13146 let r = ed(&mut srv, json!([{ "op": "nudge", "clips": ["V1@10"] }]));
13147 assert!(r.is_error && r.text.contains("`by`"), "{}", r.text);
13148 }
13149
13150 #[test]
13151 fn a_swap_without_ripple_says_where_each_clip_now_starts() {
13152 // Two picture-only 2 s clips (a clip in a take is not swapped apart, so no sound here).
13153 let mut srv = empty_av();
13154 let r = ed(
13155 &mut srv,
13156 json!([
13157 { "op": "append", "source": "src:0", "in": "0s", "out": "2s", "lane": "V1", "audio": false },
13158 { "op": "append", "source": "src:0", "in": "2s", "out": "4s", "lane": "V1", "audio": false }
13159 ]),
13160 );
13161 assert!(!r.is_error, "{}", r.text);
13162 // Both clips are 2 s: swapping them is even, so the reply is exactly the two starts.
13163 let r = ed(&mut srv, json!([{ "op": "swap", "a": "V1@0", "b": "V1@60", "ripple": false }]));
13164 assert!(!r.is_error, "{}", r.text);
13165 assert!(r.text.contains("swap V1@0 ↔ V1@60: first now at 2.0s, second now at 0.0s"), "{}", r.text);
13166 assert!(!r.text.contains("nothing between them moved"), "{}", r.text);
13167 }
13168
13169 #[test]
13170 fn a_speed_reply_gives_lengths_to_three_decimals() {
13171 let mut srv = open();
13172 let r = ed(&mut srv, json!([{ "op": "speed", "clip": "V1@0", "x": 2.0 }]));
13173 assert!(!r.is_error, "{}", r.text);
13174 assert!(r.text.contains("(5.000s → 2.500s)"), "{}", r.text);
13175 }
13176
13177 #[test]
13178 fn a_trim_states_the_asked_time_once() {
13179 // Scope clip: the single-clip path.
13180 let mut srv = open();
13181 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "V1@0", "edge": "out", "to": "4.07s", "scope": "clip" }]));
13182 assert!(!r.is_error, "{}", r.text);
13183 assert!(r.text.contains("asked 4.07s → 122f (4.067s)"), "{}", r.text);
13184 assert!(!r.text.contains("(4.07s → 122f)"), "{}", r.text);
13185 // Default scope: the take path.
13186 let mut srv = open();
13187 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "V1@0", "edge": "out", "to": "4.07s" }]));
13188 assert!(!r.is_error, "{}", r.text);
13189 assert!(r.text.contains("asked 4.07s → 122f (4.067s)"), "{}", r.text);
13190 }
13191
13192 #[test]
13193 fn visualizer_on_an_audio_clip_places_a_ring_waveform_picture() {
13194 let mut srv = open();
13195 let r = ed(&mut srv, json!([{ "op": "visualizer", "clip": "A1@0", "on": true }]));
13196 assert!(!r.is_error, "{}", r.text);
13197 assert!(r.text.contains("placed a waveform picture for A1@0 on V"), "{}", r.text);
13198 let s = srv.session.as_ref().unwrap();
13199 assert!(s.lanes().iter().any(|l| l.kind == LaneKind::Video && s.lane_clips(*l).iter().any(|c| c.visualizer != 0)));
13200 // on:false on the sound clip turns its picture off.
13201 let r = ed(&mut srv, json!([{ "op": "visualizer", "clip": "A1@0", "on": false }]));
13202 assert!(!r.is_error && r.text.contains("its waveform picture on V2@0 is off"), "{}", r.text);
13203 }
13204
13205 #[test]
13206 fn visualizer_on_a_locked_audio_clip_refuses_and_adds_no_lane() {
13207 let mut srv = open();
13208 let lanes = srv.session.as_ref().unwrap().lanes().len();
13209 let r = ed(&mut srv, json!([{ "op": "lane_flags", "lane": "A1", "locked": true }]));
13210 assert!(!r.is_error, "{}", r.text);
13211 let r = ed(&mut srv, json!([{ "op": "visualizer", "clip": "A1@0", "on": true }]));
13212 assert!(r.is_error, "{}", r.text);
13213 assert_eq!(srv.session.as_ref().unwrap().lanes().len(), lanes, "nothing was added");
13214 }
13215
13216 #[test]
13217 fn placing_on_an_empty_lane_names_no_hole() {
13218 let mut srv = empty_av();
13219 let r = ed(&mut srv, json!([{ "op": "place", "source": "src:0", "lane": "V1", "at": "2s", "audio": false }]));
13220 assert!(!r.is_error, "{}", r.text);
13221 assert!(!r.text.contains("hole left"), "{}", r.text);
13222 }
13223
13224 fn srt_path() -> String {
13225 Path::new(env!("CARGO_MANIFEST_DIR")).join("../engine/tests/data/test_subs.srt").to_string_lossy().into_owned()
13226 }
13227
13228 /// Lanes and captions as (lane, start, end, link) rows, for before/after comparisons.
13229 fn full_state(srv: &Server) -> Vec<(Lane, u32, u32, Option<u32>)> {
13230 let s = srv.session.as_ref().expect("session");
13231 let mut out = Vec::new();
13232 for l in s.lanes() {
13233 if l.kind == LaneKind::Subtitle {
13234 out.extend(s.sub_lane(l).iter().map(|c| (l, c.start, c.start + c.frames, c.link)));
13235 } else {
13236 out.extend(s.lane_clips(l).iter().map(|c| (l, c.start, c.end(), c.link)));
13237 }
13238 }
13239 out
13240 }
13241
13242 /// A 5 s test clip split at 2 s, with the srt placed as a caption track on S1 from 0.
13243 fn split_with_captions(srv: &mut Server) {
13244 let r = ed(srv, json!([{ "op": "split", "at": "2s" }, { "op": "subtitles_import", "path": srt_path() }, { "op": "captions_place", "track": 0, "lane": "S1", "at": "0" }]));
13245 assert!(!r.is_error, "{}", r.text);
13246 }
13247
13248 #[test]
13249 fn grouped_caption_over_the_slot_is_refused_by_name_and_dry_matches_real() {
13250 let mut srv = open();
13251 split_with_captions(&mut srv);
13252 // The caption (0 s to 4.77 s) grouped with V1@60: it lies over the slot of V1@0.
13253 let r = ed(&mut srv, json!([{ "op": "group", "clips": ["S1@0", "V1@2s"] }]));
13254 assert!(!r.is_error, "{}", r.text);
13255 let before = full_state(&srv);
13256 let mv = json!([{ "op": "move", "clip": "V1@0", "at": "60f", "insert": true, "split_captions": true }]);
13257 let dry = run_edit(&mut srv, &json!({ "ops": mv, "dry_run": true }));
13258 let real = ed(&mut srv, mv);
13259 assert!(dry.is_error && real.is_error, "dry {} / real {}", dry.text, real.text);
13260 assert!(real.text.contains("grouped with another take") && real.text.contains("S1@0"), "{}", real.text);
13261 assert_eq!(dry.text.lines().next(), real.text.lines().next(), "a dry run names what the real run refuses");
13262 assert_eq!(full_state(&srv), before, "a refused move changes nothing");
13263 }
13264
13265 #[test]
13266 fn grouped_caption_moves_with_its_take_and_no_audio_is_dropped() {
13267 let mut srv = open();
13268 split_with_captions(&mut srv);
13269 // Trim the caption to the take it is grouped with (V1@60, 2 s to 5 s): a consistent group.
13270 let r = ed(&mut srv, json!([{ "op": "captions_place", "track": 0, "lane": "S2", "at": "2s" }, { "op": "sub_trim", "clip": "S2@60", "edge": "out", "to": "5s" }, { "op": "group", "clips": ["S2@60", "V1@2s"] }]));
13271 assert!(!r.is_error, "{}", r.text);
13272 let mv = json!([{ "op": "move", "clip": "V1@60", "at": "0", "insert": true, "split_captions": true }]);
13273 let dry = run_edit(&mut srv, &json!({ "ops": mv, "dry_run": true }));
13274 assert!(!dry.is_error, "{}", dry.text);
13275 let before = full_state(&srv);
13276 let real = ed(&mut srv, mv);
13277 assert!(!real.is_error, "{}", real.text);
13278 let s = srv.session.as_ref().unwrap();
13279 assert!(!real.text.contains("detached"), "{}", real.text);
13280 let starts = |l: Lane| s.lane_clips(l).iter().map(|c| (c.start, c.frames())).collect::<Vec<_>>();
13281 assert_eq!(starts(Lane::V1), vec![(0, 90), (90, 60)], "{}", real.text);
13282 assert_eq!(starts(Lane::A1), vec![(0, 90), (90, 60)], "no audio is dropped: {}", real.text);
13283 let caps = s.sub_lane(Lane::new(LaneKind::Subtitle, 1));
13284 assert_eq!(caps.len(), 1, "the grouped caption is still one placement");
13285 assert_eq!(caps[0].start, 0, "the caption moved with its take to the take's new start");
13286 assert_ne!(before, full_state(&srv));
13287 }
13288
13289 #[test]
13290 fn a_cut_between_cues_splits_with_no_refusal_and_a_cue_crossing_is_named() {
13291 // Cues sit at 0.5–1.5, 2.0–3.25 and 4.0–4.75 s. The 2 s edge falls between cues.
13292 let mut srv = open();
13293 split_with_captions(&mut srv);
13294 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@0", "at": "90f", "insert": true }]));
13295 assert!(!r.is_error, "a block spanning the edge with no cue across it moves: {}", r.text);
13296 assert!(r.text.contains("between cues (no cue cut)"), "{}", r.text);
13297 let cues = srv.session.as_ref().unwrap().sub_lane_cues(Lane::new(LaneKind::Subtitle, 0)).len();
13298 assert_eq!(cues, 3, "every cue is still listed once: {}", r.text);
13299 // Split at 1 s instead: "first line" (0.5–1.5 s) crosses the edge, so the move is refused by that cue.
13300 let mut srv = open();
13301 let r = ed(&mut srv, json!([{ "op": "split", "at": "1s" }, { "op": "subtitles_import", "path": srt_path() }, { "op": "captions_place", "track": 0, "lane": "S1", "at": "0" }]));
13302 assert!(!r.is_error, "{}", r.text);
13303 let before = full_state(&srv);
13304 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@0", "at": "90f", "insert": true }]));
13305 assert!(r.is_error && r.text.contains("cue 'first line' (S1 0.5s–1.5s) crosses the edge"), "{}", r.text);
13306 assert_eq!(full_state(&srv), before);
13307 }
13308
13309 #[test]
13310 fn a_sound_clip_visualizer_takes_style_and_fast_and_moves_with_its_clip() {
13311 let mut srv = open();
13312 let r = ed(&mut srv, json!([{ "op": "visualizer", "clip": "A1@0", "on": true, "style": "ring", "fast": true }]));
13313 assert!(!r.is_error, "{}", r.text);
13314 assert!(r.text.contains("style ring, fast") && r.text.contains("grouped with it"), "{}", r.text);
13315 let s = srv.session.as_ref().unwrap();
13316 let pic = s.lanes().into_iter().find(|l| l.kind == LaneKind::Video && s.lane_clips(*l).iter().any(|c| c.visualizer != 0)).expect("picture");
13317 let c = &s.lane_clips(pic)[0];
13318 assert!(c.visualizer & engine::decode::VIZ_FAST != 0, "fast is set");
13319 assert_eq!(engine::decode::viz_style(c.visualizer), 2, "ring");
13320 assert!(c.link.is_some() && c.link == s.lane_clips(Lane::A1)[0].link, "the picture is grouped with its sound clip");
13321 // A move of the sound clip's take carries the picture; a trim carries it too.
13322 let r = ed(&mut srv, json!([{ "op": "move", "clip": "V1@0", "at": "2s" }]));
13323 assert!(!r.is_error, "{}", r.text);
13324 let s = srv.session.as_ref().unwrap();
13325 assert!(s.lane_clips(pic).iter().any(|c| c.start == 60), "the picture moved with the take");
13326 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "A1@60", "edge": "out", "to": "4s" }]));
13327 assert!(!r.is_error, "{}", r.text);
13328 let s = srv.session.as_ref().unwrap();
13329 assert!(s.lane_clips(pic).iter().any(|c| c.start == 60 && c.end() == 120), "the picture trimmed with the take");
13330 }
13331
13332 #[test]
13333 fn a_still_at_the_same_start_on_a_second_lane_takes_its_length() {
13334 let mut srv = open();
13335 let png = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_still.png");
13336 srv.session.as_mut().unwrap().import(&png).expect("import still");
13337 let r = ed(&mut srv, json!([{ "op": "place", "source": "src:1", "lane": "V1", "at": "32s", "length": "3s" }]));
13338 assert!(!r.is_error, "{}", r.text);
13339 let r = ed(&mut srv, json!([{ "op": "lane_add", "kind": "video" }, { "op": "place", "source": "src:1", "lane": "V2", "at": "32s", "length": "3s" }]));
13340 assert!(!r.is_error, "{}", r.text);
13341 let s = srv.session.as_ref().unwrap();
13342 let at = |l: Lane| s.lane_clips(l).iter().find(|c| c.start == 960).map(|c| c.frames());
13343 assert_eq!(at(Lane::new(LaneKind::Video, 1)), Some(90), "V2 takes the length");
13344 assert_eq!(at(Lane::V1), Some(90), "V1 keeps its own");
13345 // The default still length is five seconds: asking for it is not a trim.
13346 let r = ed(&mut srv, json!([{ "op": "place", "source": "src:1", "lane": "V1", "at": "60s", "length": "5s" }]));
13347 assert!(!r.is_error, "{}", r.text);
13348 }
13349
13350 #[test]
13351 fn an_overwrite_says_what_it_cut_and_where_the_tail_went() {
13352 // A clip at 3 s, 5 s long (frames 90 to 240 at 30 fps), overwritten from 4 s to 5 s.
13353 let clip = |start: u32, frames: u32| Clip { start, ..clip_of(0, 0, frames) };
13354 let both = vec![(Lane::V1, vec![clip(90, 150)])];
13355 assert_eq!(
13356 overwrite_notes(&both, 120, 150, 30.0),
13357 vec!["V1@90 cut to 3.000–4.000; 5.000–8.000 kept as V1@150".to_string()]
13358 );
13359 // Overwritten from its head: the tail alone is kept, at its new address.
13360 let tail = vec![(Lane::V1, vec![clip(90, 150)])];
13361 assert_eq!(overwrite_notes(&tail, 90, 120, 30.0), vec!["V1@90 cut to 4.000–8.000 (kept as V1@120)".to_string()]);
13362 // Covered wholly: removed, with the range it had.
13363 let wholly = vec![(Lane::V1, vec![clip(90, 60)])];
13364 assert_eq!(overwrite_notes(&wholly, 80, 160, 30.0), vec!["V1@90 removed (3.000–5.000)".to_string()]);
13365 }
13366
13367 #[test]
13368 fn a_hole_names_its_range_and_the_op_that_left_it() {
13369 let mut srv = open();
13370 let r = ed(&mut srv, json!([{ "op": "split", "at": "1s" }, { "op": "split", "at": "2s" }]));
13371 assert!(!r.is_error, "{}", r.text);
13372 let r = ed(&mut srv, json!([{ "op": "lift", "clip": "V1@30" }]));
13373 assert!(!r.is_error, "{}", r.text);
13374 assert!(r.text.contains("hole left on V1 at 1.000–2.000s by lift"), "{}", r.text);
13375 }
13376
13377 #[test]
13378 fn copy_look_lists_a_target_that_took_nothing_as_skipped() {
13379 let mut srv = open();
13380 let r = ed(&mut srv, json!([{ "op": "copy_look", "from": "V1@0", "to": ["A1@0"], "what": ["transform"] }]));
13381 assert!(!r.is_error, "{}", r.text);
13382 assert!(!r.text.contains("→ A1@0"), "{}", r.text);
13383 assert!(r.text.contains("skipped:") && r.text.contains("A1@0"), "{}", r.text);
13384 }
13385
13386 #[test]
13387 fn a_visualizer_on_a_video_clip_reports_no_split() {
13388 let mut srv = open();
13389 let r = ed(&mut srv, json!([{ "op": "visualizer", "clip": "A1@0", "on": true }]));
13390 assert!(!r.is_error, "{}", r.text);
13391 assert!(!r.text.contains("split "), "{}", r.text);
13392 }
13393
13394 #[test]
13395 fn a_failed_batch_with_a_freeze_keeps_the_undo_history() {
13396 let mut srv = open();
13397 let r = ed(&mut srv, json!([{ "op": "split", "at": "1s" }]));
13398 assert!(!r.is_error, "{}", r.text);
13399 let depth = srv.session.as_ref().unwrap().undo_depth();
13400 let r = ed(&mut srv, json!([{ "op": "freeze", "at": "2s", "duration": "1s" }, { "op": "trim", "clip": "V1@999999f", "edge": "out", "to": "1f" }]));
13401 assert!(r.is_error, "{}", r.text);
13402 let s = srv.session.as_ref().unwrap();
13403 assert_eq!(s.undo_depth(), depth, "the failed batch took no undo step away");
13404 assert_eq!(s.sources().len(), 1, "the still was taken back");
13405 assert_eq!(srv.ledger.len(), 1, "the ledger keeps its step");
13406 }
13407}
13408
13409#[cfg(test)]
13410mod audio_track_tests {
13411 use super::*;
13412 use crate::testutil::TestDir;
13413 use std::path::Path;
13414
13415 fn asset(name: &str) -> PathBuf {
13416 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
13417 }
13418
13419 /// A timeline opened on a multi-audio file, so its tracks are `src:0`'s file's own.
13420 fn open_asset(name: &str) -> Server {
13421 engine::ao::set_silent_output();
13422 let sess = PlaybackSession::open(asset(name)).expect("open multi-audio asset");
13423 Server { session: Some(sess), ..Server::default() }
13424 }
13425
13426 fn ed(srv: &mut Server, ops: Value) -> Reply {
13427 run_edit(srv, &json!({ "ops": ops }))
13428 }
13429
13430 #[test]
13431 fn audio_track_out_of_range_names_the_tracks_the_file_has() {
13432 let mut srv = open_asset("test_multiaudio.mp4");
13433 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "audio_track": 9, "at": "end" }]));
13434 assert!(r.text.contains("audio_track:9: src:0 has audio tracks 0 (und), 1 (fra), 2 (und)"), "{}", r.text);
13435 assert_eq!(srv.session.as_ref().unwrap().sources().len(), 1, "the refusal changed nothing");
13436 }
13437
13438 #[test]
13439 fn audio_track_takes_in_and_out_of_the_chosen_track() {
13440 let mut srv = open_asset("test_multiaudio.mp4");
13441 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "audio_track": 1, "at": "end", "in": "0f", "out": "10f" }]));
13442 assert!(!r.is_error, "{}", r.text);
13443 assert!(r.text.contains("audio track 1 (fra)"), "{}", r.text);
13444 let s = srv.session.as_ref().unwrap();
13445 let clip = s.lane_clips(Lane::V1).last().expect("a clip on V1");
13446 assert_eq!(clip.frames(), 10, "the in/out range is placed");
13447 assert_eq!(s.sources()[clip.source].audio_stream, 1);
13448 assert_eq!(s.lane_clips(Lane::V1).len(), 2, "the scratch clips of the registration are gone");
13449 }
13450
13451 #[test]
13452 fn audio_track_places_the_chosen_track_names_it_and_survives_save() {
13453 let mut srv = open_asset("test_multiaudio.mp4");
13454 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "audio_track": 1, "at": "end" }]));
13455 assert!(!r.is_error, "{}", r.text);
13456 assert!(r.text.contains("audio track 1 (fra)"), "the reply names the track: {}", r.text);
13457 let s = srv.session.as_ref().unwrap();
13458 let clip = s.lane_clips(Lane::V1).last().expect("a clip was placed on V1");
13459 assert_eq!(s.sources()[clip.source].audio_stream, 1, "the placed clip plays track 1");
13460 assert_eq!(s.sources()[0].audio_stream, 0, "src:0 keeps its own track");
13461
13462 // The choice survives save and reopen.
13463 let dir = TestDir::new("audio-track-save");
13464 let proj = dir.join("multi.edith");
13465 s.save_project(&proj).expect("save");
13466 let back = PlaybackSession::open_project(&proj).expect("reopen");
13467 let back_clip = back.lane_clips(Lane::V1).last().expect("the clip is back").clone();
13468 assert_eq!(back.sources()[back_clip.source].audio_stream, 1, "track 1 survives reopen");
13469 }
13470
13471 #[test]
13472 fn track_one_and_track_zero_sound_different() {
13473 let file = asset("test_multiaudio.mp4");
13474 let zero = engine::silence::levels(&file, 0, (0.0, f64::INFINITY)).expect("levels 0").expect("track 0 has sound");
13475 let one = engine::silence::levels(&file, 1, (0.0, f64::INFINITY)).expect("levels 1").expect("track 1 has sound");
13476 assert_ne!(zero, one, "the tracks differ, so placing one is not placing the other");
13477 }
13478
13479 #[test]
13480 fn a_placement_that_overwrites_a_clip_names_it_removed_not_shifted() {
13481 let mut srv = open_asset("test_av.mp4");
13482 let len = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].frames();
13483 let half = len / 2;
13484 // X2 spans [half, len); the placement covers exactly that span, so X2 is removed outright.
13485 let r = ed(
13486 &mut srv,
13487 json!([
13488 { "op": "split", "at": format!("{half}f") },
13489 { "op": "place", "source": 0, "in": "0f", "length": format!("{}f", len - half), "at": format!("{half}f"), "lane": "V1", "overwrite": true }
13490 ]),
13491 );
13492 assert!(r.text.contains("removed"), "the removed clip is named: {}", r.text);
13493 assert!(!r.text.contains("shifted:"), "no clip shifted: {}", r.text);
13494 }
13495
13496 /// A scope:"clip" trim to the edge the clip already has changes nothing: no detach, no undo step.
13497 #[test]
13498 fn scope_clip_trim_to_the_current_edge_is_a_true_no_op() {
13499 let mut srv = open_asset("test_av.mp4");
13500 let out = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].end();
13501 let (ledger_before, v1_link) = (srv.ledger.len(), srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].link);
13502 let r = ed(&mut srv, json!([{ "op": "trim", "clip": "V1@0", "edge": "out", "to": format!("{out}f"), "scope": "clip" }]));
13503 assert!(!r.is_error, "{}", r.text);
13504 assert!(r.text.contains("nothing to trim"), "{}", r.text);
13505 assert!(!r.text.contains("detached"), "{}", r.text);
13506 assert_eq!(srv.ledger.len(), ledger_before, "no undo step");
13507 assert_eq!(srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].link, v1_link, "the take is still linked");
13508 }
13509
13510 /// Deleting one clip of a take names the whole take it removed, and a delete at the end of a lane
13511 /// has no arrow list: the clips it removed are not listed as if they stayed.
13512 #[test]
13513 fn delete_of_one_clip_of_a_take_names_the_take() {
13514 let mut srv = open_asset("test_av.mp4");
13515 let half = srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].frames() / 2;
13516 let r = ed(&mut srv, json!([
13517 { "op": "split", "at": format!("{half}f") },
13518 { "op": "delete", "clip": format!("A1@{half}") }
13519 ]));
13520 assert!(!r.is_error, "{}", r.text);
13521 assert!(r.text.contains(&format!("removed V1@{half} and A1@{half} (its take)")) || r.text.contains(&format!("removed A1@{half} and V1@{half} (its take)")), "{}", r.text);
13522 assert!(!r.text.contains(&format!("→ V1@{half}")), "a removed clip is not an arrow target: {}", r.text);
13523 }
13524
13525 /// A ripple_delete names the span it closed, and its removed take is named as removed.
13526 #[test]
13527 fn ripple_delete_names_the_span_it_closed_and_the_removed_take() {
13528 let mut srv = open_asset("test_av.mp4");
13529 let r = ed(&mut srv, json!([{ "op": "ripple_delete", "clip": "V1@0" }]));
13530 assert!(!r.is_error, "{}", r.text);
13531 assert!(r.text.contains("closed 0.0s–"), "{}", r.text);
13532 assert!(r.text.contains("removed") && r.text.contains("(its take)"), "{}", r.text);
13533 let first = r.text.lines().next().unwrap_or("");
13534 assert!(!first.contains("→"), "nothing is left after the cut to move: {}", r.text);
13535 }
13536
13537 /// A cut inside one clip splits it: the reply names both pieces, not a trim of the first.
13538 #[test]
13539 fn remove_time_inside_a_clip_says_split_and_names_both_pieces() {
13540 let mut srv = open_asset("test_av.mp4");
13541 let r = ed(&mut srv, json!([{ "op": "remove_time", "at": "2s", "duration": "0.5s" }]));
13542 assert!(!r.is_error, "{}", r.text);
13543 assert!(r.text.contains("split V1@0: V1@0 0.0s–2.0s, V1@60 2.0s–"), "{}", r.text);
13544 assert!(!r.text.contains("trimmed V1@0"), "{}", r.text);
13545 }
13546
13547 /// A dissolve whose successor a delete removed and the next clip moved up into: the reply says the
13548 /// dissolve now joins that clip, and a dissolve that loses its successor for good says it is a cut.
13549 #[test]
13550 fn dissolve_names_the_clip_it_now_joins_after_a_ripple() {
13551 let mut srv = open_asset("test_av.mp4");
13552 let r = ed(&mut srv, json!([
13553 { "op": "lane_add", "kind": "video" },
13554 { "op": "place", "source": 0, "at": "0s", "in": "0s", "out": "2s", "lane": "V2", "audio": false },
13555 { "op": "place", "source": 0, "at": "2s", "in": "2s", "out": "4s", "lane": "V2", "audio": false },
13556 { "op": "place", "source": 0, "at": "4s", "in": "3s", "out": "5s", "lane": "V2", "audio": false },
13557 { "op": "dissolve", "clip": "V2@0", "frames": 12, "linked": false },
13558 { "op": "delete", "clip": "V2@60", "lanes": ["V2"] }
13559 ]));
13560 assert!(!r.is_error, "{}", r.text);
13561 assert!(r.text.contains("V2@0's dissolve now joins V2@60 (was the deleted clip)"), "{}", r.text);
13562 }
13563
13564}
13565
13566#[cfg(test)]
13567mod round26_tests {
13568 use super::*;
13569 use std::path::Path;
13570
13571 fn asset(name: &str) -> PathBuf {
13572 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
13573 }
13574
13575 /// An empty 30 fps timeline with test_av.mp4 as src:0 and test_still.png as src:1.
13576 fn bank() -> Server {
13577 engine::ao::set_silent_output();
13578 let mut sess = PlaybackSession::empty(1280, 720, 30.0).expect("empty session");
13579 sess.import(&asset("test_av.mp4")).expect("import test asset");
13580 sess.import(&asset("test_still.png")).expect("import still");
13581 Server { session: Some(sess), ..Server::default() }
13582 }
13583
13584 fn ed(srv: &mut Server, ops: Value) -> Reply {
13585 run_edit(srv, &json!({ "ops": ops }))
13586 }
13587
13588 #[test]
13589 fn visualizer_over_a_logo_names_the_picture_it_covers() {
13590 let mut srv = bank();
13591 let r = ed(&mut srv, json!([
13592 { "op": "append", "source": 0 },
13593 { "op": "lane_add", "kind": "video" },
13594 { "op": "place", "source": 0, "at": "1s", "in": "0s", "out": "3s", "lane": "V2", "audio": false },
13595 ]));
13596 assert!(!r.is_error, "{}", r.text);
13597 let r = ed(&mut srv, json!([{ "op": "visualizer", "clip": "A1@0", "on": true, "style": "ring" }]));
13598 assert!(!r.is_error, "{}", r.text);
13599 // V1 is the sound's own take, so only the logo on V2 is named.
13600 assert!(
13601 r.text.contains("the visualizer on V3 draws over V2 (test_av.mp4) during 1.0s–4.0s;"),
13602 "{}",
13603 r.text
13604 );
13605 assert!(!r.text.contains("draws over V1"), "{}", r.text);
13606 assert!(r.text.contains("lane_move it below them"), "{}", r.text);
13607 assert!(r.text.contains("no background option makes it transparent"), "{}", r.text);
13608 }
13609
13610 #[test]
13611 fn visualizer_over_its_own_take_is_not_a_cover() {
13612 // The take's own picture on V1 sits below the visualizer's V2 picture, but it is the take the
13613 // visualizer is for: no note.
13614 let mut srv = bank();
13615 let r = ed(&mut srv, json!([{ "op": "append", "source": 0 }]));
13616 assert!(!r.is_error, "{}", r.text);
13617 let r = ed(&mut srv, json!([{ "op": "visualizer", "clip": "A1@0", "on": true, "style": "ring" }]));
13618 assert!(!r.is_error, "{}", r.text);
13619 assert!(r.text.contains("grouped with it"), "{}", r.text);
13620 assert!(!r.text.contains("draws over"), "{}", r.text);
13621 }
13622
13623 #[test]
13624 fn visualizer_over_a_take_with_a_logo_below_names_only_the_logo() {
13625 // Own take (V1+A1) plus an unlinked logo on V2 under the new V3 picture: only the logo is named.
13626 let mut srv = bank();
13627 let r = ed(&mut srv, json!([
13628 { "op": "append", "source": 0 },
13629 { "op": "lane_add", "kind": "video" },
13630 { "op": "place", "source": 0, "at": "2s", "in": "0s", "out": "2s", "lane": "V2", "audio": false },
13631 ]));
13632 assert!(!r.is_error, "{}", r.text);
13633 let r = ed(&mut srv, json!([{ "op": "visualizer", "clip": "A1@0", "on": true }]));
13634 assert!(!r.is_error, "{}", r.text);
13635 assert!(r.text.contains("draws over V2 (test_av.mp4) during 2.0s–4.0s"), "{}", r.text);
13636 assert!(!r.text.contains("draws over V1"), "{}", r.text);
13637 }
13638
13639 #[test]
13640 fn visualizer_on_a_video_clip_names_its_sound_clip_and_is_refused() {
13641 let mut srv = bank();
13642 let r = ed(&mut srv, json!([{ "op": "append", "source": 0 }]));
13643 assert!(!r.is_error, "{}", r.text);
13644 let r = ed(&mut srv, json!([{ "op": "visualizer", "clip": "V1@0", "on": true }]));
13645 assert!(r.is_error, "{}", r.text);
13646 assert!(r.text.contains("the visualizer is set on the sound clip of its take, A1@0 (A1@0 is the sound of V1@0)"), "{}", r.text);
13647 // Turning a flag off is let through: nothing is refused on a video clip with on:false.
13648 let r = ed(&mut srv, json!([{ "op": "visualizer", "clip": "V1@0", "on": false }]));
13649 assert!(!r.text.contains("refused"), "{}", r.text);
13650 }
13651
13652 #[test]
13653 fn visualizer_on_a_video_clip_with_no_sound_is_refused() {
13654 let mut srv = bank();
13655 let r = ed(&mut srv, json!([{ "op": "append", "source": 0, "audio": false }]));
13656 assert!(!r.is_error, "{}", r.text);
13657 let r = ed(&mut srv, json!([{ "op": "visualizer", "clip": "V1@0", "on": true }]));
13658 assert!(r.is_error && r.text.contains("no linked sound clip"), "{}", r.text);
13659 assert_eq!(srv.session.as_ref().unwrap().lane_clips(Lane::V1)[0].visualizer, 0);
13660 }
13661
13662 #[test]
13663 fn undo_and_redo_with_no_project_say_no_project_is_open() {
13664 let mut srv = Server::default();
13665 let r = run_undo(&mut srv, &json!({}));
13666 assert!(r.is_error && r.text.starts_with("no project is open"), "{}", r.text);
13667 assert!(!r.text.contains("checkpoints survive"), "{}", r.text);
13668 let r = run_redo(&mut srv, &json!({}));
13669 assert!(r.is_error && r.text.starts_with("no project is open"), "{}", r.text);
13670 }
13671
13672 #[test]
13673 fn a_placement_far_past_the_clips_names_the_gap_it_left() {
13674 let mut srv = bank();
13675 let r = ed(&mut srv, json!([{ "op": "append", "source": 0, "audio": false }]));
13676 assert!(!r.is_error, "{}", r.text);
13677 let r = ed(&mut srv, json!([{ "op": "place", "source": "src:0", "at": "999s", "lane": "V1", "audio": false }]));
13678 assert!(!r.is_error, "{}", r.text);
13679 assert!(r.text.contains("note: left a 994.0s gap before it on V1 (the timeline was 5.0s)"), "{}", r.text);
13680 }
13681
13682 #[test]
13683 fn a_placement_against_the_clip_before_it_leaves_no_gap_note() {
13684 let mut srv = bank();
13685 let r = ed(&mut srv, json!([{ "op": "append", "source": 0, "audio": false }]));
13686 assert!(!r.is_error, "{}", r.text);
13687 let r = ed(&mut srv, json!([{ "op": "append", "source": 0, "audio": false }]));
13688 assert!(!r.is_error, "{}", r.text);
13689 assert!(!r.text.contains("left a "), "{}", r.text);
13690 }
13691
13692 #[test]
13693 fn close_gaps_on_an_empty_lane_says_it_is_empty() {
13694 let mut srv = bank();
13695 let r = ed(&mut srv, json!([{ "op": "append", "source": 0 }]));
13696 assert!(!r.is_error, "{}", r.text);
13697 let r = ed(&mut srv, json!([{ "op": "close_gaps", "lane": "A2" }]));
13698 assert!(r.is_error && r.text.contains("A2 is not a lane on this timeline; the lanes are V1, A1"), "{}", r.text);
13699 let r = ed(&mut srv, json!([{ "op": "lane_add", "kind": "audio" }, { "op": "close_gaps", "lane": "A2" }]));
13700 assert!(!r.is_error, "{}", r.text);
13701 assert!(r.text.contains("A2 is empty: nothing to close"), "{}", r.text);
13702 assert!(!r.text.contains("ends at"), "{}", r.text);
13703 }
13704
13705 #[test]
13706 fn crossfade_after_a_dissolve_says_the_pair_already_crosses() {
13707 let mut srv = bank();
13708 let r = ed(&mut srv, json!([{ "op": "append", "source": 0 }, { "op": "append", "source": 0 }]));
13709 assert!(!r.is_error, "{}", r.text);
13710 let r = ed(&mut srv, json!([{ "op": "dissolve", "clip": "V1@0", "frames": 15 }]));
13711 assert!(!r.is_error, "{}", r.text);
13712 let r = ed(&mut srv, json!([{ "op": "crossfade", "clip": "A1@0", "frames": 15 }]));
13713 assert!(!r.is_error, "{}", r.text);
13714 assert!(r.text.starts_with("no change: A1@0 and A1@150 already crossfade over 15f (from the dissolve)"), "{}", r.text);
13715 }
13716
13717 #[test]
13718 fn crossfade_again_without_a_dissolve_names_the_crossfade_only() {
13719 let mut srv = bank();
13720 let r = ed(&mut srv, json!([{ "op": "append", "source": 0 }, { "op": "append", "source": 0 }]));
13721 assert!(!r.is_error, "{}", r.text);
13722 let r = ed(&mut srv, json!([{ "op": "crossfade", "clip": "A1@0", "frames": 15 }]));
13723 assert!(!r.is_error, "{}", r.text);
13724 let r = ed(&mut srv, json!([{ "op": "crossfade", "clip": "A1@0", "frames": 15 }]));
13725 assert!(r.text.contains("already crossfade over 15f"), "{}", r.text);
13726 assert!(!r.text.contains("from the dissolve"), "{}", r.text);
13727 }
13728}
13729
13730#[cfg(test)]
13731mod round27_tests {
13732 use super::*;
13733 use crate::testutil::TestDir;
13734 use std::path::Path;
13735
13736 fn asset(name: &str) -> PathBuf {
13737 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
13738 }
13739
13740 /// An empty 30 fps timeline with test_av.mp4 as src:0 and test_still.png as src:1.
13741 fn bank() -> Server {
13742 engine::ao::set_silent_output();
13743 let mut sess = PlaybackSession::empty(1280, 720, 30.0).expect("empty session");
13744 sess.import(&asset("test_av.mp4")).expect("import test asset");
13745 sess.import(&asset("test_still.png")).expect("import still");
13746 Server { session: Some(sess), ..Server::default() }
13747 }
13748
13749 fn ed(srv: &mut Server, ops: Value) -> Reply {
13750 run_edit(srv, &json!({ "ops": ops }))
13751 }
13752
13753 /// `restore` keeps the open state as a checkpoint first, and the reply names it, so the
13754 /// restore can be undone by restoring that checkpoint back.
13755 #[test]
13756 fn restore_keeps_the_open_state_as_a_checkpoint() {
13757 let td = TestDir::new("r27-restore-keeps");
13758 TEST_CHECKPOINTS.with(|d| *d.borrow_mut() = Some(td.join("checkpoints")));
13759 let mut srv = bank();
13760 let c = run_checkpoint(&mut srv, &json!({ "name": "rs1" }));
13761 assert!(!c.is_error, "{}", c.text);
13762 let r = ed(&mut srv, json!([{ "op": "append", "source": 0, "audio": false }]));
13763 assert!(!r.is_error, "{}", r.text);
13764 let rs = run_restore(&mut srv, &json!({ "name": "rs1" }));
13765 assert!(!rs.is_error, "{}", rs.text);
13766 assert!(rs.text.contains("the state before the restore is kept as checkpoint before-restore-rs1"), "{}", rs.text);
13767 assert!(srv.session.as_ref().unwrap().lane_clips(Lane::V1).is_empty());
13768 let back = run_restore(&mut srv, &json!({ "name": "before-restore-rs1" }));
13769 assert!(!back.is_error, "{}", back.text);
13770 assert_eq!(srv.session.as_ref().unwrap().lane_clips(Lane::V1).len(), 1, "the unsaved edit came back");
13771 }
13772
13773 /// A fade clamped to its clip reads the frames the clip kept in its header, with the asked time in the note.
13774 #[test]
13775 fn a_fade_clamped_to_its_clip_shows_the_frames_it_got() {
13776 let mut srv = bank();
13777 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s", "in": "0s", "out": "2s", "audio": false }]));
13778 assert!(!r.is_error, "{}", r.text);
13779 let r = ed(&mut srv, json!([{ "op": "fade", "clip": "V1@0", "in": "999s" }]));
13780 assert!(!r.is_error, "{}", r.text);
13781 assert!(r.text.contains("in 60f (in clamped from 999.0s to the clip's 2.0s)"), "{}", r.text);
13782 }
13783
13784 /// A locked lane refuses a dissolve on its last clip as locked, not as having no clip after it.
13785 #[test]
13786 fn a_dissolve_on_a_locked_last_clip_names_the_lock() {
13787 let mut srv = bank();
13788 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s", "in": "0s", "out": "2s", "audio": false }]));
13789 assert!(!r.is_error, "{}", r.text);
13790 let r = ed(&mut srv, json!([{ "op": "lane_flags", "lane": "V1", "locked": true }]));
13791 assert!(!r.is_error, "{}", r.text);
13792 let r = ed(&mut srv, json!([{ "op": "dissolve", "clip": "V1@0", "frames": 12 }]));
13793 assert!(r.is_error && r.text.contains("lane V1 is locked"), "{}", r.text);
13794 assert!(!r.text.contains("last clip"), "{}", r.text);
13795 }
13796
13797 /// Taking an audio track in for the first time says it added a source, with its file and track.
13798 #[test]
13799 fn a_track_taken_in_for_the_first_time_says_it_added_a_source() {
13800 engine::ao::set_silent_output();
13801 let sess = PlaybackSession::open(asset("test_multiaudio.mp4")).expect("open multi-audio asset");
13802 let mut srv = Server { session: Some(sess), ..Server::default() };
13803 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "audio_track": 1, "at": "end" }]));
13804 assert!(!r.is_error, "{}", r.text);
13805 assert!(r.text.contains("1. added src:1 (test_multiaudio.mp4 audio track 1); place src:1 "), "{}", r.text);
13806 let again = ed(&mut srv, json!([{ "op": "place", "source": 0, "audio_track": 1, "at": "end" }]));
13807 assert!(!again.text.contains("added src:"), "{}", again.text);
13808 }
13809
13810 /// A file with one audio track names it in parts, not as a one-item list.
13811 #[test]
13812 fn a_file_with_one_audio_track_names_it_in_parts() {
13813 engine::ao::set_silent_output();
13814 let sess = PlaybackSession::open(asset("test_av.mp4")).expect("open asset");
13815 let mut srv = Server { session: Some(sess), ..Server::default() };
13816 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "audio_track": 9, "at": "end" }]));
13817 assert!(r.is_error, "{}", r.text);
13818 assert!(r.text.contains("src:0 has one audio track ("), "{}", r.text);
13819 assert!(!r.text.contains("audio tracks"), "{}", r.text);
13820 }
13821
13822 /// A group whose members differ in length says so, with each one's length.
13823 #[test]
13824 fn a_group_of_unequal_members_says_they_differ_in_length() {
13825 let mut srv = bank();
13826 let r = ed(&mut srv, json!([
13827 { "op": "place", "source": 0, "lane": "V1", "at": "0s", "in": "0s", "out": "2s", "audio": false },
13828 { "op": "lane_add", "kind": "video" },
13829 { "op": "place", "source": 0, "lane": "V2", "at": "0s", "in": "0s", "out": "4s", "audio": false },
13830 ]));
13831 assert!(!r.is_error, "{}", r.text);
13832 let r = ed(&mut srv, json!([{ "op": "group", "clips": ["V1@0", "V2@0"] }]));
13833 assert!(!r.is_error, "{}", r.text);
13834 assert!(r.text.contains("the members differ in length (V1@0 2.000s, V2@0 4.000s)"), "{}", r.text);
13835 }
13836
13837 /// A gap a close_gaps sweep leaves open says the engine's own reason for it, with its span: here
13838 /// the V1 clip after the gap is one take with an A1 clip that starts elsewhere.
13839 #[test]
13840 fn close_gaps_names_the_reason_each_gap_stayed_open() {
13841 let mut srv = bank();
13842 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s", "in": "0s", "out": "2s", "audio": false }]));
13843 assert!(!r.is_error, "{}", r.text);
13844 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "3s", "in": "0s", "out": "2s", "audio": true }]));
13845 assert!(!r.is_error, "{}", r.text);
13846 let r = ed(&mut srv, json!([{ "op": "close_gaps", "lane": "V1" }]));
13847 assert!(!r.is_error, "{}", r.text);
13848 assert!(r.text.contains("left open 1 (2.0s–3.0s: the V1 clip at V1@90 is one take with the A1 clip at A1@90, and A1 has no gap of that length there"), "{}", r.text);
13849 assert!(!r.text.contains("a linked take would split"), "{}", r.text);
13850 }
13851
13852 /// The source out of a placed range is the timeline's exclusive end, not the last frame's start.
13853 /// A 2 s range of the 2.002 s 23.976 fps file lands 61 timeline frames long, which the file's
13854 /// real end caps at `2.002s`, the same end the timeline prints.
13855 #[test]
13856 fn a_placed_source_range_ends_where_the_timeline_ends_it() {
13857 engine::ao::set_silent_output();
13858 let mut sess = PlaybackSession::empty(1280, 720, 30.0).expect("empty session");
13859 sess.import(&asset("test_23976fps.mp4")).expect("import 23.976 fps asset");
13860 let mut srv = Server { session: Some(sess), ..Server::default() };
13861 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s", "in": "0s", "out": "2s", "audio": false }]));
13862 assert!(!r.is_error, "{}", r.text);
13863 assert!(r.text.contains("src 0.000s–2.002s"), "{}", r.text);
13864 }
13865}
13866
13867#[cfg(test)]
13868mod round29_tests {
13869 use super::*;
13870 use std::path::Path;
13871
13872 fn asset(name: &str) -> PathBuf {
13873 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
13874 }
13875
13876 /// An empty 30 fps timeline with test_av.mp4 (5 s, picture and sound) as src:0.
13877 fn bank() -> Server {
13878 engine::ao::set_silent_output();
13879 let mut sess = PlaybackSession::empty(1280, 720, 30.0).expect("empty session");
13880 sess.import(&asset("test_av.mp4")).expect("import test asset");
13881 Server { session: Some(sess), ..Server::default() }
13882 }
13883
13884 fn ed(srv: &mut Server, ops: Value) -> Reply {
13885 run_edit(srv, &json!({ "ops": ops }))
13886 }
13887
13888 /// Three 5 s clips on V1 and A1 (0 s, 5 s, 10 s), the first slowed to half speed with its ripple,
13889 /// so the timeline is 20 s and the slow clip ends at 10 s.
13890 fn slow_first() -> Server {
13891 let mut srv = bank();
13892 assert!(!ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s" }])).is_error);
13893 assert!(!ed(&mut srv, json!([{ "op": "append", "source": 0 }, { "op": "append", "source": 0 }])).is_error);
13894 let r = ed(&mut srv, json!([{ "op": "speed", "clip": "V1@0", "x": 0.5, "ripple": true }]));
13895 assert!(!r.is_error, "{}", r.text);
13896 srv
13897 }
13898
13899 /// insert_time and remove_time cut a slow clip at a frame where it has no cut point: the cut moves to
13900 /// the nearest one, the reply says so, and the amount moved is what was asked.
13901 #[test]
13902 fn insert_and_remove_work_inside_a_slow_clip_at_an_odd_frame() {
13903 let mut srv = slow_first();
13904 let s = srv.session.as_ref().unwrap();
13905 // At half speed a cut is possible only at an even timeline frame of the clip: 151f is not one.
13906 assert!(!cuttable(s, &[Lane::V1], 151), "151f is between two showings of one source frame");
13907 assert_eq!(cut_point(s, &[Lane::V1], 151), 150, "the nearest earlier cut point");
13908 let ins = ed(&mut srv, json!([{ "op": "insert_time", "at": "151f", "duration": "15f" }]));
13909 assert!(!ins.is_error, "{}", ins.text);
13910 assert!(ins.text.contains("the cut moved from 151f to 150f"), "{}", ins.text);
13911 assert_eq!(parse::session_end(srv.session.as_ref().unwrap()), 615, "15f inserted exactly");
13912
13913 let mut srv = slow_first();
13914 let rm = ed(&mut srv, json!([{ "op": "remove_time", "at": "151f", "duration": "30f" }]));
13915 assert!(!rm.is_error, "{}", rm.text);
13916 let s = srv.session.as_ref().unwrap();
13917 assert_eq!(parse::session_end(s), 570, "the 30f removed are the 30f asked, no more");
13918 assert_eq!(s.gap_count(Lane::V1), 0, "no hole left by the cut: {}", rm.text);
13919 }
13920
13921 #[test]
13922 fn close_gaps_names_the_hole_it_leaves_on_another_lane() {
13923 // A hole on V1 and the matching one on A2 (a bed), with no take between them: closing V1 alone leaves
13924 // A2's, and the reply names it with its own close_gaps.
13925 let mut srv = bank();
13926 let r = ed(&mut srv, json!([
13927 { "op": "lane_add", "kind": "audio" },
13928 { "op": "append", "source": 0, "lane": "V1", "audio": false },
13929 { "op": "append", "source": 0, "lane": "V1", "audio": false },
13930 { "op": "append", "source": 0, "lane": "V1", "audio": false },
13931 { "op": "place", "source": 0, "lane": "A2", "at": "0s" },
13932 { "op": "place", "source": 0, "lane": "A2", "at": "5s" },
13933 { "op": "place", "source": 0, "lane": "A2", "at": "10s" },
13934 { "op": "lift", "clip": "V1@150" },
13935 { "op": "lift", "clip": "A2@150" }
13936 ]));
13937 assert!(!r.is_error, "{}", r.text);
13938 let r = ed(&mut srv, json!([{ "op": "close_gaps", "lane": "V1" }]));
13939 assert!(!r.is_error && r.text.contains("closed 1"), "{}", r.text);
13940 assert!(r.text.contains("gaps left on other lanes: A2 5.0s–10.0s (close with close_gaps {lane:\"A2\"})"), "{}", r.text);
13941 assert_eq!(srv.session.as_ref().unwrap().gap_count(Lane::new(LaneKind::Audio, 1)), 1);
13942 }
13943
13944 /// A speed change with ripple names only the items after it: the sped clip and its take are not
13945 /// among the later items, so a clip with nothing after it says no item moved.
13946 #[test]
13947 fn speed_ripple_does_not_name_the_sped_clip_as_a_later_item() {
13948 let mut srv = bank();
13949 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s" }]));
13950 assert!(!r.is_error, "{}", r.text);
13951 let r = ed(&mut srv, json!([{ "op": "speed", "clip": "V1@0", "x": 0.5, "ripple": true }]));
13952 assert!(!r.is_error, "{}", r.text);
13953 assert!(!r.text.contains("later items moved"), "{}", r.text);
13954 let r = ed(&mut srv, json!([{ "op": "speed", "clip": "V1@0", "x": 1.0, "ripple": true }]));
13955 assert!(!r.is_error && !r.text.contains("later items moved"), "{}", r.text);
13956 }
13957
13958 /// split at a frame between two showings of one source frame inside a slow clip cuts at the nearest
13959 /// cut point, and the reply says it moved, as insert_time does.
13960 #[test]
13961 fn split_works_inside_a_slow_clip_at_an_odd_frame() {
13962 let mut srv = slow_first();
13963 assert!(!cuttable(srv.session.as_ref().unwrap(), &[Lane::V1], 151));
13964 let r = ed(&mut srv, json!([{ "op": "split", "at": "151f" }]));
13965 assert!(!r.is_error, "{}", r.text);
13966 assert!(r.text.contains("the cut moved from 151f to 150f"), "{}", r.text);
13967 let s = srv.session.as_ref().unwrap();
13968 assert!(s.lane_clips(Lane::V1).iter().any(|c| c.start == 150), "a cut at 150f: {}", r.text);
13969 assert_eq!(parse::session_end(s), 600, "the cut removes nothing");
13970 }
13971
13972 /// A cut that a hole closes must not pull the clips after it: the removed amount is the amount asked.
13973 #[test]
13974 fn remove_time_closes_a_sliver_without_removing_more() {
13975 let mut srv = slow_first();
13976 let before = parse::session_end(srv.session.as_ref().unwrap());
13977 let rm = ed(&mut srv, json!([{ "op": "remove_time", "at": "10.033s", "duration": "1s" }]));
13978 assert!(!rm.is_error, "{}", rm.text);
13979 assert_eq!(before - parse::session_end(srv.session.as_ref().unwrap()), 30, "{}", rm.text);
13980 assert!(!rm.text.contains("moving V1@"), "a sliver closing names no moved clip: {}", rm.text);
13981 }
13982
13983 /// A locked lane that a ripple would move or cut refuses the op by name, and nothing changes.
13984 #[test]
13985 fn a_ripple_refuses_a_locked_lane_it_would_leave_behind() {
13986 let mut srv = bank();
13987 assert!(!ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s" }, { "op": "append", "source": 0 }, { "op": "append", "source": 0 }, { "op": "append", "source": 0 }])).is_error);
13988 srv.session.as_mut().unwrap().set_lane_locked(Lane::A1, true);
13989 let depth = srv.session.as_ref().unwrap().undo_depth();
13990 for op in [
13991 json!({ "op": "insert_time", "at": "18s", "duration": "0.5s" }),
13992 json!({ "op": "remove_time", "at": "18s", "duration": "0.5s" }),
13993 json!({ "op": "insert_time", "at": "18s", "duration": "0.5s", "lanes": ["V1"] }),
13994 ] {
13995 let r = ed(&mut srv, json!([op]));
13996 assert!(r.is_error, "{}", r.text);
13997 assert!(r.text.contains("lane A1 is locked"), "{}", r.text);
13998 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth);
13999 }
14000 }
14001
14002 /// A second insert into the first one's hole names the hole it grew, on every lane it grew on.
14003 #[test]
14004 fn a_second_insert_into_a_hole_names_each_lane_that_grew() {
14005 let mut srv = bank();
14006 assert!(!ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "0s" }, { "op": "append", "source": 0 }, { "op": "append", "source": 0 }, { "op": "append", "source": 0 }])).is_error);
14007 assert!(!ed(&mut srv, json!([{ "op": "insert_time", "at": "18s", "duration": "0.5s" }])).is_error);
14008 let r = ed(&mut srv, json!([{ "op": "insert_time", "at": "18s", "duration": "0.5s" }]));
14009 assert!(!r.is_error, "{}", r.text);
14010 assert!(r.text.contains("hole left on V1 at 18.000–19.000s by insert_time"), "{}", r.text);
14011 assert!(r.text.contains("hole left on A1 at 18.000–19.000s by insert_time"), "{}", r.text);
14012 }
14013
14014 /// Splitting a take on its sound lane alone detaches a locked picture clip from the take: it refuses.
14015 #[test]
14016 fn split_and_lift_refuse_to_detach_a_locked_partner() {
14017 let mut srv = slow_first();
14018 srv.session.as_mut().unwrap().set_lane_locked(Lane::V1, true);
14019 let depth = srv.session.as_ref().unwrap().undo_depth();
14020 let r = ed(&mut srv, json!([{ "op": "split", "at": "7s", "lanes": ["A1"] }]));
14021 assert!(r.is_error && r.text.contains("lane V1 is locked"), "{}", r.text);
14022 let l = ed(&mut srv, json!([{ "op": "lift", "clip": "A1@0" }]));
14023 assert!(l.is_error && l.text.contains("lane V1 is locked"), "{}", l.text);
14024 assert_eq!(srv.session.as_ref().unwrap().undo_depth(), depth);
14025 }
14026
14027 /// on:false on a sound clip turns off the waveform picture of its take, as it does on the picture.
14028 #[test]
14029 fn visualizer_off_from_the_sound_clip_turns_its_picture_off() {
14030 let mut srv = bank();
14031 assert!(!ed(&mut srv, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s" }])).is_error);
14032 let on = ed(&mut srv, json!([{ "op": "visualizer", "clip": "A1@0", "on": true }]));
14033 assert!(!on.is_error, "{}", on.text);
14034 let off = ed(&mut srv, json!([{ "op": "visualizer", "clip": "A1@0", "on": false }]));
14035 assert!(!off.is_error, "{}", off.text);
14036 assert!(off.text.contains("visualizer A1@0 off: its waveform picture"), "{}", off.text);
14037 let s = srv.session.as_ref().unwrap();
14038 assert!(s.lanes().into_iter().filter(|l| l.kind == LaneKind::Video).all(|l| s.lane_clips(l).iter().all(|c| c.visualizer == 0)));
14039 }
14040
14041 /// The picture refusal states what the sound needs first: 1x speed for a waveform that matches it.
14042 #[test]
14043 fn a_video_visualizer_refusal_states_the_speed_its_sound_needs() {
14044 let mut srv = slow_first();
14045 let r = ed(&mut srv, json!([{ "op": "visualizer", "clip": "V1@0", "on": true }]));
14046 assert!(r.is_error, "{}", r.text);
14047 assert!(r.text.contains("A1@0 plays at 0.5x: set its speed to 1x first"), "{}", r.text);
14048 }
14049
14050 /// A ripple delete moves titles with the picture: one inside the removed span goes (named, undoable),
14051 /// one the span crosses is trimmed to the part outside, and one after it moves back.
14052 #[test]
14053 fn ripple_delete_removes_trims_and_moves_titles() {
14054 let mut srv2 = bank();
14055 assert!(!ed(&mut srv2, json!([{ "op": "place", "source": 0, "lane": "V1", "at": "0s" }, { "op": "append", "source": 0, "lane": "V1" }, { "op": "append", "source": 0, "lane": "V1" }])).is_error);
14056 let t = ed(&mut srv2, json!([
14057 { "op": "title_add", "at": "3s", "duration": "1s", "text": "T-A" },
14058 { "op": "title_add", "at": "8s", "duration": "1s", "text": "T-B" },
14059 { "op": "title_add", "at": "4.5s", "duration": "1s", "text": "T-C" }
14060 ]));
14061 assert!(!t.is_error, "{}", t.text);
14062 let r = ed(&mut srv2, json!([{ "op": "ripple_delete", "clip": "V1@0" }]));
14063 assert!(!r.is_error, "{}", r.text);
14064 assert!(r.text.contains("T1 3.000s removed with the cut"), "{}", r.text);
14065 assert!(r.text.contains("trimmed to 0.000–0.500s"), "{}", r.text);
14066 assert!(r.text.contains("T3 8.000s→3.000s"), "{}", r.text);
14067 let s = srv2.session.as_ref().unwrap();
14068 let mut titles: Vec<(String, u32, u32)> = s.titles().iter().map(|t| (t.text.clone(), t.start, t.frames)).collect();
14069 titles.sort();
14070 assert_eq!(titles, vec![("T-B".to_string(), 90, 30), ("T-C".to_string(), 0, 15)]);
14071 }
14072
14073 /// A source range ends at the source frame after the last one a clip shows, at the file's own rate.
14074 #[test]
14075 fn a_source_range_ends_after_the_last_source_frame_shown() {
14076 let b = Base { src: 23_976_000, tl: 23_976_000, dur: f64::MAX };
14077 assert_eq!(b.span(0, 48), "src 0.000s–2.002s");
14078 let b = Base { src: 30_000_000, tl: 30_000_000, dur: f64::MAX };
14079 assert_eq!(b.span(0, 150), "src 0.000s–5.000s");
14080 }
14081}
14082
14083#[cfg(test)]
14084mod range_length_tests {
14085 use super::*;
14086 use serde_json::json;
14087
14088 /// A 23.976 source on a 30 fps timeline: each end snaps to a source frame on its own, but the length is
14089 /// the requested duration in timeline frames, so none of these comes out a frame long.
14090 #[test]
14091 fn a_range_from_a_23976_source_is_its_duration_at_30_fps() {
14092 let b = Base { src: 23_976_000, tl: 30_000_000, dur: f64::MAX };
14093 let snap = |secs: f64| b.conform((secs * 23.976 + 0.5).floor() as u32);
14094 let len = |i: f64, o: f64| {
14095 let in_f = snap(i);
14096 range_end(Some(&json!(format!("{i}s"))), &json!(format!("{o}s")), b, 30.0, 1200, in_f, snap(o)) - in_f
14097 };
14098 assert_eq!(len(0.0, 12.0), 360);
14099 assert_eq!(len(20.0, 30.0), 300);
14100 assert_eq!(len(0.0, 15.0), 450);
14101 assert_eq!(len(15.0, 35.0), 600);
14102 // `end` keeps the snapped end, and a range in frames is its own duration too.
14103 assert_eq!(range_end(Some(&json!("0s")), &json!("end"), b, 30.0, 1200, 0, 1200), 1200);
14104 assert_eq!(range_end(Some(&json!("0f")), &json!("288f"), b, 30.0, 1200, 0, 361), 360);
14105 }
14106}
14107
14108#[cfg(test)]
14109mod three_point_tests {
14110 use super::*;
14111 use serde_json::json;
14112 use std::path::Path;
14113
14114 fn asset(name: &str) -> PathBuf {
14115 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
14116 }
14117
14118 /// An empty 30 fps timeline; the library holds src:0 test_av.mp4, src:1 test_av2.mp4,
14119 /// src:2 test_audio_only.mp4, src:3 test_still.png. Then src:0 is placed whole at 0 (V1+A1).
14120 fn bench() -> Server {
14121 engine::ao::set_silent_output();
14122 let mut sess = PlaybackSession::empty(1280, 720, 30.0).expect("empty session");
14123 for f in ["test_av.mp4", "test_av2.mp4", "test_audio_only.mp4", "test_still.png"] {
14124 sess.import(&asset(f)).expect("import");
14125 }
14126 let mut srv = Server { session: Some(sess), ..Server::default() };
14127 let r = ed(&mut srv, json!([{ "op": "place", "source": 0, "at": "0s" }]));
14128 assert!(!r.is_error, "{}", r.text);
14129 srv
14130 }
14131
14132 fn ed(srv: &mut Server, ops: Value) -> Reply {
14133 run_edit(srv, &json!({ "ops": ops }))
14134 }
14135
14136 /// `(start, end, in_frame, source)` of every clip on `lane`.
14137 fn spans(srv: &Server, lane: Lane) -> Vec<(u32, u32, u32, usize)> {
14138 srv.session.as_ref().unwrap().lane_clips(lane).iter().map(|c| (c.start, c.end(), c.in_frame, c.source)).collect()
14139 }
14140
14141 fn link_of(srv: &Server, lane: Lane, idx: usize) -> Option<u32> {
14142 srv.session.as_ref().unwrap().lane_clips(lane)[idx].link
14143 }
14144
14145 #[test]
14146 fn insert_into_the_middle_splits_ripples_and_undoes_in_one_step() {
14147 let mut srv = bench();
14148 let whole = spans(&srv, Lane::V1)[0].1;
14149 let steps = srv.ledger.len();
14150 let r = ed(&mut srv, json!([{ "op": "insert", "src": "src:1", "in": "1s", "out": "2s", "at": "2s" }]));
14151 assert!(!r.is_error, "{}", r.text);
14152 assert!(r.text.contains("split V1@0, A1@0") && r.text.contains("rippled"), "{}", r.text);
14153 let want = vec![(0, 60, 0, 0), (60, 90, 30, 1), (90, whole + 30, 60, 0)];
14154 assert_eq!(spans(&srv, Lane::V1), want);
14155 assert_eq!(spans(&srv, Lane::A1), want);
14156 assert!(link_of(&srv, Lane::V1, 1).is_some() && link_of(&srv, Lane::V1, 1) == link_of(&srv, Lane::A1, 1), "the new take is linked");
14157 assert_eq!(srv.ledger.len(), steps + 1, "one undo step");
14158 let u = run_undo(&mut srv, &json!({}));
14159 assert!(!u.is_error, "{}", u.text);
14160 assert_eq!(spans(&srv, Lane::V1), vec![(0, whole, 0, 0)]);
14161 assert_eq!(spans(&srv, Lane::A1), vec![(0, whole, 0, 0)]);
14162 }
14163
14164 #[test]
14165 fn src_and_source_are_the_same_key_and_not_both() {
14166 let mut srv = bench();
14167 let r = ed(&mut srv, json!([{ "op": "insert", "src": 1, "source": 1, "at": "0s", "length": "1s" }]));
14168 assert!(r.is_error && r.text.contains("not both"), "{}", r.text);
14169 let r = ed(&mut srv, json!([{ "op": "insert", "source": 1, "at": "0s", "length": "1s" }]));
14170 assert!(!r.is_error, "{}", r.text);
14171 assert_eq!(spans(&srv, Lane::V1)[0], (0, 30, 0, 1));
14172 }
14173
14174 #[test]
14175 fn overwrite_across_two_clips_replaces_and_moves_nothing() {
14176 let mut srv = bench();
14177 let whole = spans(&srv, Lane::V1)[0].1;
14178 let r = ed(&mut srv, json!([{ "op": "split", "at": "2s" }]));
14179 assert!(!r.is_error, "{}", r.text);
14180 // 1s..3s of the timeline is 2s of src:1: it covers the end of the first clip and the head of the second.
14181 let r = ed(&mut srv, json!([{ "op": "overwrite", "src": 1, "in": "0s", "at": "1s", "to": "3s" }]));
14182 assert!(!r.is_error, "{}", r.text);
14183 assert!(r.text.contains("overwrote") && r.text.contains("V1@0 cut to") && r.text.contains("V1@60 cut to"), "{}", r.text);
14184 let want = vec![(0, 30, 0, 0), (30, 90, 0, 1), (90, whole, 90, 0)];
14185 assert_eq!(spans(&srv, Lane::V1), want);
14186 assert_eq!(spans(&srv, Lane::A1), want);
14187 let u = run_undo(&mut srv, &json!({}));
14188 assert!(!u.is_error, "{}", u.text);
14189 assert_eq!(spans(&srv, Lane::V1), vec![(0, 60, 0, 0), (60, whole, 60, 0)]);
14190 }
14191
14192 #[test]
14193 fn overwrite_past_the_end_keeps_the_gap() {
14194 let mut srv = bench();
14195 let whole = spans(&srv, Lane::V1)[0].1;
14196 let r = ed(&mut srv, json!([{ "op": "overwrite", "src": 1, "at": format!("{}f", whole + 30), "length": "1s" }]));
14197 assert!(!r.is_error, "{}", r.text);
14198 assert_eq!(spans(&srv, Lane::V1), vec![(0, whole, 0, 0), (whole + 30, whole + 60, 0, 1)]);
14199 assert_eq!(spans(&srv, Lane::A1).len(), 2);
14200 }
14201
14202 #[test]
14203 fn an_audio_only_source_lands_on_an_audio_lane_and_a_partnerless_insert_refuses() {
14204 let mut srv = bench();
14205 // Into V1+A1 material an audio-only insert would pull the take's picture and sound apart.
14206 let r = ed(&mut srv, json!([{ "op": "insert", "src": 2, "at": "1s", "length": "1s" }]));
14207 assert!(r.is_error && r.text.contains("one take with the V1 clip"), "{}", r.text);
14208 assert_eq!(spans(&srv, Lane::A1).len(), 1, "nothing changed");
14209 // Overwrite moves nothing, so it is fine, and only A1 holds the new clip.
14210 let r = ed(&mut srv, json!([{ "op": "overwrite", "src": 2, "at": "1s", "length": "1s" }]));
14211 assert!(!r.is_error, "{}", r.text);
14212 assert!(spans(&srv, Lane::A1).iter().any(|c| c.3 == 2 && c.0 == 30));
14213 assert!(spans(&srv, Lane::V1).iter().all(|c| c.3 == 0));
14214 let v = ed(&mut srv, json!([{ "op": "overwrite", "src": 2, "at": "1s", "length": "1s", "lanes": ["V1"] }]));
14215 assert!(v.is_error && v.text.contains("no picture"), "{}", v.text);
14216 }
14217
14218 #[test]
14219 fn a_still_takes_a_video_lane_and_a_length() {
14220 let mut srv = bench();
14221 let r = ed(&mut srv, json!([{ "op": "overwrite", "src": 3, "at": "1s", "length": "2s" }]));
14222 assert!(!r.is_error, "{}", r.text);
14223 assert!(spans(&srv, Lane::V1).contains(&(30, 90, 0, 3)), "{:?}", spans(&srv, Lane::V1));
14224 assert!(spans(&srv, Lane::A1).iter().all(|c| c.3 == 0), "a still has no sound");
14225 let bad = ed(&mut srv, json!([{ "op": "overwrite", "src": 3, "in": "1s", "at": "0s" }]));
14226 assert!(bad.is_error && bad.text.contains("still"), "{}", bad.text);
14227 }
14228
14229 #[test]
14230 fn a_locked_lane_refuses_and_the_default_skips_it() {
14231 let mut srv = bench();
14232 let r = ed(&mut srv, json!([{ "op": "lane_flags", "lane": "A1", "locked": true }]));
14233 assert!(!r.is_error, "{}", r.text);
14234 let before = spans(&srv, Lane::V1);
14235 let r = ed(&mut srv, json!([{ "op": "overwrite", "src": 1, "at": "1s", "length": "1s", "lanes": ["V1", "A1"] }]));
14236 assert!(r.is_error && r.text.contains("locked"), "{}", r.text);
14237 assert_eq!(spans(&srv, Lane::V1), before);
14238 // With no lanes the default is the first unlocked audio lane: A2, added first.
14239 let r = ed(&mut srv, json!([{ "op": "lane_add", "kind": "audio" }]));
14240 assert!(!r.is_error, "{}", r.text);
14241 let r = ed(&mut srv, json!([{ "op": "overwrite", "src": 1, "at": "1s", "length": "1s" }]));
14242 assert!(!r.is_error, "{}", r.text);
14243 let a2 = spans(&srv, Lane::new(LaneKind::Audio, 1));
14244 assert_eq!(a2, vec![(30, 60, 0, 1)]);
14245 assert_eq!(spans(&srv, Lane::A1).len(), 1, "the locked lane is untouched");
14246 }
14247
14248 #[test]
14249 fn bad_ranges_and_arguments_refuse_by_name() {
14250 let mut srv = bench();
14251 let steps = srv.ledger.len();
14252 for (op, want) in [
14253 (json!({ "op": "insert", "src": 1, "at": "1s", "out": "2s", "length": "1s" }), "not both"),
14254 (json!({ "op": "insert", "src": 1, "at": "2s", "to": "1s" }), "must be after"),
14255 (json!({ "op": "insert", "src": 1, "at": "1s", "to": "2s", "length": "1s" }), "not both"),
14256 (json!({ "op": "insert", "src": 1, "at": "1s", "in": "3s", "out": "2s" }), "not inside"),
14257 (json!({ "op": "insert", "src": 1, "at": "1s", "lanes": [] }), "empty"),
14258 (json!({ "op": "insert", "src": 1, "at": "1s", "lanes": ["V1", "V2"] }), "is not a lane on this timeline"),
14259 (json!({ "op": "insert", "src": 9, "at": "1s" }), "no src:9"),
14260 (json!({ "op": "insert", "src": 1 }), "missing `at`"),
14261 ] {
14262 let r = ed(&mut srv, json!([op]));
14263 assert!(r.is_error && r.text.contains(want), "{want}: {}", r.text);
14264 }
14265 assert_eq!(srv.ledger.len(), steps, "refusals are no undo steps");
14266 }
14267}