From c439c14612e5d6e2402abd87f6b7d7cd5bd8da7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 6 Nov 2026 14:02:09 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20MCP:=20regroup,=20copy=5Fpaste,=20c?= =?UTF-8?q?lose=5Fgap,=20solo=20ops;=20speed=5Framp=20presets;=20cut=5Fsil?= =?UTF-8?q?ence=20modes=20speed=5Fup=20and=20keep=5Fsilence?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- MCP.md | 8 +- crates/app/src/audio_cards.rs | 20 +-- crates/app/src/player/editkeys.rs | 2 +- crates/app/src/player/timeline_edit.rs | 12 +- crates/engine/src/playback.rs | 17 ++ crates/engine/src/project.rs | 50 ++++++ crates/mcp/src/help.rs | 1 + crates/mcp/src/tools/edit.rs | 239 ++++++++++++++++++++++--- crates/mcp/src/tools/hear.rs | 194 ++++++++++++++++++-- 9 files changed, 479 insertions(+), 64 deletions(-) diff --git a/MCP.md b/MCP.md index 687340e..b7c60e4 100644 --- a/MCP.md +++ b/MCP.md @@ -152,12 +152,16 @@ in the GUI. Ops take `scope: "group" | "clip"` where it matters. | `move` | group | `to_lane` must be the same kind (V to V). A drop on empty frames lands exactly there, jumping over the clips between; a head that would land inside a clip stops short, and the reply says what was asked | | `delete` | group | closes the gap; a ripple (below) | | `speed` | group | | -| `speed_ramp` | group | `keys:[{at, speed}…]` (`[]` clears it); a ramp, not a constant rate | +| `speed_ramp` | group | `keys:[{at, speed}…]` (`[]` clears it); a ramp, not a constant rate. `preset:"speed_up"\|"slow_down"\|"fast_middle"\|"slow_middle"` lays the speed card's shape across the clip instead of `keys` | | `reverse` | group | `on?` (absent toggles); picture and sound play backward, length and place unchanged | | `sub_move` | group | captions | | `group` / `ungroup` | — | `group {clips:[…]}`, `ungroup {clip}` | | `lift`, `fade`, `dissolve`, `transition`, `crossfade`, `gain`, `color`, `transform`, `fit`, `eq`, `sub_trim`, `sub_delete`, `cue_text` | clip | act on the one clip named | | `split` | all lanes (or `lanes`) | a cut, not a ripple: nothing moves. `lanes` limits which lanes are cut; a linked partner follows its clip | +| `regroup` | all lanes | `regroup {at}` rejoins the clips that meet at `at` and groups them again: the inverse of `split`, metadata only | +| `copy_paste` | the copied clips | `copy_paste {clips:[addr…], at, lane?}`: one clip pastes as the GUI paste does (splits and ripples the room open); several, or any with `lane`, land as one set and are refused whole if they would overlap. Each copy gets a new link, so group the halves of a copied take after | +| `close_gap` | the gap's take | `close_gap {lane, at}` closes the one gap on `lane` that `at` stands in (the GUI's Close gap); a linked take's other lane closes with it. Captions use `close_gaps` | +| `solo` | — | `solo {lane, on}` for an audio lane: monitoring only, not project state, not saved, never exported, no undo step | | `close_gaps` | one lane | closes the gaps on that lane only | | `delete`, `ripple_delete`, `cut_regions`, `insert_time`, `remove_time`, `speed` with `ripple:true`, `find_words` with `cut:true`, `cut_silence` | the ripple scope (below) | ripple ops: later items move | | `freeze` | one lane | `lane` defaults to V1; `insert` defaults to true | @@ -284,7 +288,7 @@ with timecodes and the source's own frame count. | `scenes` | **source**, range (`{from, to}`, or the array form `[from, to]`), threshold=0.35, min_shot=0.6, sheet | shot list in source frames as `{from, to}` pairs, ready for `keep`: hard cuts and fades to black. Each boundary is the first frame of the new shot, exact to the frame; a fade through black is placed at the first picture frame after the dark run. A range gives the same boundaries as the whole file inside it. A clip address (`V1@450`) scans that clip's source within its span and adds timeline times. A source with no picture is refused. Cached per file and settings; `sheet:true` adds one contact-sheet image, saved in `~/.cache/edith/frames//` and named in the reply | | `levels` | **target**, range, per_sec=2 (a number: buckets per second, default 2, max 50) | RMS dBFS in 20 ms windows, grouped per second; text rows and a summary. Clip gain, its volume envelope and lane gain are included; fades and EQ are not | | `silence` | target, threshold_db, min_silence, padding, min_keep | quiet stretches as timeline frames, the same shape `cut_regions` takes. Clip gain, its envelope and lane gain are applied before judging; fades and EQ are not | -| `cut_silence` | target, threshold_db, min_silence, padding, min_keep, keep=0.4, lanes, force, dry_run | runs `silence`, then shortens every silence to `keep` seconds of pause inside its padded edges (a natural beat survives). The padding at each end is never cut, so the pause left is max(`keep`, 2 × `padding`), and the reply measures it. A silence at or under `keep` is left alone; when none is longer the reply says nothing was cut. A listed silence is at least `min_silence` with its padding counted; `min_keep` defaults to 0. One undo step. `lanes` default: the target's lane and its linked lanes; a mix target cuts every lane. A cut that would remove more than half the target's sound is refused unless `force`. With no target and two or more audio `lanes`, it is a joint cut: the silence is where every listed lane is quiet at once, so their turns stay in step. `src:N` is refused | +| `cut_silence` | target, threshold_db, min_silence, padding, min_keep, keep=0.4, lanes, force, dry_run, mode=cut\|speed_up\|keep_silence, rate=4 | `mode:"speed_up"` plays each silence at `rate` (1.05–4) instead of cutting it, as the GUI's speed silences do; `mode:"keep_silence"` cuts the speech and keeps the silence (one target, no joint cut), as keep-only silence does; both take no `keep`, and neither is limited by the more-than-half guard (`force` is for `cut`); `speed_up` leaves titles where they were. Default `mode:"cut"`: runs `silence`, then shortens every silence to `keep` seconds of pause inside its padded edges (a natural beat survives). The padding at each end is never cut, so the pause left is max(`keep`, 2 × `padding`), and the reply measures it. A silence at or under `keep` is left alone; when none is longer the reply says nothing was cut. A listed silence is at least `min_silence` with its padding counted; `min_keep` defaults to 0. One undo step. `lanes` default: the target's lane and its linked lanes; a mix target cuts every lane. A cut that would remove more than half the target's sound is refused unless `force`. With no target and two or more audio `lanes`, it is a joint cut: the silence is where every listed lane is quiet at once, so their turns stay in step. `src:N` is refused | | `loudness` | **target**, range | EBU R128: integrated LUFS, loudness range, true peak, max momentary and short-term. Clip and lane gain, clip speed, fades and EQ are included as played | | `clean_voice` | lane=A1, strength=medium (light, medium, strong), noise_from | gate + spectral noise reduction + compressor + de-esser on one audio lane, as one undo step. The noise profile is learned from `noise_from` (`{from, to}`) or, by default, the quietest half second of the lane; if none is found noise reduction is left off and the reply says so. The timeline, `clip_info` and `project_status` list the processors that are on | | `track` | clip, effect_index, from?, to?, direction?=forward\|backward, apply?=mask, cancel? | follows a rect or ellipse mask's box through a clip in the background (sub-pixel normalised cross-correlation, the template learned slowly); the mask's centre takes the feature's path, size and soft edge kept. from/to are clip-relative times, default the whole clip. Stops where the feature is lost (flat or line-only patch, or a rival match nearly as good) and says at which frame. Titles cannot be tracked (no keyable position). The path follows the clip's placement (position, scale, rotation, crop and transform keys). Not yet: a source stored turned (a phone's portrait video) or with non-square pixels is tracked as stored. `cancel:true` stops the clip's tracks | diff --git a/crates/app/src/audio_cards.rs b/crates/app/src/audio_cards.rs index 372342e..55bd787 100644 --- a/crates/app/src/audio_cards.rs +++ b/crates/app/src/audio_cards.rs @@ -68,17 +68,17 @@ impl RampPreset { /// The keys of the shape over a clip `frames` timeline frames long. `None` when the /// clip is too short to hold the shape's keys one frame apart. pub(crate) fn keys(self, frames: u32) -> Option> { - let key = |at: u32, permille: u16| engine::project::SpeedKey { - at, - speed: Speed::from_permille(permille), - }; + self.shape().keys(frames) + } + + /// The engine's shape this chip lays: the same four, named there so the MCP can take them too. + pub(crate) fn shape(self) -> engine::project::SpeedRampShape { + use engine::project::SpeedRampShape as Shape; match self { - RampPreset::Up => (frames >= 1).then(|| vec![key(0, 1000), key(frames, 2000)]), - RampPreset::Down => (frames >= 1).then(|| vec![key(0, 2000), key(frames, 1000)]), - RampPreset::SlowFastSlow => (frames >= 2) - .then(|| vec![key(0, 500), key(frames / 2, 2000), key(frames, 500)]), - RampPreset::FastSlowFast => (frames >= 2) - .then(|| vec![key(0, 2000), key(frames / 2, 500), key(frames, 2000)]), + RampPreset::Up => Shape::SpeedUp, + RampPreset::Down => Shape::SlowDown, + RampPreset::SlowFastSlow => Shape::FastMiddle, + RampPreset::FastSlowFast => Shape::SlowMiddle, } } } diff --git a/crates/app/src/player/editkeys.rs b/crates/app/src/player/editkeys.rs index 6ddb7be..aff2935 100644 --- a/crates/app/src/player/editkeys.rs +++ b/crates/app/src/player/editkeys.rs @@ -66,7 +66,7 @@ pub(crate) fn gap_under(session: &PlaybackSession, frame: u32) -> Option<(Lane, .lanes() .into_iter() .filter(|l| l.kind != LaneKind::Subtitle) - .find_map(|l| crate::timeline_math::between_clips(session.gap_at(l, frame)).map(|(start, frames)| (l, start, frames))) + .find_map(|l| session.closable_gap_at(l, frame).map(|(start, frames)| (l, start, frames))) } diff --git a/crates/app/src/player/timeline_edit.rs b/crates/app/src/player/timeline_edit.rs index d6ec765..a8d72b1 100644 --- a/crates/app/src/player/timeline_edit.rs +++ b/crates/app/src/player/timeline_edit.rs @@ -1718,16 +1718,8 @@ impl Player { let Some(session) = self.session.as_mut() else { return; }; - let scope = match session.gap_take_scope(lane, start, frames) { - Ok(scope) => scope, - Err(e) => { - self.notify_user(e.to_string().into()); - cx.notify(); - return; - } - }; - match session.cut_regions(&[(start, frames)], &scope) { - Ok(()) => { + match session.close_gap_at(lane, start, frames) { + Ok(scope) => { self.mark_dirty(); // The ripple moves every index after the gap on the scoped // lanes, the same reason a delete drops the selection. diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 2bf31c2..5950a1c 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -3266,6 +3266,23 @@ impl PlaybackSession { self.project.gap_at(lane, frame) } + /// The gap a Close gap verb closes on `lane` at `frame`: [`gap_at`](Self::gap_at), but + /// only a gap that starts after frame 0. A lead-in before a lane's first clip is empty + /// time, not a gap a hand made, so it is never closed. + pub fn closable_gap_at(&self, lane: Lane, frame: u32) -> Option<(u32, u32)> { + self.gap_at(lane, frame).filter(|&(start, _)| start > 0) + } + + /// Closes the gap `(start, frames)` on `lane` and, when it borders a take, on the take's + /// other lane too: the scope [`gap_take_scope`](Self::gap_take_scope) names, cut out by + /// [`cut_regions`](Self::cut_regions). Returns that scope, so a caller can say what moved. + /// The `Err` names what is in the way and nothing changes. + pub fn close_gap_at(&mut self, lane: Lane, start: u32, frames: u32) -> crate::Result> { + let scope = self.gap_take_scope(lane, start, frames)?; + self.cut_regions(&[(start, frames)], &scope)?; + Ok(scope) + } + /// How many bounded gaps that same right-click lane holds. The tail after /// the last placement is not counted, because nothing would ripple there. pub fn gap_count(&self, lane: Lane) -> usize { diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index e851722..2aee544 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -347,6 +347,56 @@ pub struct SpeedKey { pub speed: Speed, } +/// The four ramp shapes a clip's speed can be laid in: the speed card and the palette lay them +/// across a clip's length, and the MCP `speed_ramp` takes them by name ([`SpeedRampShape::name`]). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum SpeedRampShape { + /// Real time easing up to double. + SpeedUp, + /// Double easing down to real time. + SlowDown, + /// Slow, then fast through the middle, then slow: the classic speed ramp. + FastMiddle, + /// Fast, then slow through the middle, then fast: the hero shot. + SlowMiddle, +} + +impl SpeedRampShape { + /// Every shape, in the order the speed card shows them. + pub const ALL: [SpeedRampShape; 4] = [ + SpeedRampShape::SpeedUp, + SpeedRampShape::SlowDown, + SpeedRampShape::FastMiddle, + SpeedRampShape::SlowMiddle, + ]; + + /// The shape's name as the MCP takes it: `speed_up`, `slow_down`, `fast_middle` or `slow_middle`. + pub fn name(self) -> &'static str { + match self { + SpeedRampShape::SpeedUp => "speed_up", + SpeedRampShape::SlowDown => "slow_down", + SpeedRampShape::FastMiddle => "fast_middle", + SpeedRampShape::SlowMiddle => "slow_middle", + } + } + + /// The keys of the shape over a clip `frames` timeline frames long. `None` when the clip is + /// too short to hold the shape's keys one frame apart. + pub fn keys(self, frames: u32) -> Option> { + let key = |at: u32, permille: u16| SpeedKey { at, speed: Speed::from_permille(permille) }; + match self { + SpeedRampShape::SpeedUp => (frames >= 1).then(|| vec![key(0, 1000), key(frames, 2000)]), + SpeedRampShape::SlowDown => (frames >= 1).then(|| vec![key(0, 2000), key(frames, 1000)]), + SpeedRampShape::FastMiddle => { + (frames >= 2).then(|| vec![key(0, 500), key(frames / 2, 2000), key(frames, 500)]) + } + SpeedRampShape::SlowMiddle => { + (frames >= 2).then(|| vec![key(0, 2000), key(frames / 2, 500), key(frames, 2000)]) + } + } + } +} + /// The source position a speed ramp has carried a clip through by its clip-relative /// timeline frame `t`: the integral of the piecewise-linear speed from frame 0 to /// `t`, in source frames (fractional). Each segment's integral is the trapezoid of diff --git a/crates/mcp/src/help.rs b/crates/mcp/src/help.rs index 3c0c6d0..eaa68cc 100644 --- a/crates/mcp/src/help.rs +++ b/crates/mcp/src/help.rs @@ -145,6 +145,7 @@ RECIPES silence: judged inside clips only; the timeline gaps between a lane's clips are structure and are reported, never listed or cut. Default threshold: 30 dB under the target's median speech level (−90..−10 dBFS); the reply names the value used. min_silence is judged before padding. cut_silence: a silence that runs to the end of its clip keeps `keep` in all after the last speech, its end padding included. Gaps between clips are never cut. Caption lanes ripple with the cut; locked caption lanes stay (a locked caption lane in the scope is skipped with a note). + mode:\"speed_up\" plays each silence faster instead of cutting it (rate 1.05–4, default 4); mode:\"keep_silence\" cuts the speech and keeps the silence (one target, no joint cut). Both take dry_run and undo like the cut. Normalize loudness: measure the mix, then set it. loudness {target:\"mix\"}, then normalize {target:\"mix\", lufs:-14}; its reply leads with whether the target was reached. When the true-peak ceiling holds the gain back (the reply's capped_by is true_peak), add allow_limiter:true with true_peak set to the ceiling (-1 for lossless, -2 for lossy): the limiter then lets the mix reach the target, and the reply says it switched the limiter on. diff --git a/crates/mcp/src/tools/edit.rs b/crates/mcp/src/tools/edit.rs index cf515a9..619582e 100644 --- a/crates/mcp/src/tools/edit.rs +++ b/crates/mcp/src/tools/edit.rs @@ -33,7 +33,7 @@ const OWN_OPS: &[&str] = &[ "chapter_add", "chapter_set", "chapter_remove", "marker_add", "marker_set", "marker_remove", "beats", "place", "insert", "overwrite", "append", "keep", "assemble", "split", "trim", "split_edit", "roll", "slip", "slide", "move", "delete", "lift", "ripple_delete", "close_gaps", "cut_regions", "insert_time", "remove_time", "freeze", "speed", "speed_ramp", "reverse", "fade", "dissolve", "transition", "crossfade", "visualizer", - "swap", "copy_look", "replace", "nudge", + "swap", "copy_look", "replace", "nudge", "regroup", "copy_paste", "close_gap", "solo", ]; /// Ops `edit_fx` answers. @@ -96,7 +96,11 @@ insert_time {at, duration, lanes?} — ripple empty time in at `at`: clips, capt remove_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). TIME speed {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. -speed_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 8, 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. +speed_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 8, 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. +regroup {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). +copy_paste {clips:[addr,...], at, lane?} — pastes copies of the named clips at `at`, with their effects, keys and volume, keeping their spacing. 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). Each copy gets a new link, as the GUI's paste gives it: the halves of a copied take come back unlinked to each other, so group them after with group {clips}. +close_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. +solo {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. reverse {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. fade {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. dissolve {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. @@ -268,6 +272,10 @@ fn accepted_keys(name: &str) -> Option<&'static [&'static str]> { "keep" => &["source", "ranges", "lane", "at", "audio", "audio_lane", "overwrite"], "assemble" => &["items", "lane", "at", "gap", "audio", "audio_lane", "overwrite"], "split" => &["at", "lanes"], + "regroup" => &["at"], + "copy_paste" => &["clips", "at", "lane"], + "close_gap" => &["lane", "at"], + "solo" => &["lane", "on"], "trim" => &["clip", "edge", "to", "scope", "ripple"], "roll" => &["clip", "by", "to", "edge"], "split_edit" => &["clip", "side", "edge", "to"], @@ -284,7 +292,7 @@ fn accepted_keys(name: &str) -> Option<&'static [&'static str]> { "insert_time" | "remove_time" => &["at", "duration", "lanes"], "freeze" => &["at", "duration", "lane", "insert"], "speed" => &["clip", "x", "ripple", "lanes"], - "speed_ramp" => &["clip", "keys", "ripple", "lanes"], + "speed_ramp" => &["clip", "keys", "preset", "ripple", "lanes"], "reverse" => &["clip", "on"], "fade" => &["clip", "in", "out", "linked"], "dissolve" | "transition" => &["clip", "frames", "length", "kind", "direction", "linked"], @@ -4766,6 +4774,176 @@ fn op_close_gaps(s: &mut PlaybackSession, op: &Value) -> Result { Ok(Done { text, touched, lanes: vec![lane] }) } +/// `close_gap {lane, at}`: closes the one gap on `lane` that `at` stands in, the way the GUI's Close +/// gap does: the gap's take scope ([`PlaybackSession::gap_take_scope`]) is cut out together, so a +/// linked partner closes with it. Nothing else moves. +fn op_close_gap(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result { + let lane = lane_arg(op, "lane")?.ok_or("missing `lane`: give a lane such as V1")?; + let at = need(op, "at", fps, end)?; + let name = parse::lane_name(lane); + if lane.kind == LaneKind::Subtitle { + return Err(format!("close_gap {name}: captions have no gap closed this way; use close_gaps {{lane:\"{name}\"}}")); + } + let Some((start, frames)) = s.closable_gap_at(lane, at) else { + return Err(format!( + "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", + shown_time(op.get("at"), at) + )); + }; + let scope = s.gap_take_scope(lane, start, frames).map_err(|e| e.to_string())?; + check_unlocked(s, &scope)?; + let scope = s.close_gap_at(lane, start, frames).map_err(|e| e.to_string())?; + let names: Vec = scope.iter().map(|&l| parse::lane_name(l)).collect(); + let take = if scope.len() > 1 { format!(" with its take on {}", names.join(", ")) } else { String::new() }; + let text = format!( + "close_gap {name}: closed {}–{} ({frames}f){take}", + secs_text(start, fps), + secs_text(start + frames, fps) + ); + Ok(Done { text, touched: ripple_touched(s, &scope, start), lanes: scope }) +} + +/// `regroup {at}`: rejoins the clips that meet at `at` in every lane and puts them back in one group, +/// the inverse of `split`. The GUI's Regroup does the same at the playhead, through the same engine door. +fn op_regroup(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result { + let at = need(op, "at", fps, end)?; + let shown = shown_time(op.get("at"), at); + if !s.regroup_at(parse::secs(at, fps)) { + return Err(format!( + "regroup {shown}: nothing to rejoin there; no cut sits at that frame, or the clips on it were never split apart" + )); + } + let lanes: Vec = s.lanes().into_iter().filter(|&l| s.lane_clips(l).iter().any(|c| c.start == at)).collect(); + let touched = lanes.iter().map(|&l| (l, at)).collect(); + let names: Vec = lanes.iter().map(|&l| parse::lane_name(l)).collect(); + Ok(Done { text: format!("regroup {shown}: the cut is rejoined on {}", names.join(", ")), touched, lanes }) +} + +/// `solo {lane, on}`: solos an audio lane for listening, so only the soloed lanes are heard while this +/// session plays. Solo is monitoring only: it is not project state, it is not saved, and an export never +/// reads it, so it leaves no undo step and marks nothing changed. +fn op_solo(s: &mut PlaybackSession, op: &Value) -> Result { + let lane = lane_arg(op, "lane")?.ok_or("missing `lane`: give an audio lane such as A1")?; + let name = parse::lane_name(lane); + if lane.kind != LaneKind::Audio { + return Err(format!("solo {name}: only audio lanes solo, and {name} is not one")); + } + let on = match op.get("on") { + Some(Value::Bool(b)) => *b, + None | Some(Value::Null) => return Err("missing `on`: true solos the lane, false un-solos it".into()), + Some(_) => return Err("`on` must be true or false".into()), + }; + let mut solo: Vec = s.soloed().to_vec(); + if on { + if !solo.contains(&lane) { + solo.push(lane); + } + } else { + solo.retain(|&l| l != lane); + } + let changed = s.set_solo(&solo); + let text = if s.soloed().is_empty() { + format!("solo {name}: {}", if changed { "solo cleared, every audio lane plays" } else { "no solo to clear" }) + } else { + let names: Vec = s.soloed().iter().map(|&l| parse::lane_name(l)).collect(); + let state = if changed { "soloed" } else { "already soloed" }; + format!("solo {name}: {state}; only {} play while listening (monitoring only: not saved, not exported)", names.join(", ")) + }; + Ok(Done { text, touched: Vec::new(), lanes: Vec::new() }) +} + +/// The ramp shape `preset` names, or None when it is absent. The names are the speed card's chips. +fn preset_arg(op: &Value) -> Result, String> { + let Some(v) = op.get("preset").filter(|v| !v.is_null()) else { return Ok(None) }; + let t = v.as_str().ok_or("`preset` must be one of speed_up, slow_down, fast_middle, slow_middle")?; + engine::project::SpeedRampShape::ALL + .into_iter() + .find(|shape| shape.name() == t) + .map(Some) + .ok_or_else(|| format!("`preset` {t} is not one of speed_up, slow_down, fast_middle, slow_middle")) +} + +/// `copy_paste {clips:[addr...], at, lane?}`: the GUI's copy and paste, through the same engine doors. +/// One clip goes in as the GUI's single paste does (`paste_at`: it splits the clip under `at` and ripples +/// the room open). Several, or any clip with `lane`, go in as one set (`paste_set_at`): each keeps its +/// own lane and its spacing from the others, and the set is refused whole rather than opening room. +/// `lane` puts every copy on that lane, which must be the kind (V or A) of each copied clip. +fn op_copy_paste(s: &mut PlaybackSession, op: &Value, fps: f64, end: u32) -> Result { + let at = need(op, "at", fps, end)?; + let shown = shown_time(op.get("at"), at); + let raw = op + .get("clips") + .and_then(Value::as_array) + .filter(|a| !a.is_empty()) + .ok_or("missing `clips`: give the clip addresses to copy, e.g. [\"V1@0\", \"A1@0\"]")?; + let mut picks: Vec<(Lane, usize)> = Vec::with_capacity(raw.len()); + for v in raw { + let addr = v.as_str().ok_or("`clips` lists clip addresses such as \"V1@0\"")?; + let (lane, idx) = clip_addr(s, addr).map_err(|e| format!("copy_paste clips: {e}"))?; + if lane.kind == LaneKind::Subtitle { + return Err(format!("{addr} is a caption lane; copy_paste takes media clips")); + } + if !picks.contains(&(lane, idx)) { + picks.push((lane, idx)); + } + } + let target = lane_arg(op, "lane")?; + let mut items: Vec<(Lane, Clip)> = picks.iter().map(|&(l, i)| (l, s.lane_clips(l)[i].clone())).collect(); + if let Some(to) = target { + if let Some(&(l, _)) = items.iter().find(|(l, _)| l.kind != to.kind) { + return Err(format!( + "copy_paste: {} is on {} and `lane` {} is not, so the copy would not go there; name a lane of the same kind", + parse::lane_name(l), + if l.kind == LaneKind::Audio { "a sound lane" } else { "a picture lane" }, + parse::lane_name(to) + )); + } + for item in &mut items { + item.0 = to; + } + } + let mut locks: Vec = picks.iter().map(|&(l, _)| l).collect(); + locks.extend(target); + check_unlocked(s, &locks)?; + // The clips already there, as (lane, source, in, out): what the paste adds is read by difference. + let key = |l: Lane, c: &Clip| (l, c.source, c.in_frame, c.out_frame); + 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::>()).collect(); + let shape_before = shape(s); + let pasted = match items.as_slice() { + [(_, clip)] if target.is_none() => s.paste_at(parse::secs(at, fps), clip.clone()), + _ => s.paste_set_at(parse::secs(at, fps), &items), + }; + if !pasted { + let why = if items.len() > 1 || target.is_some() { + format!("the set would land on a clip on its lane at {shown} (a set-paste opens no room)") + } else { + format!("the clip would not go in at {shown}") + }; + return Err(format!("copy_paste refused: {why}; nothing changed")); + } + // The copies are the clips the paste added: the before list minus what is still there, by key. + let mut pending = before; + let mut landed: Vec<(Lane, u32)> = Vec::new(); + for l in s.lanes() { + for c in s.lane_clips(l) { + match pending.iter().position(|k| *k == key(l, c)) { + Some(p) => { + pending.swap_remove(p); + } + None => landed.push((l, c.start)), + } + } + } + let addrs: Vec = landed.iter().map(|&(l, start)| parse::addr(l, start)).collect(); + let effects = side_effects(&shape_before, &shape(s), "copy_paste"); + let mut text = format!("copy_paste {} clip(s) at {shown}: pasted {}", items.len(), addrs.join(", ")); + if !effects.is_empty() { + text.push_str(&format!("; effects: {}", effects.join("; "))); + } + let lanes: Vec = landed.iter().map(|&(l, _)| l).collect(); + Ok(Done { text, touched: landed, lanes }) +} + /// Where the last clip or caption on `lane` ends, in timeline frames (0 for an empty lane). fn lane_end(s: &PlaybackSession, lane: Lane) -> u32 { if lane.kind == LaneKind::Subtitle { @@ -5054,26 +5232,39 @@ fn op_speed_ramp(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result return Err("missing `keys`: give a list of {at, speed}, or [] to clear the ramp".into()), - Some(Value::Array(a)) => a, - Some(_) => return Err("`keys` must be a list of {at, speed} objects".into()), - }; - if raw.len() > engine::project::MAX_SPEED_KEYS { - return Err(format!("a speed ramp takes at most {} keys", engine::project::MAX_SPEED_KEYS)); - } - let mut keys = Vec::with_capacity(raw.len()); - for k in raw { - let at = k.get("at").ok_or_else(|| "each key needs `at`: a time such as 0s, 2s or end".to_string())?; - let at = parse::frame(at, fps, clip_frames)?; - let speed = match k.get("speed") { - None | Some(Value::Null) => return Err("each key needs `speed`: a number between 0.25 and 4".into()), - Some(v) => v.as_f64().ok_or_else(|| format!("`speed` must be a number between 0.25 and 4, not {v}"))?, - }; - if !(0.25..=4.0).contains(&speed) { - return Err(format!("speed {} is outside 0.25–4", compact(speed))); + let mut keys: Vec = Vec::new(); + match preset_arg(op)? { + // A preset lays the speed card's shape across the clip's length, as the card's chip does. + Some(shape) => { + if op.get("keys").is_some_and(|v| !v.is_null()) { + return Err("speed_ramp takes `keys` or `preset`, not both".into()); + } + keys = shape.keys(clip_frames).ok_or_else(|| { + format!("speed_ramp {addr}: the clip is too short for {} (it needs at least 2 frames)", shape.name()) + })?; + } + None => { + let raw = match op.get("keys") { + 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()), + Some(Value::Array(a)) => a, + Some(_) => return Err("`keys` must be a list of {at, speed} objects".into()), + }; + if raw.len() > engine::project::MAX_SPEED_KEYS { + return Err(format!("a speed ramp takes at most {} keys", engine::project::MAX_SPEED_KEYS)); + } + for k in raw { + let at = k.get("at").ok_or_else(|| "each key needs `at`: a time such as 0s, 2s or end".to_string())?; + let at = parse::frame(at, fps, clip_frames)?; + let speed = match k.get("speed") { + None | Some(Value::Null) => return Err("each key needs `speed`: a number between 0.25 and 4".into()), + Some(v) => v.as_f64().ok_or_else(|| format!("`speed` must be a number between 0.25 and 4, not {v}"))?, + }; + if !(0.25..=4.0).contains(&speed) { + return Err(format!("speed {} is outside 0.25–4", compact(speed))); + } + keys.push(engine::project::SpeedKey { at, speed: Speed::from_permille((speed * 1000.0).round() as u16) }); + } } - keys.push(engine::project::SpeedKey { at, speed: Speed::from_permille((speed * 1000.0).round() as u16) }); } if !keys.is_empty() && !engine::project::valid_speed_keys(&keys) { return Err("speed ramp keys must be in strictly increasing order of `at`, one per time".into()); @@ -6282,6 +6473,10 @@ fn run_op_inner(s: &mut PlaybackSession, name: &str, op: &Value, fps: f64, proje "keep" => op_keep(s, op, fps, end), "assemble" => op_assemble(s, op, fps, end), "split" => op_split(s, op, fps, end), + "regroup" => op_regroup(s, op, fps, end), + "copy_paste" => op_copy_paste(s, op, fps, end), + "close_gap" => op_close_gap(s, op, fps, end), + "solo" => op_solo(s, op), "trim" => op_trim(s, op, fps, end), "split_edit" => op_split_edit(s, op, fps, end), "roll" => op_roll(s, op, fps, end), diff --git a/crates/mcp/src/tools/hear.rs b/crates/mcp/src/tools/hear.rs index ea470b2..cca64e3 100644 --- a/crates/mcp/src/tools/hear.rs +++ b/crates/mcp/src/tools/hear.rs @@ -20,7 +20,7 @@ use engine::project::{ GainKey, Lane, LaneKind, MAX_CLIP_GAIN_DB, MAX_GAIN_DB, MIN_GAIN_DB, RedoCheckpoint, gain_keys_db_at, }; use engine::silence::{self, SILENT_DB, Settings, WINDOWS_PER_SEC}; -use engine::{Clip, PlaybackSession}; +use engine::{Clip, PlaybackSession, Speed}; use serde_json::{Value, json}; use crate::parse; @@ -54,7 +54,8 @@ force: a cut that would remove more than half the target's sound is refused, wit lanes: the lanes to cut. With a target, lanes is the RIPPLE SCOPE: the silence is judged on the target alone, and the same spans are cut on every listed lane (the target's own lane is added when it is not listed). Default with no lanes: the target's lane and the lanes of clips linked (grouped) to it, so linked video follows the sound while picture-only B-roll stays put; a mix target cuts every lane. A take must stay whole, or the engine refuses and says why; a lane not named never moves, and the reply names it as left in place (a music bed: name it in lanes to move it too). JOINT CUT: lanes:["A1","A2"] (two speakers in a conversation, say) with no target. The silence is where EVERY listed audio lane is quiet at once: each lane is judged on its own clips at its own threshold (or threshold_db for all when given), and a timeline gap on a lane counts as quiet for it, so the joint silence is a stretch where the other listed lanes are quiet too, and a stretch where no listed lane has a clip is never cut. The cut is made on the listed lanes together, so their turns stay in step. A video lane in a joint list is cut with the spans but not judged, and a joint cut needs two or more audio lanes in its list. A target with lanes is never a joint cut: there lanes is the ripple scope, judged on the target alone. Locks follow the ripple rule: a locked target, or a locked lane named in lanes, refuses the cut with the lane_flags way out; a mix's default scope (every lane) refuses the same way, naming each locked lane, and changes nothing. dry_run: report what would be cut, then roll back. Nothing changed and no undo step is added. -The reply names the pause each cut left as "pauses now X s", measured back from the sound after the cut: the lane's for a lane or clip, the mix as exported for a mix, the joint quiet for a joint cut (frames are 1/fps, so a keep that is not a whole frame reads a frame over at most)."#; +The reply names the pause each cut left as "pauses now X s", measured back from the sound after the cut: the lane's for a lane or clip, the mix as exported for a mix, the joint quiet for a joint cut (frames are 1/fps, so a keep that is not a whole frame reads a frame over at most). +mode: cut (default, as above) · speed_up: each silence plays at rate (1.05–4, default 4) instead of being cut, the room it no longer needs closed, as the GUI's speed silences do; keep and force do not apply, and titles keep their times · keep_silence: the speech is cut and the silence kept, the GUI's keep-only silence; one target only (no joint cut), its share guard does not apply since the speech is the point. Both take dry_run and undo as cut does."#; /// The pause cut_silence leaves at each cut when neither `keep` nor `padding` is given. const DEFAULT_KEEP: f64 = 0.4; @@ -176,6 +177,21 @@ fn cut_silence_schema() -> Value { "dry_run".into(), json!({ "type": "boolean", "description": "Report what would be cut, then roll back." }), ); + props.insert( + "mode".into(), + json!({ + "type": "string", + "enum": ["cut", "speed_up", "keep_silence"], + "description": "cut (default): shorten each silence to keep. speed_up: play each silence at rate instead of cutting it (the GUI's speed-silences). keep_silence: cut the speech and keep the silence (the GUI's keep-only silence); one target only." + }), + ); + props.insert( + "rate".into(), + json!({ + "type": "number", "minimum": 1.05, "maximum": 4, + "description": "mode speed_up only: the speed each silence plays at, 1.05 to 4. Default 4 (the GUI's default)." + }), + ); json!({ "type": "object", "properties": props }) } @@ -1326,6 +1342,94 @@ pub(super) fn record_pushes(srv: &mut Server, start: u64, label: String) { /// The shortest pause a cut may leave: below it the pause is not a pause a person can hear. const MIN_KEEP_SECS: f64 = 0.05; +/// The slowest a speed_up plays a silence at: the GUI's silence rate starts one step above real time. +const MIN_SILENCE_RATE: f64 = 1.05; + +/// What cut_silence does to each silence it finds: cut it back to `keep` (the default), play it at a +/// speed, or cut the speech and keep the silence (the GUI's keep-only silence). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum CutMode { + Cut, + SpeedUp, + KeepSilence, +} + +impl CutMode { + /// The word the `mode` argument takes for this mode. + fn name(self) -> &'static str { + match self { + CutMode::Cut => "cut", + CutMode::SpeedUp => "speed_up", + CutMode::KeepSilence => "keep_silence", + } + } +} + +/// `mode`, or cut when it is absent. +fn cut_mode(args: &Value) -> Result { + match args.get("mode") { + None | Some(Value::Null) => Ok(CutMode::Cut), + Some(Value::String(t)) => match t.as_str() { + "cut" => Ok(CutMode::Cut), + "speed_up" => Ok(CutMode::SpeedUp), + "keep_silence" => Ok(CutMode::KeepSilence), + other => Err(format!("`mode` {other} is not one of cut, speed_up, keep_silence")), + }, + Some(_) => Err("`mode` is a word: cut, speed_up or keep_silence".into()), + } +} + +/// `rate`, the speed a speed_up plays each silence at: 1.05 to 4 (the GUI's silence rate), or None when +/// it is absent. The GUI's default is the top rate, 4, which the caller applies. +fn speed_rate(args: &Value) -> Result, String> { + match args.get("rate") { + None | Some(Value::Null) => Ok(None), + Some(v) => match v.as_f64() { + Some(x) if x.is_finite() && (MIN_SILENCE_RATE..=4.0).contains(&x) => { + Ok(Some(Speed::from_permille((x * 1000.0).round() as u16))) + } + _ => Err(format!("`rate` is the speed a silence plays at, from {MIN_SILENCE_RATE} to 4")), + }, + } +} + +/// The timeline spans a target's sound covers, as `(from, to)` frames: a clip's own span, a lane's +/// clips, or the whole mix. Empty for a source file, which has no place on the timeline. +fn target_windows(s: &PlaybackSession, t: &Target) -> Vec<(u32, u32)> { + match t { + Target::Clip(_, c) => vec![(c.start, c.end())], + Target::Lane(l) => s.lane_clips(*l).iter().map(|c| (c.start, c.end())).collect(), + Target::Mix => vec![(0, parse::session_end(s))], + Target::Source(_) => Vec::new(), + } +} + +/// The speech a keep_silence cut takes out: the stretches of each window that the quiet `quiet` +/// does not cover, as `(start, len)` timeline frames. The complement is taken with +/// `silence::invert` inside each window, as the GUI's keep-only silence does per clip. +fn speech_within(windows: &[(u32, u32)], quiet: &[(u32, u32)], fps: f64) -> Vec<(u32, u32)> { + let mut out = Vec::new(); + for &(a, b) in windows { + if b <= a { + continue; + } + let duration = f64::from(b - a) / fps; + let inside: Vec<(f64, f64)> = quiet + .iter() + .filter(|&&(qa, qb)| qb > a && qa < b) + .map(|&(qa, qb)| (f64::from(qa.max(a) - a) / fps, f64::from(qb.min(b) - a) / fps)) + .collect(); + for (from, to) in silence::invert(duration, &inside) { + let start = a + (from * fps).round() as u32; + let end = (a + (to * fps).round() as u32).min(b); + if end > start { + out.push((start, end - start)); + } + } + } + out +} + /// `keep` in seconds, 0.05 to 10, or absent. fn keep_secs(args: &Value) -> Result, String> { match args.get("keep") { @@ -1490,6 +1594,22 @@ fn run_cut_silence(srv: &mut Server, args: &Value) -> Reply { Ok(k) => k.unwrap_or(DEFAULT_KEEP), Err(e) => return fail(e), }; + let mode = match cut_mode(args) { + Ok(m) => m, + Err(e) => return fail(e), + }; + let rate = match speed_rate(args) { + Ok(r) => r, + Err(e) => return fail(e), + }; + if mode != CutMode::Cut && args.get("keep").is_some_and(|v| !v.is_null()) { + return fail(format!("`keep` is the pause mode cut leaves; {} takes no keep", mode.name())); + } + if mode != CutMode::SpeedUp && rate.is_some() { + return fail(format!("`rate` is the speed of mode speed_up; {} takes no rate", mode.name())); + } + // The GUI's silence rate defaults to its top speed. + let speed = rate.unwrap_or(Speed::MAX); let dry = opt_bool(args, "dry_run").unwrap_or(false); // A cut that is rolled back (a dry run, or a refused cut) leaves the project as it was. let was_clean = !super::project::dirty(srv); @@ -1501,6 +1621,9 @@ fn run_cut_silence(srv: &mut Server, args: &Value) -> Reply { Ok(j) => j, Err(e) => return fail(e), }; + if mode == CutMode::KeepSilence && joint.is_some() { + return fail("mode keep_silence takes one target, not a joint cut: name the target and drop lanes".into()); + } let target = match &joint { Some(_) => None, None => match target_arg(s, args) { @@ -1626,15 +1749,28 @@ fn run_cut_silence(srv: &mut Server, args: &Value) -> Reply { .iter() .flat_map(|&l| s.lane_clips(l).iter().map(|c| c.end())) .collect(); - let spans = cut_spans_for(&found.regions, keep, cfg.padding, fps, &clip_ends); + // What each mode acts on: the silence cut back to keep, the silence itself (played fast), or the + // speech inside the target (kept silence). All are (start, len) timeline frames. + let spans = match mode { + CutMode::Cut => cut_spans_for(&found.regions, keep, cfg.padding, fps, &clip_ends), + CutMode::SpeedUp => found.regions.iter().map(|&(a, b)| (a, b - a)).collect(), + CutMode::KeepSilence => match &target { + Some(t) => speech_within(&target_windows(s, t), &found.regions, fps), + None => Vec::new(), + }, + }; let gaps = match (&joint, &target) { (Some(lanes), _) => gap_note(s, lanes, fps), (None, Some(Target::Lane(l))) => gap_note(s, &[*l], fps), _ => String::new(), }; if spans.is_empty() { + let why = match mode { + CutMode::KeepSilence => format!("the silence covers all of {name}, so there is no speech to cut"), + _ => format!("all ≤ keep ({keep} s)"), + }; return Reply::ok(format!( - "{} silence(s) found on {name}, all ≤ keep ({keep} s); nothing cut{other_lanes}", + "{} silence(s) found on {name}, {why}; nothing cut{other_lanes}", found.regions.len() )) .with(json!({ @@ -1657,7 +1793,11 @@ fn run_cut_silence(srv: &mut Server, args: &Value) -> Reply { // Each span is cut as found: its edges are inside the silence, so no kept sliver of speech // lies between two spans for the edit's sliver join to delete. let shape0 = super::edit::shape(s); - if let Err(e) = s.cut_regions(&spans, &scope) { + let applied = match mode { + CutMode::SpeedUp => s.speed_regions(&spans, speed, &scope), + _ => s.cut_regions(&spans, &scope), + }; + if let Err(e) = applied { let rolled = roll_back_cut(srv, start, trial); srv.trim_ledger(); keep_clean_marks(srv, was_clean); @@ -1666,10 +1806,13 @@ fn run_cut_silence(srv: &mut Server, args: &Value) -> Reply { } else { " (could not roll every step back; check the project)" }; - return fail(format!("cut refused: {e}; nothing changed{note}")); + let verb = if mode == CutMode::SpeedUp { "speed refused" } else { "cut refused" }; + return fail(format!("{verb}: {e}; nothing changed{note}")); } - // Titles move with the cut as they do for cut_regions, and the reply names what the cut left behind. - let moved = if super::edit::has_picture(&scope) { + // Titles move with a cut as they do for cut_regions. A speed-up closes only part of each silence's + // room, which moves the later titles by an amount move_titles_for_cuts does not model, so they keep + // their times there. + let moved = if mode != CutMode::SpeedUp && super::edit::has_picture(&scope) { match super::edit::move_titles_for_cuts(s, &spans, fps) { Ok(m) => m, Err(e) => { @@ -1697,9 +1840,11 @@ fn run_cut_silence(srv: &mut Server, args: &Value) -> Reply { let lanes_after = super::listen::media_end(s, &scope); let sound_after = sound_frames(s, &scope); // The pause actually left, read back from the sound after the cut and before any undo below. - let pauses = match &target { - Some(t) => measured_cut_pauses(s, t, &spans, cfg, fps), - None => measured_joint_pauses(s, &judged, &spans, fps), + // A pause is what a cut leaves; a speed-up or a kept silence leaves none to measure. + let pauses = match (mode, &target) { + (CutMode::Cut, Some(t)) => measured_cut_pauses(s, t, &spans, cfg, fps), + (CutMode::Cut, None) => measured_joint_pauses(s, &judged, &spans, fps), + _ => Ok(Vec::new()), }; // Measured on the cut lanes: a cut on A1 alone shortens A1 even when a longer lane sets the timeline end. let removed = lanes_before.saturating_sub(lanes_after); @@ -1714,7 +1859,9 @@ fn run_cut_silence(srv: &mut Server, args: &Value) -> Reply { } else { 0.0 }; - if !force && share > CUT_SHARE_LIMIT { + // The guard is for a cut that takes sound away by accident. A speed-up removes none, and keep_silence + // removes the speech on purpose, so neither is limited by it. + if mode == CutMode::Cut && !force && share > CUT_SHARE_LIMIT { let rolled = roll_back_cut(srv, start, trial); srv.trim_ledger(); keep_clean_marks(srv, was_clean); @@ -1740,11 +1887,20 @@ fn run_cut_silence(srv: &mut Server, args: &Value) -> Reply { keep_clean_marks(srv, was_clean); } // `s` is not used past this point, so the ledger can be written. + // The count phrase and the verbs for this mode: a kept silence counts the speech it cuts. + let counted = match mode { + CutMode::KeepSilence => format!("{} speech stretch(es) between {} silence(s)", spans.len(), found.regions.len()), + _ => format!("{} of {} silence(s)", spans.len(), found.regions.len()), + }; + let rate_txt = format!("{:.2}x", f64::from(speed.permille()) / 1000.0); + let (dry_verb, done_verb) = match mode { + CutMode::Cut => ("would cut".to_string(), "cut".to_string()), + CutMode::SpeedUp => (format!("would speed up to {rate_txt}"), format!("sped up to {rate_txt}")), + CutMode::KeepSilence => ("would cut the speech out".to_string(), "cut the speech out".to_string()), + }; let head = if dry { format!( - "dry run — would cut {} of {} silence(s) from {lanes_named}, and would remove {removed_secs:.3} s (the timeline's loss, not the silence found); timeline {:.3} s → {:.3} s; nothing changed{note}", - spans.len(), - found.regions.len(), + "dry run — {dry_verb} {counted} from {lanes_named}, and would remove {removed_secs:.3} s (the timeline's loss, not the silence found); timeline {:.3} s → {:.3} s; nothing changed{note}", parse::secs(end_before, fps), parse::secs(end_after, fps), ) @@ -1755,9 +1911,7 @@ fn run_cut_silence(srv: &mut Server, args: &Value) -> Reply { format!("cut_silence {name} ({} regions)", spans.len()), ); format!( - "cut {} of {} silence(s) from {lanes_named}, {removed_secs:.3} s removed; timeline {:.3} s → {:.3} s ({end_after}f) · undo step {}", - spans.len(), - found.regions.len(), + "{done_verb} {counted} from {lanes_named}, {removed_secs:.3} s removed; timeline {:.3} s → {:.3} s ({end_after}f) · undo step {}", parse::secs(end_before, fps), parse::secs(end_after, fps), srv.ledger.len(), @@ -1792,7 +1946,9 @@ fn run_cut_silence(srv: &mut Server, args: &Value) -> Reply { Ok(_) => "none (no cut joints)".to_string(), Err(e) => format!("not measured ({e})"), }; - text.push_str(&format!(" · pauses now {pause_note} (measured after the cut on {name})")); + if mode == CutMode::Cut { + text.push_str(&format!(" · pauses now {pause_note} (measured after the cut on {name})")); + } if let Some(note) = &thr_note { text.push_str(&format!("\nthreshold: {note}")); }